xref: /openbmc/linux/mm/vmscan.c (revision d43006d503ac921c7df4f94d13c17db6f13c9d26)
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,
679*d43006d5SMel 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;
686*d43006d5SMel 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 
727c661b078SAndy Whitcroft 		if (PageWriteback(page)) {
728e62e384eSMichal Hocko 			/*
729e62e384eSMichal Hocko 			 * memcg doesn't have any dirty pages throttling so we
730e62e384eSMichal Hocko 			 * could easily OOM just because too many pages are in
731c3b94f44SHugh Dickins 			 * writeback and there is nothing else to reclaim.
732e62e384eSMichal Hocko 			 *
733c3b94f44SHugh Dickins 			 * Check __GFP_IO, certainly because a loop driver
734e62e384eSMichal Hocko 			 * thread might enter reclaim, and deadlock if it waits
735e62e384eSMichal Hocko 			 * on a page for which it is needed to do the write
736e62e384eSMichal Hocko 			 * (loop masks off __GFP_IO|__GFP_FS for this reason);
737e62e384eSMichal Hocko 			 * but more thought would probably show more reasons.
738c3b94f44SHugh Dickins 			 *
739c3b94f44SHugh Dickins 			 * Don't require __GFP_FS, since we're not going into
740c3b94f44SHugh Dickins 			 * the FS, just waiting on its writeback completion.
741c3b94f44SHugh Dickins 			 * Worryingly, ext4 gfs2 and xfs allocate pages with
742c3b94f44SHugh Dickins 			 * grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so
743c3b94f44SHugh Dickins 			 * testing may_enter_fs here is liable to OOM on them.
744e62e384eSMichal Hocko 			 */
745c3b94f44SHugh Dickins 			if (global_reclaim(sc) ||
746c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
747c3b94f44SHugh Dickins 				/*
748c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
749c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
750c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
751c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
752c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
753c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
754c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
755c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
756c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
757c3b94f44SHugh Dickins 				 */
758c3b94f44SHugh Dickins 				SetPageReclaim(page);
75992df3a72SMel Gorman 				nr_writeback++;
760c3b94f44SHugh Dickins 				goto keep_locked;
761c661b078SAndy Whitcroft 			}
762c3b94f44SHugh Dickins 			wait_on_page_writeback(page);
763e62e384eSMichal Hocko 		}
7641da177e4SLinus Torvalds 
76502c6de8dSMinchan Kim 		if (!force_reclaim)
7666a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
76702c6de8dSMinchan Kim 
768dfc8d636SJohannes Weiner 		switch (references) {
769dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
7701da177e4SLinus Torvalds 			goto activate_locked;
77164574746SJohannes Weiner 		case PAGEREF_KEEP:
77264574746SJohannes Weiner 			goto keep_locked;
773dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
774dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
775dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
776dfc8d636SJohannes Weiner 		}
7771da177e4SLinus Torvalds 
7781da177e4SLinus Torvalds 		/*
7791da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
7801da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
7811da177e4SLinus Torvalds 		 */
782b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
78363eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
78463eb6b93SHugh Dickins 				goto keep_locked;
7855bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
7861da177e4SLinus Torvalds 				goto activate_locked;
78763eb6b93SHugh Dickins 			may_enter_fs = 1;
788b291f000SNick Piggin 		}
7891da177e4SLinus Torvalds 
7901da177e4SLinus Torvalds 		mapping = page_mapping(page);
7911da177e4SLinus Torvalds 
7921da177e4SLinus Torvalds 		/*
7931da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
7941da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
7951da177e4SLinus Torvalds 		 */
7961da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
79702c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
7981da177e4SLinus Torvalds 			case SWAP_FAIL:
7991da177e4SLinus Torvalds 				goto activate_locked;
8001da177e4SLinus Torvalds 			case SWAP_AGAIN:
8011da177e4SLinus Torvalds 				goto keep_locked;
802b291f000SNick Piggin 			case SWAP_MLOCK:
803b291f000SNick Piggin 				goto cull_mlocked;
8041da177e4SLinus Torvalds 			case SWAP_SUCCESS:
8051da177e4SLinus Torvalds 				; /* try to free the page below */
8061da177e4SLinus Torvalds 			}
8071da177e4SLinus Torvalds 		}
8081da177e4SLinus Torvalds 
8091da177e4SLinus Torvalds 		if (PageDirty(page)) {
8100e093d99SMel Gorman 			nr_dirty++;
8110e093d99SMel Gorman 
812*d43006d5SMel Gorman 			if (!PageWriteback(page))
813*d43006d5SMel Gorman 				nr_unqueued_dirty++;
814*d43006d5SMel Gorman 
815ee72886dSMel Gorman 			/*
816ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
817*d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
818*d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
819ee72886dSMel Gorman 			 */
820f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
8219e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
822*d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
82349ea7eb6SMel Gorman 				/*
82449ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
82549ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
82649ea7eb6SMel Gorman 				 * except we already have the page isolated
82749ea7eb6SMel Gorman 				 * and know it's dirty
82849ea7eb6SMel Gorman 				 */
82949ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
83049ea7eb6SMel Gorman 				SetPageReclaim(page);
83149ea7eb6SMel Gorman 
832ee72886dSMel Gorman 				goto keep_locked;
833ee72886dSMel Gorman 			}
834ee72886dSMel Gorman 
835dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
8361da177e4SLinus Torvalds 				goto keep_locked;
8374dd4b920SAndrew Morton 			if (!may_enter_fs)
8381da177e4SLinus Torvalds 				goto keep_locked;
83952a8363eSChristoph Lameter 			if (!sc->may_writepage)
8401da177e4SLinus Torvalds 				goto keep_locked;
8411da177e4SLinus Torvalds 
8421da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
8437d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
8441da177e4SLinus Torvalds 			case PAGE_KEEP:
8450e093d99SMel Gorman 				nr_congested++;
8461da177e4SLinus Torvalds 				goto keep_locked;
8471da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
8481da177e4SLinus Torvalds 				goto activate_locked;
8491da177e4SLinus Torvalds 			case PAGE_SUCCESS:
8507d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
85141ac1999SMel Gorman 					goto keep;
8527d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
8531da177e4SLinus Torvalds 					goto keep;
8547d3579e8SKOSAKI Motohiro 
8551da177e4SLinus Torvalds 				/*
8561da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
8571da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
8581da177e4SLinus Torvalds 				 */
859529ae9aaSNick Piggin 				if (!trylock_page(page))
8601da177e4SLinus Torvalds 					goto keep;
8611da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
8621da177e4SLinus Torvalds 					goto keep_locked;
8631da177e4SLinus Torvalds 				mapping = page_mapping(page);
8641da177e4SLinus Torvalds 			case PAGE_CLEAN:
8651da177e4SLinus Torvalds 				; /* try to free the page below */
8661da177e4SLinus Torvalds 			}
8671da177e4SLinus Torvalds 		}
8681da177e4SLinus Torvalds 
8691da177e4SLinus Torvalds 		/*
8701da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
8711da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
8721da177e4SLinus Torvalds 		 * the page as well.
8731da177e4SLinus Torvalds 		 *
8741da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
8751da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
8761da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
8771da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
8781da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
8791da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
8801da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
8811da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
8821da177e4SLinus Torvalds 		 *
8831da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
8841da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
8851da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
8861da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
8871da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
8881da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
8891da177e4SLinus Torvalds 		 */
890266cf658SDavid Howells 		if (page_has_private(page)) {
8911da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
8921da177e4SLinus Torvalds 				goto activate_locked;
893e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
894e286781dSNick Piggin 				unlock_page(page);
895e286781dSNick Piggin 				if (put_page_testzero(page))
8961da177e4SLinus Torvalds 					goto free_it;
897e286781dSNick Piggin 				else {
898e286781dSNick Piggin 					/*
899e286781dSNick Piggin 					 * rare race with speculative reference.
900e286781dSNick Piggin 					 * the speculative reference will free
901e286781dSNick Piggin 					 * this page shortly, so we may
902e286781dSNick Piggin 					 * increment nr_reclaimed here (and
903e286781dSNick Piggin 					 * leave it off the LRU).
904e286781dSNick Piggin 					 */
905e286781dSNick Piggin 					nr_reclaimed++;
906e286781dSNick Piggin 					continue;
907e286781dSNick Piggin 				}
908e286781dSNick Piggin 			}
9091da177e4SLinus Torvalds 		}
9101da177e4SLinus Torvalds 
911e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
91249d2e9ccSChristoph Lameter 			goto keep_locked;
9131da177e4SLinus Torvalds 
914a978d6f5SNick Piggin 		/*
915a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
916a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
917a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
918a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
919a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
920a978d6f5SNick Piggin 		 */
921a978d6f5SNick Piggin 		__clear_page_locked(page);
922e286781dSNick Piggin free_it:
92305ff5137SAndrew Morton 		nr_reclaimed++;
924abe4c3b5SMel Gorman 
925abe4c3b5SMel Gorman 		/*
926abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
927abe4c3b5SMel Gorman 		 * appear not as the counts should be low
928abe4c3b5SMel Gorman 		 */
929abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
9301da177e4SLinus Torvalds 		continue;
9311da177e4SLinus Torvalds 
932b291f000SNick Piggin cull_mlocked:
93363d6c5adSHugh Dickins 		if (PageSwapCache(page))
93463d6c5adSHugh Dickins 			try_to_free_swap(page);
935b291f000SNick Piggin 		unlock_page(page);
936b291f000SNick Piggin 		putback_lru_page(page);
937b291f000SNick Piggin 		continue;
938b291f000SNick Piggin 
9391da177e4SLinus Torvalds activate_locked:
94068a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
94168a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
942a2c43eedSHugh Dickins 			try_to_free_swap(page);
943894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
9441da177e4SLinus Torvalds 		SetPageActive(page);
9451da177e4SLinus Torvalds 		pgactivate++;
9461da177e4SLinus Torvalds keep_locked:
9471da177e4SLinus Torvalds 		unlock_page(page);
9481da177e4SLinus Torvalds keep:
9491da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
950b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
9511da177e4SLinus Torvalds 	}
952abe4c3b5SMel Gorman 
9530e093d99SMel Gorman 	/*
9540e093d99SMel Gorman 	 * Tag a zone as congested if all the dirty pages encountered were
9550e093d99SMel Gorman 	 * backed by a congested BDI. In this case, reclaimers should just
9560e093d99SMel Gorman 	 * back off and wait for congestion to clear because further reclaim
9570e093d99SMel Gorman 	 * will encounter the same problem
9580e093d99SMel Gorman 	 */
95989b5fae5SJohannes Weiner 	if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
9606a18adb3SKonstantin Khlebnikov 		zone_set_flag(zone, ZONE_CONGESTED);
9610e093d99SMel Gorman 
962cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
963abe4c3b5SMel Gorman 
9641da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
965f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
96669980e31STim Chen 	mem_cgroup_uncharge_end();
967*d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
96892df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
96905ff5137SAndrew Morton 	return nr_reclaimed;
9701da177e4SLinus Torvalds }
9711da177e4SLinus Torvalds 
97202c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
97302c6de8dSMinchan Kim 					    struct list_head *page_list)
97402c6de8dSMinchan Kim {
97502c6de8dSMinchan Kim 	struct scan_control sc = {
97602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
97702c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
97802c6de8dSMinchan Kim 		.may_unmap = 1,
97902c6de8dSMinchan Kim 	};
98002c6de8dSMinchan Kim 	unsigned long ret, dummy1, dummy2;
98102c6de8dSMinchan Kim 	struct page *page, *next;
98202c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
98302c6de8dSMinchan Kim 
98402c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
98502c6de8dSMinchan Kim 		if (page_is_file_cache(page) && !PageDirty(page)) {
98602c6de8dSMinchan Kim 			ClearPageActive(page);
98702c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
98802c6de8dSMinchan Kim 		}
98902c6de8dSMinchan Kim 	}
99002c6de8dSMinchan Kim 
99102c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
99202c6de8dSMinchan Kim 				TTU_UNMAP|TTU_IGNORE_ACCESS,
99302c6de8dSMinchan Kim 				&dummy1, &dummy2, true);
99402c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
99502c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
99602c6de8dSMinchan Kim 	return ret;
99702c6de8dSMinchan Kim }
99802c6de8dSMinchan Kim 
9995ad333ebSAndy Whitcroft /*
10005ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
10015ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
10025ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
10035ad333ebSAndy Whitcroft  *
10045ad333ebSAndy Whitcroft  * page:	page to consider
10055ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
10065ad333ebSAndy Whitcroft  *
10075ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
10085ad333ebSAndy Whitcroft  */
1009f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
10105ad333ebSAndy Whitcroft {
10115ad333ebSAndy Whitcroft 	int ret = -EINVAL;
10125ad333ebSAndy Whitcroft 
10135ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
10145ad333ebSAndy Whitcroft 	if (!PageLRU(page))
10155ad333ebSAndy Whitcroft 		return ret;
10165ad333ebSAndy Whitcroft 
1017e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1018e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1019894bc310SLee Schermerhorn 		return ret;
1020894bc310SLee Schermerhorn 
10215ad333ebSAndy Whitcroft 	ret = -EBUSY;
102208e552c6SKAMEZAWA Hiroyuki 
1023c8244935SMel Gorman 	/*
1024c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1025c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1026c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1027c8244935SMel Gorman 	 *
1028c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1029c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1030c8244935SMel Gorman 	 *
1031c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1032c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1033c8244935SMel Gorman 	 */
1034c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1035c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1036c8244935SMel Gorman 		if (PageWriteback(page))
103739deaf85SMinchan Kim 			return ret;
103839deaf85SMinchan Kim 
1039c8244935SMel Gorman 		if (PageDirty(page)) {
1040c8244935SMel Gorman 			struct address_space *mapping;
1041c8244935SMel Gorman 
1042c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1043c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1044c8244935SMel Gorman 				return ret;
1045c8244935SMel Gorman 
1046c8244935SMel Gorman 			/*
1047c8244935SMel Gorman 			 * Only pages without mappings or that have a
1048c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1049c8244935SMel Gorman 			 * without blocking
1050c8244935SMel Gorman 			 */
1051c8244935SMel Gorman 			mapping = page_mapping(page);
1052c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1053c8244935SMel Gorman 				return ret;
1054c8244935SMel Gorman 		}
1055c8244935SMel Gorman 	}
1056c8244935SMel Gorman 
1057f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1058f80c0673SMinchan Kim 		return ret;
1059f80c0673SMinchan Kim 
10605ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
10615ad333ebSAndy Whitcroft 		/*
10625ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
10635ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
10645ad333ebSAndy Whitcroft 		 * page release code relies on it.
10655ad333ebSAndy Whitcroft 		 */
10665ad333ebSAndy Whitcroft 		ClearPageLRU(page);
10675ad333ebSAndy Whitcroft 		ret = 0;
10685ad333ebSAndy Whitcroft 	}
10695ad333ebSAndy Whitcroft 
10705ad333ebSAndy Whitcroft 	return ret;
10715ad333ebSAndy Whitcroft }
10725ad333ebSAndy Whitcroft 
107349d2e9ccSChristoph Lameter /*
10741da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
10751da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
10761da177e4SLinus Torvalds  * and working on them outside the LRU lock.
10771da177e4SLinus Torvalds  *
10781da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
10791da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
10801da177e4SLinus Torvalds  *
10811da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
10821da177e4SLinus Torvalds  *
10831da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
10845dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
10851da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1086f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1087fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
10885ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
10893cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
10901da177e4SLinus Torvalds  *
10911da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
10921da177e4SLinus Torvalds  */
109369e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
10945dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1095fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
10963cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
10971da177e4SLinus Torvalds {
109875b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
109969e05944SAndrew Morton 	unsigned long nr_taken = 0;
1100c9b02d97SWu Fengguang 	unsigned long scan;
11011da177e4SLinus Torvalds 
1102c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
11035ad333ebSAndy Whitcroft 		struct page *page;
1104fa9add64SHugh Dickins 		int nr_pages;
11055ad333ebSAndy Whitcroft 
11061da177e4SLinus Torvalds 		page = lru_to_page(src);
11071da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
11081da177e4SLinus Torvalds 
1109725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
11108d438f96SNick Piggin 
1111f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
11125ad333ebSAndy Whitcroft 		case 0:
1113fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1114fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
11155ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1116fa9add64SHugh Dickins 			nr_taken += nr_pages;
11175ad333ebSAndy Whitcroft 			break;
11187c8ee9a8SNick Piggin 
11195ad333ebSAndy Whitcroft 		case -EBUSY:
11205ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
11215ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
11225ad333ebSAndy Whitcroft 			continue;
11235ad333ebSAndy Whitcroft 
11245ad333ebSAndy Whitcroft 		default:
11255ad333ebSAndy Whitcroft 			BUG();
11265ad333ebSAndy Whitcroft 		}
11275ad333ebSAndy Whitcroft 	}
11281da177e4SLinus Torvalds 
1129f626012dSHugh Dickins 	*nr_scanned = scan;
113075b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
113175b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
11321da177e4SLinus Torvalds 	return nr_taken;
11331da177e4SLinus Torvalds }
11341da177e4SLinus Torvalds 
113562695a84SNick Piggin /**
113662695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
113762695a84SNick Piggin  * @page: page to isolate from its LRU list
113862695a84SNick Piggin  *
113962695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
114062695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
114162695a84SNick Piggin  *
114262695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
114362695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
114462695a84SNick Piggin  *
114562695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1146894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1147894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1148894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
114962695a84SNick Piggin  *
115062695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
115162695a84SNick Piggin  * found will be decremented.
115262695a84SNick Piggin  *
115362695a84SNick Piggin  * Restrictions:
115462695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
115562695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
115662695a84SNick Piggin  *     without a stable reference).
115762695a84SNick Piggin  * (2) the lru_lock must not be held.
115862695a84SNick Piggin  * (3) interrupts must be enabled.
115962695a84SNick Piggin  */
116062695a84SNick Piggin int isolate_lru_page(struct page *page)
116162695a84SNick Piggin {
116262695a84SNick Piggin 	int ret = -EBUSY;
116362695a84SNick Piggin 
11640c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
11650c917313SKonstantin Khlebnikov 
116662695a84SNick Piggin 	if (PageLRU(page)) {
116762695a84SNick Piggin 		struct zone *zone = page_zone(page);
1168fa9add64SHugh Dickins 		struct lruvec *lruvec;
116962695a84SNick Piggin 
117062695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1171fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
11720c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1173894bc310SLee Schermerhorn 			int lru = page_lru(page);
11740c917313SKonstantin Khlebnikov 			get_page(page);
117562695a84SNick Piggin 			ClearPageLRU(page);
1176fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1177fa9add64SHugh Dickins 			ret = 0;
117862695a84SNick Piggin 		}
117962695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
118062695a84SNick Piggin 	}
118162695a84SNick Piggin 	return ret;
118262695a84SNick Piggin }
118362695a84SNick Piggin 
11845ad333ebSAndy Whitcroft /*
1185d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1186d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1187d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1188d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1189d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
119035cd7815SRik van Riel  */
119135cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
119235cd7815SRik van Riel 		struct scan_control *sc)
119335cd7815SRik van Riel {
119435cd7815SRik van Riel 	unsigned long inactive, isolated;
119535cd7815SRik van Riel 
119635cd7815SRik van Riel 	if (current_is_kswapd())
119735cd7815SRik van Riel 		return 0;
119835cd7815SRik van Riel 
119989b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
120035cd7815SRik van Riel 		return 0;
120135cd7815SRik van Riel 
120235cd7815SRik van Riel 	if (file) {
120335cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
120435cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
120535cd7815SRik van Riel 	} else {
120635cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
120735cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
120835cd7815SRik van Riel 	}
120935cd7815SRik van Riel 
12103cf23841SFengguang Wu 	/*
12113cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
12123cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
12133cf23841SFengguang Wu 	 * deadlock.
12143cf23841SFengguang Wu 	 */
12153cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
12163cf23841SFengguang Wu 		inactive >>= 3;
12173cf23841SFengguang Wu 
121835cd7815SRik van Riel 	return isolated > inactive;
121935cd7815SRik van Riel }
122035cd7815SRik van Riel 
122166635629SMel Gorman static noinline_for_stack void
122275b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
122366635629SMel Gorman {
122427ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
122527ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
12263f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
122766635629SMel Gorman 
122866635629SMel Gorman 	/*
122966635629SMel Gorman 	 * Put back any unfreeable pages.
123066635629SMel Gorman 	 */
123166635629SMel Gorman 	while (!list_empty(page_list)) {
12323f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
123366635629SMel Gorman 		int lru;
12343f79768fSHugh Dickins 
123566635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
123666635629SMel Gorman 		list_del(&page->lru);
123739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
123866635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
123966635629SMel Gorman 			putback_lru_page(page);
124066635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
124166635629SMel Gorman 			continue;
124266635629SMel Gorman 		}
1243fa9add64SHugh Dickins 
1244fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1245fa9add64SHugh Dickins 
12467a608572SLinus Torvalds 		SetPageLRU(page);
124766635629SMel Gorman 		lru = page_lru(page);
1248fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1249fa9add64SHugh Dickins 
125066635629SMel Gorman 		if (is_active_lru(lru)) {
125166635629SMel Gorman 			int file = is_file_lru(lru);
12529992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
12539992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
125466635629SMel Gorman 		}
12552bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
12562bcf8879SHugh Dickins 			__ClearPageLRU(page);
12572bcf8879SHugh Dickins 			__ClearPageActive(page);
1258fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
12592bcf8879SHugh Dickins 
12602bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
126166635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
12622bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
126366635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
12642bcf8879SHugh Dickins 			} else
12652bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
126666635629SMel Gorman 		}
126766635629SMel Gorman 	}
126866635629SMel Gorman 
12693f79768fSHugh Dickins 	/*
12703f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
12713f79768fSHugh Dickins 	 */
12723f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
127366635629SMel Gorman }
127466635629SMel Gorman 
127566635629SMel Gorman /*
12761742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
12771742f19fSAndrew Morton  * of reclaimed pages
12781da177e4SLinus Torvalds  */
127966635629SMel Gorman static noinline_for_stack unsigned long
12801a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
12819e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
12821da177e4SLinus Torvalds {
12831da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1284e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
128505ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1286e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
128792df3a72SMel Gorman 	unsigned long nr_dirty = 0;
128892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1289f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
12903cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
12911a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
12921a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
129378dc583dSKOSAKI Motohiro 
129435cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
129558355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
129635cd7815SRik van Riel 
129735cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
129835cd7815SRik van Riel 		if (fatal_signal_pending(current))
129935cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
130035cd7815SRik van Riel 	}
130135cd7815SRik van Riel 
13021da177e4SLinus Torvalds 	lru_add_drain();
1303f80c0673SMinchan Kim 
1304f80c0673SMinchan Kim 	if (!sc->may_unmap)
130561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1306f80c0673SMinchan Kim 	if (!sc->may_writepage)
130761317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1308f80c0673SMinchan Kim 
13091da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
13101da177e4SLinus Torvalds 
13115dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
13125dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
131395d918fcSKonstantin Khlebnikov 
131495d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
131595d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
131695d918fcSKonstantin Khlebnikov 
131789b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1318e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1319b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
132075b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1321b35ea17bSKOSAKI Motohiro 		else
132275b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1323b35ea17bSKOSAKI Motohiro 	}
132466635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1325d563c050SHillf Danton 
1326d563c050SHillf Danton 	if (nr_taken == 0)
132766635629SMel Gorman 		return 0;
1328b35ea17bSKOSAKI Motohiro 
132902c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
133002c6de8dSMinchan Kim 					&nr_dirty, &nr_writeback, false);
1331c661b078SAndy Whitcroft 
13323f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
13333f79768fSHugh Dickins 
133495d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1335d563c050SHillf Danton 
1336904249aaSYing Han 	if (global_reclaim(sc)) {
1337b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1338904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1339904249aaSYing Han 					       nr_reclaimed);
1340904249aaSYing Han 		else
1341904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1342904249aaSYing Han 					       nr_reclaimed);
1343904249aaSYing Han 	}
1344a74609faSNick Piggin 
134527ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
13463f79768fSHugh Dickins 
134795d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
13483f79768fSHugh Dickins 
13493f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
13503f79768fSHugh Dickins 
13513f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1352e11da5b4SMel Gorman 
135392df3a72SMel Gorman 	/*
135492df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
135592df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
135692df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
135792df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
135892df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
135992df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
136092df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
136192df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
136292df3a72SMel Gorman 	 *
136392df3a72SMel Gorman 	 * This scales the number of dirty pages that must be under writeback
136492df3a72SMel Gorman 	 * before throttling depending on priority. It is a simple backoff
136592df3a72SMel Gorman 	 * function that has the most effect in the range DEF_PRIORITY to
136692df3a72SMel Gorman 	 * DEF_PRIORITY-2 which is the priority reclaim is considered to be
136792df3a72SMel Gorman 	 * in trouble and reclaim is considered to be in trouble.
136892df3a72SMel Gorman 	 *
136992df3a72SMel Gorman 	 * DEF_PRIORITY   100% isolated pages must be PageWriteback to throttle
137092df3a72SMel Gorman 	 * DEF_PRIORITY-1  50% must be PageWriteback
137192df3a72SMel Gorman 	 * DEF_PRIORITY-2  25% must be PageWriteback, kswapd in trouble
137292df3a72SMel Gorman 	 * ...
137392df3a72SMel Gorman 	 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
137492df3a72SMel Gorman 	 *                     isolated page is PageWriteback
137592df3a72SMel Gorman 	 */
13769e3b2f8cSKonstantin Khlebnikov 	if (nr_writeback && nr_writeback >=
13779e3b2f8cSKonstantin Khlebnikov 			(nr_taken >> (DEF_PRIORITY - sc->priority)))
137892df3a72SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
137992df3a72SMel Gorman 
1380*d43006d5SMel Gorman 	/*
1381*d43006d5SMel Gorman 	 * Similarly, if many dirty pages are encountered that are not
1382*d43006d5SMel Gorman 	 * currently being written then flag that kswapd should start
1383*d43006d5SMel Gorman 	 * writing back pages.
1384*d43006d5SMel Gorman 	 */
1385*d43006d5SMel Gorman 	if (global_reclaim(sc) && nr_dirty &&
1386*d43006d5SMel Gorman 			nr_dirty >= (nr_taken >> (DEF_PRIORITY - sc->priority)))
1387*d43006d5SMel Gorman 		zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1388*d43006d5SMel Gorman 
1389e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1390e11da5b4SMel Gorman 		zone_idx(zone),
1391e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
13929e3b2f8cSKonstantin Khlebnikov 		sc->priority,
139323b9da55SMel Gorman 		trace_shrink_flags(file));
139405ff5137SAndrew Morton 	return nr_reclaimed;
13951da177e4SLinus Torvalds }
13961da177e4SLinus Torvalds 
13973bb1a852SMartin Bligh /*
13981cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
13991cfb419bSKAMEZAWA Hiroyuki  *
14001cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
14011cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
14021cfb419bSKAMEZAWA Hiroyuki  *
14031cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
14041cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
14051cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
14061cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
14071cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
14081cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
14091cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
14101cfb419bSKAMEZAWA Hiroyuki  *
14111cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
14121cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
14131cfb419bSKAMEZAWA Hiroyuki  */
14141cfb419bSKAMEZAWA Hiroyuki 
1415fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
14163eb4140fSWu Fengguang 				     struct list_head *list,
14172bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
14183eb4140fSWu Fengguang 				     enum lru_list lru)
14193eb4140fSWu Fengguang {
1420fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
14213eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
14223eb4140fSWu Fengguang 	struct page *page;
1423fa9add64SHugh Dickins 	int nr_pages;
14243eb4140fSWu Fengguang 
14253eb4140fSWu Fengguang 	while (!list_empty(list)) {
14263eb4140fSWu Fengguang 		page = lru_to_page(list);
1427fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
14283eb4140fSWu Fengguang 
14293eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
14303eb4140fSWu Fengguang 		SetPageLRU(page);
14313eb4140fSWu Fengguang 
1432fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1433fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1434925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1435fa9add64SHugh Dickins 		pgmoved += nr_pages;
14363eb4140fSWu Fengguang 
14372bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
14382bcf8879SHugh Dickins 			__ClearPageLRU(page);
14392bcf8879SHugh Dickins 			__ClearPageActive(page);
1440fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
14412bcf8879SHugh Dickins 
14422bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
14433eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
14442bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
14453eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
14462bcf8879SHugh Dickins 			} else
14472bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
14483eb4140fSWu Fengguang 		}
14493eb4140fSWu Fengguang 	}
14503eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
14513eb4140fSWu Fengguang 	if (!is_active_lru(lru))
14523eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
14533eb4140fSWu Fengguang }
14541cfb419bSKAMEZAWA Hiroyuki 
1455f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
14561a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1457f16015fbSJohannes Weiner 			       struct scan_control *sc,
14589e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
14591cfb419bSKAMEZAWA Hiroyuki {
146044c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1461f626012dSHugh Dickins 	unsigned long nr_scanned;
14626fe6b7e3SWu Fengguang 	unsigned long vm_flags;
14631cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
14648cab4754SWu Fengguang 	LIST_HEAD(l_active);
1465b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
14661cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
14671a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
146844c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1469f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
14703cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
14711a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14721cfb419bSKAMEZAWA Hiroyuki 
14731da177e4SLinus Torvalds 	lru_add_drain();
1474f80c0673SMinchan Kim 
1475f80c0673SMinchan Kim 	if (!sc->may_unmap)
147661317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1477f80c0673SMinchan Kim 	if (!sc->may_writepage)
147861317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1479f80c0673SMinchan Kim 
14801da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1481925b7673SJohannes Weiner 
14825dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
14835dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
148489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1485f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
148689b5fae5SJohannes Weiner 
1487b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
14881cfb419bSKAMEZAWA Hiroyuki 
1489f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
14903cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1491a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
14921da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
14931da177e4SLinus Torvalds 
14941da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
14951da177e4SLinus Torvalds 		cond_resched();
14961da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
14971da177e4SLinus Torvalds 		list_del(&page->lru);
14987e9cd484SRik van Riel 
149939b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1500894bc310SLee Schermerhorn 			putback_lru_page(page);
1501894bc310SLee Schermerhorn 			continue;
1502894bc310SLee Schermerhorn 		}
1503894bc310SLee Schermerhorn 
1504cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1505cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1506cc715d99SMel Gorman 				if (page_has_private(page))
1507cc715d99SMel Gorman 					try_to_release_page(page, 0);
1508cc715d99SMel Gorman 				unlock_page(page);
1509cc715d99SMel Gorman 			}
1510cc715d99SMel Gorman 		}
1511cc715d99SMel Gorman 
1512c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1513c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
15149992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
15158cab4754SWu Fengguang 			/*
15168cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
15178cab4754SWu Fengguang 			 * give them one more trip around the active list. So
15188cab4754SWu Fengguang 			 * that executable code get better chances to stay in
15198cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
15208cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
15218cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
15228cab4754SWu Fengguang 			 * so we ignore them here.
15238cab4754SWu Fengguang 			 */
152441e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
15258cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
15268cab4754SWu Fengguang 				continue;
15278cab4754SWu Fengguang 			}
15288cab4754SWu Fengguang 		}
15297e9cd484SRik van Riel 
15305205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
15311da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
15321da177e4SLinus Torvalds 	}
15331da177e4SLinus Torvalds 
1534b555749aSAndrew Morton 	/*
15358cab4754SWu Fengguang 	 * Move pages back to the lru list.
1536b555749aSAndrew Morton 	 */
15372a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
15384f98a2feSRik van Riel 	/*
15398cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
15408cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
15418cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
15428cab4754SWu Fengguang 	 * get_scan_ratio.
1543556adecbSRik van Riel 	 */
1544b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1545556adecbSRik van Riel 
1546fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1547fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1548a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1549f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
15502bcf8879SHugh Dickins 
15512bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
15521da177e4SLinus Torvalds }
15531da177e4SLinus Torvalds 
155474e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
155514797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1556f89eb90eSKOSAKI Motohiro {
1557f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1558f89eb90eSKOSAKI Motohiro 
1559f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1560f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1561f89eb90eSKOSAKI Motohiro 
1562f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1563f89eb90eSKOSAKI Motohiro 		return 1;
1564f89eb90eSKOSAKI Motohiro 
1565f89eb90eSKOSAKI Motohiro 	return 0;
1566f89eb90eSKOSAKI Motohiro }
1567f89eb90eSKOSAKI Motohiro 
156814797e23SKOSAKI Motohiro /**
156914797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1570c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
157114797e23SKOSAKI Motohiro  *
157214797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
157314797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
157414797e23SKOSAKI Motohiro  */
1575c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
157614797e23SKOSAKI Motohiro {
157774e3f3c3SMinchan Kim 	/*
157874e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
157974e3f3c3SMinchan Kim 	 * is pointless.
158074e3f3c3SMinchan Kim 	 */
158174e3f3c3SMinchan Kim 	if (!total_swap_pages)
158274e3f3c3SMinchan Kim 		return 0;
158374e3f3c3SMinchan Kim 
1584c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1585c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1586f16015fbSJohannes Weiner 
1587c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
158814797e23SKOSAKI Motohiro }
158974e3f3c3SMinchan Kim #else
1590c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
159174e3f3c3SMinchan Kim {
159274e3f3c3SMinchan Kim 	return 0;
159374e3f3c3SMinchan Kim }
159474e3f3c3SMinchan Kim #endif
159514797e23SKOSAKI Motohiro 
159656e49d21SRik van Riel /**
159756e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1598c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
159956e49d21SRik van Riel  *
160056e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
160156e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
160256e49d21SRik van Riel  * than half of the file pages are on the inactive list.
160356e49d21SRik van Riel  *
160456e49d21SRik van Riel  * Once we get to that situation, protect the system's working
160556e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
160656e49d21SRik van Riel  *
160756e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
160856e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
160956e49d21SRik van Riel  */
1610c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
161156e49d21SRik van Riel {
1612e3790144SJohannes Weiner 	unsigned long inactive;
1613e3790144SJohannes Weiner 	unsigned long active;
161456e49d21SRik van Riel 
1615e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1616e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1617e3790144SJohannes Weiner 
1618e3790144SJohannes Weiner 	return active > inactive;
161956e49d21SRik van Riel }
162056e49d21SRik van Riel 
162175b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1622b39415b2SRik van Riel {
162375b00af7SHugh Dickins 	if (is_file_lru(lru))
1624c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1625b39415b2SRik van Riel 	else
1626c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1627b39415b2SRik van Riel }
1628b39415b2SRik van Riel 
16294f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
16301a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1631b69408e8SChristoph Lameter {
1632b39415b2SRik van Riel 	if (is_active_lru(lru)) {
163375b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
16341a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1635556adecbSRik van Riel 		return 0;
1636556adecbSRik van Riel 	}
1637556adecbSRik van Riel 
16381a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1639b69408e8SChristoph Lameter }
1640b69408e8SChristoph Lameter 
16413d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
16421f4c025bSKAMEZAWA Hiroyuki {
164389b5fae5SJohannes Weiner 	if (global_reclaim(sc))
16441f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
16453d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
16461f4c025bSKAMEZAWA Hiroyuki }
16471f4c025bSKAMEZAWA Hiroyuki 
16489a265114SJohannes Weiner enum scan_balance {
16499a265114SJohannes Weiner 	SCAN_EQUAL,
16509a265114SJohannes Weiner 	SCAN_FRACT,
16519a265114SJohannes Weiner 	SCAN_ANON,
16529a265114SJohannes Weiner 	SCAN_FILE,
16539a265114SJohannes Weiner };
16549a265114SJohannes Weiner 
16551da177e4SLinus Torvalds /*
16564f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
16574f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
16584f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
16594f98a2feSRik van Riel  * onto the active list instead of evict.
16604f98a2feSRik van Riel  *
1661be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1662be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
16634f98a2feSRik van Riel  */
166490126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
16659e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
16664f98a2feSRik van Riel {
166790126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
16689a265114SJohannes Weiner 	u64 fraction[2];
16699a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
167090126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
16719a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
16729a265114SJohannes Weiner 	enum scan_balance scan_balance;
16739a265114SJohannes Weiner 	unsigned long anon, file, free;
16749a265114SJohannes Weiner 	bool force_scan = false;
16759a265114SJohannes Weiner 	unsigned long ap, fp;
16769a265114SJohannes Weiner 	enum lru_list lru;
1677246e87a9SKAMEZAWA Hiroyuki 
1678f11c0ca5SJohannes Weiner 	/*
1679f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1680f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1681f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1682f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1683f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1684f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1685f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1686f11c0ca5SJohannes Weiner 	 * well.
1687f11c0ca5SJohannes Weiner 	 */
168890126375SKonstantin Khlebnikov 	if (current_is_kswapd() && zone->all_unreclaimable)
1689a4d3e9e7SJohannes Weiner 		force_scan = true;
169089b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1691a4d3e9e7SJohannes Weiner 		force_scan = true;
169276a33fc3SShaohua Li 
169376a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1694ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
16959a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
169676a33fc3SShaohua Li 		goto out;
169776a33fc3SShaohua Li 	}
16984f98a2feSRik van Riel 
169910316b31SJohannes Weiner 	/*
170010316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
170110316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
170210316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
170310316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
170410316b31SJohannes Weiner 	 * too expensive.
170510316b31SJohannes Weiner 	 */
170610316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
17079a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
170810316b31SJohannes Weiner 		goto out;
170910316b31SJohannes Weiner 	}
171010316b31SJohannes Weiner 
171110316b31SJohannes Weiner 	/*
171210316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
171310316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
171410316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
171510316b31SJohannes Weiner 	 */
171610316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
17179a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
171810316b31SJohannes Weiner 		goto out;
171910316b31SJohannes Weiner 	}
172010316b31SJohannes Weiner 
17214d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
17224d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
17234d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
17244d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1725a4d3e9e7SJohannes Weiner 
172611d16c25SJohannes Weiner 	/*
172711d16c25SJohannes Weiner 	 * If it's foreseeable that reclaiming the file cache won't be
172811d16c25SJohannes Weiner 	 * enough to get the zone back into a desirable shape, we have
172911d16c25SJohannes Weiner 	 * to swap.  Better start now and leave the - probably heavily
173011d16c25SJohannes Weiner 	 * thrashing - remaining file pages alone.
173111d16c25SJohannes Weiner 	 */
173289b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
173390126375SKonstantin Khlebnikov 		free = zone_page_state(zone, NR_FREE_PAGES);
173490126375SKonstantin Khlebnikov 		if (unlikely(file + free <= high_wmark_pages(zone))) {
17359a265114SJohannes Weiner 			scan_balance = SCAN_ANON;
173676a33fc3SShaohua Li 			goto out;
17377c5bd705SJohannes Weiner 		}
17387c5bd705SJohannes Weiner 	}
17397c5bd705SJohannes Weiner 
1740e9868505SRik van Riel 	/*
17417c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
17427c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1743e9868505SRik van Riel 	 */
17447c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
17459a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1746e9868505SRik van Riel 		goto out;
17474f98a2feSRik van Riel 	}
17484f98a2feSRik van Riel 
17499a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
17509a265114SJohannes Weiner 
17514f98a2feSRik van Riel 	/*
175258c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
175358c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
175458c37f6eSKOSAKI Motohiro 	 */
17553d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
175675b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
175758c37f6eSKOSAKI Motohiro 
175858c37f6eSKOSAKI Motohiro 	/*
17594f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
17604f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
17614f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
17624f98a2feSRik van Riel 	 *
17634f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
17644f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
17654f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
17664f98a2feSRik van Riel 	 *
17674f98a2feSRik van Riel 	 * anon in [0], file in [1]
17684f98a2feSRik van Riel 	 */
176990126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
177058c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
17716e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
17726e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
17734f98a2feSRik van Riel 	}
17744f98a2feSRik van Riel 
17756e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
17766e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
17776e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
17784f98a2feSRik van Riel 	}
17794f98a2feSRik van Riel 
17804f98a2feSRik van Riel 	/*
178100d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
178200d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
178300d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
17844f98a2feSRik van Riel 	 */
1785fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
17866e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
17874f98a2feSRik van Riel 
1788fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
17896e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
179090126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
17914f98a2feSRik van Riel 
179276a33fc3SShaohua Li 	fraction[0] = ap;
179376a33fc3SShaohua Li 	fraction[1] = fp;
179476a33fc3SShaohua Li 	denominator = ap + fp + 1;
179576a33fc3SShaohua Li out:
17964111304dSHugh Dickins 	for_each_evictable_lru(lru) {
17974111304dSHugh Dickins 		int file = is_file_lru(lru);
1798d778df51SJohannes Weiner 		unsigned long size;
179976a33fc3SShaohua Li 		unsigned long scan;
180076a33fc3SShaohua Li 
1801d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1802d778df51SJohannes Weiner 		scan = size >> sc->priority;
18039a265114SJohannes Weiner 
1804f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1805d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
18069a265114SJohannes Weiner 
18079a265114SJohannes Weiner 		switch (scan_balance) {
18089a265114SJohannes Weiner 		case SCAN_EQUAL:
18099a265114SJohannes Weiner 			/* Scan lists relative to size */
18109a265114SJohannes Weiner 			break;
18119a265114SJohannes Weiner 		case SCAN_FRACT:
18129a265114SJohannes Weiner 			/*
18139a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
18149a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
18159a265114SJohannes Weiner 			 */
181676a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
18179a265114SJohannes Weiner 			break;
18189a265114SJohannes Weiner 		case SCAN_FILE:
18199a265114SJohannes Weiner 		case SCAN_ANON:
18209a265114SJohannes Weiner 			/* Scan one type exclusively */
18219a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
18229a265114SJohannes Weiner 				scan = 0;
18239a265114SJohannes Weiner 			break;
18249a265114SJohannes Weiner 		default:
18259a265114SJohannes Weiner 			/* Look ma, no brain */
18269a265114SJohannes Weiner 			BUG();
18279a265114SJohannes Weiner 		}
18284111304dSHugh Dickins 		nr[lru] = scan;
182976a33fc3SShaohua Li 	}
18306e08a369SWu Fengguang }
18314f98a2feSRik van Riel 
18329b4f98cdSJohannes Weiner /*
18339b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
18349b4f98cdSJohannes Weiner  */
18359b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
18369b4f98cdSJohannes Weiner {
18379b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
1838e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
18399b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
18409b4f98cdSJohannes Weiner 	enum lru_list lru;
18419b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
18429b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
18439b4f98cdSJohannes Weiner 	struct blk_plug plug;
1844e82e0561SMel Gorman 	bool scan_adjusted = false;
18459b4f98cdSJohannes Weiner 
18469b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
18479b4f98cdSJohannes Weiner 
1848e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
1849e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
1850e82e0561SMel Gorman 
18519b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
18529b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
18539b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
1854e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
1855e82e0561SMel Gorman 		unsigned long nr_scanned;
1856e82e0561SMel Gorman 
18579b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
18589b4f98cdSJohannes Weiner 			if (nr[lru]) {
18599b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
18609b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
18619b4f98cdSJohannes Weiner 
18629b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
18639b4f98cdSJohannes Weiner 							    lruvec, sc);
18649b4f98cdSJohannes Weiner 			}
18659b4f98cdSJohannes Weiner 		}
1866e82e0561SMel Gorman 
1867e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
1868e82e0561SMel Gorman 			continue;
1869e82e0561SMel Gorman 
18709b4f98cdSJohannes Weiner 		/*
1871e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
1872e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
1873e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
1874e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
18759b4f98cdSJohannes Weiner 		 */
1876e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
18779b4f98cdSJohannes Weiner 			break;
1878e82e0561SMel Gorman 
1879e82e0561SMel Gorman 		/*
1880e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
1881e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
1882e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
1883e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
1884e82e0561SMel Gorman 		 * proportional to the original scan target.
1885e82e0561SMel Gorman 		 */
1886e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
1887e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
1888e82e0561SMel Gorman 
1889e82e0561SMel Gorman 		if (nr_file > nr_anon) {
1890e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
1891e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
1892e82e0561SMel Gorman 			lru = LRU_BASE;
1893e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
1894e82e0561SMel Gorman 		} else {
1895e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
1896e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
1897e82e0561SMel Gorman 			lru = LRU_FILE;
1898e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
1899e82e0561SMel Gorman 		}
1900e82e0561SMel Gorman 
1901e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
1902e82e0561SMel Gorman 		nr[lru] = 0;
1903e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
1904e82e0561SMel Gorman 
1905e82e0561SMel Gorman 		/*
1906e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
1907e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
1908e82e0561SMel Gorman 		 */
1909e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
1910e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
1911e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
1912e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
1913e82e0561SMel Gorman 
1914e82e0561SMel Gorman 		lru += LRU_ACTIVE;
1915e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
1916e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
1917e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
1918e82e0561SMel Gorman 
1919e82e0561SMel Gorman 		scan_adjusted = true;
19209b4f98cdSJohannes Weiner 	}
19219b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
19229b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
19239b4f98cdSJohannes Weiner 
19249b4f98cdSJohannes Weiner 	/*
19259b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
19269b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
19279b4f98cdSJohannes Weiner 	 */
19289b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
19299b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
19309b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
19319b4f98cdSJohannes Weiner 
19329b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
19339b4f98cdSJohannes Weiner }
19349b4f98cdSJohannes Weiner 
193523b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
19369e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
193723b9da55SMel Gorman {
1938d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
193923b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
19409e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
194123b9da55SMel Gorman 		return true;
194223b9da55SMel Gorman 
194323b9da55SMel Gorman 	return false;
194423b9da55SMel Gorman }
194523b9da55SMel Gorman 
19464f98a2feSRik van Riel /*
194723b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
194823b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
194923b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
195023b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
195123b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
19523e7d3449SMel Gorman  */
19539b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
19543e7d3449SMel Gorman 					unsigned long nr_reclaimed,
19553e7d3449SMel Gorman 					unsigned long nr_scanned,
19563e7d3449SMel Gorman 					struct scan_control *sc)
19573e7d3449SMel Gorman {
19583e7d3449SMel Gorman 	unsigned long pages_for_compaction;
19593e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
19603e7d3449SMel Gorman 
19613e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
19629e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
19633e7d3449SMel Gorman 		return false;
19643e7d3449SMel Gorman 
19652876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
19662876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
19673e7d3449SMel Gorman 		/*
19682876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
19692876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
19702876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
19712876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
19723e7d3449SMel Gorman 		 */
19733e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
19743e7d3449SMel Gorman 			return false;
19752876592fSMel Gorman 	} else {
19762876592fSMel Gorman 		/*
19772876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
19782876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
19792876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
19802876592fSMel Gorman 		 * pages that were scanned. This will return to the
19812876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
19822876592fSMel Gorman 		 * the resulting allocation attempt fails
19832876592fSMel Gorman 		 */
19842876592fSMel Gorman 		if (!nr_reclaimed)
19852876592fSMel Gorman 			return false;
19862876592fSMel Gorman 	}
19873e7d3449SMel Gorman 
19883e7d3449SMel Gorman 	/*
19893e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
19903e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
19913e7d3449SMel Gorman 	 */
19923e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
19939b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
1994ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
19959b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
19963e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
19973e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
19983e7d3449SMel Gorman 		return true;
19993e7d3449SMel Gorman 
20003e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
20019b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
20023e7d3449SMel Gorman 	case COMPACT_PARTIAL:
20033e7d3449SMel Gorman 	case COMPACT_CONTINUE:
20043e7d3449SMel Gorman 		return false;
20053e7d3449SMel Gorman 	default:
20063e7d3449SMel Gorman 		return true;
20073e7d3449SMel Gorman 	}
20083e7d3449SMel Gorman }
20093e7d3449SMel Gorman 
20109e3b2f8cSKonstantin Khlebnikov static void shrink_zone(struct zone *zone, struct scan_control *sc)
2011f16015fbSJohannes Weiner {
20129b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
20139b4f98cdSJohannes Weiner 
20149b4f98cdSJohannes Weiner 	do {
20155660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
20165660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
20175660048cSJohannes Weiner 			.zone = zone,
20189e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
20195660048cSJohannes Weiner 		};
20205660048cSJohannes Weiner 		struct mem_cgroup *memcg;
20215660048cSJohannes Weiner 
20229b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
20239b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
20249b4f98cdSJohannes Weiner 
20255660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
20265660048cSJohannes Weiner 		do {
20279b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
20289b4f98cdSJohannes Weiner 
20299b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
20305660048cSJohannes Weiner 
2031f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2032f9be23d6SKonstantin Khlebnikov 
20335660048cSJohannes Weiner 			/*
2034a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2035a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
20369b4f98cdSJohannes Weiner 			 * zone.
2037a394cb8eSMichal Hocko 			 *
2038a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2039a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2040a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2041a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
20425660048cSJohannes Weiner 			 */
2043a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2044a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
20455660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
20465660048cSJohannes Weiner 				break;
20475660048cSJohannes Weiner 			}
20485660048cSJohannes Weiner 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
20495660048cSJohannes Weiner 		} while (memcg);
205070ddf637SAnton Vorontsov 
205170ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
205270ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
205370ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
205470ddf637SAnton Vorontsov 
20559b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
20569b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2057f16015fbSJohannes Weiner }
2058f16015fbSJohannes Weiner 
2059fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2060fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2061fe4b1b24SMel Gorman {
2062fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2063fe4b1b24SMel Gorman 	bool watermark_ok;
2064fe4b1b24SMel Gorman 
2065fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2066fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2067fe4b1b24SMel Gorman 		return false;
2068fe4b1b24SMel Gorman 
2069fe4b1b24SMel Gorman 	/*
2070fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2071fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2072fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2073fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2074fe4b1b24SMel Gorman 	 */
2075fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2076b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2077fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2078fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2079fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2080fe4b1b24SMel Gorman 
2081fe4b1b24SMel Gorman 	/*
2082fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2083fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2084fe4b1b24SMel Gorman 	 */
2085aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2086fe4b1b24SMel Gorman 		return watermark_ok;
2087fe4b1b24SMel Gorman 
2088fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2089fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2090fe4b1b24SMel Gorman 		return false;
2091fe4b1b24SMel Gorman 
2092fe4b1b24SMel Gorman 	return watermark_ok;
2093fe4b1b24SMel Gorman }
2094fe4b1b24SMel Gorman 
20951da177e4SLinus Torvalds /*
20961da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
20971da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
20981da177e4SLinus Torvalds  * request.
20991da177e4SLinus Torvalds  *
210041858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
210141858966SMel Gorman  * Because:
21021da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
21031da177e4SLinus Torvalds  *    allocation or
210441858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
210541858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
210641858966SMel Gorman  *    zone defense algorithm.
21071da177e4SLinus Torvalds  *
21081da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
21091da177e4SLinus Torvalds  * scan then give up on it.
2110e0c23279SMel Gorman  *
2111e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2112fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
21130cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
21140cee34fdSMel Gorman  * further reclaim.
21151da177e4SLinus Torvalds  */
21169e3b2f8cSKonstantin Khlebnikov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
21171da177e4SLinus Torvalds {
2118dd1a239fSMel Gorman 	struct zoneref *z;
211954a6eb5cSMel Gorman 	struct zone *zone;
2120d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2121d149e3b2SYing Han 	unsigned long nr_soft_scanned;
21220cee34fdSMel Gorman 	bool aborted_reclaim = false;
21231cfb419bSKAMEZAWA Hiroyuki 
2124cc715d99SMel Gorman 	/*
2125cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2126cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2127cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2128cc715d99SMel Gorman 	 */
2129cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2130cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2131cc715d99SMel Gorman 
2132d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2133d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2134f3fe6512SCon Kolivas 		if (!populated_zone(zone))
21351da177e4SLinus Torvalds 			continue;
21361cfb419bSKAMEZAWA Hiroyuki 		/*
21371cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
21381cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
21391cfb419bSKAMEZAWA Hiroyuki 		 */
214089b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
214102a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
21421da177e4SLinus Torvalds 				continue;
21439e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
21449e3b2f8cSKonstantin Khlebnikov 					sc->priority != DEF_PRIORITY)
21451da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2146d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2147e0887c19SRik van Riel 				/*
2148e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2149e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2150e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2151e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2152e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2153c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2154c7cfa37bSCopot Alexandru 				 * page allocations.
2155e0887c19SRik van Riel 				 */
2156fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
21570cee34fdSMel Gorman 					aborted_reclaim = true;
2158e0887c19SRik van Riel 					continue;
2159e0887c19SRik van Riel 				}
2160e0c23279SMel Gorman 			}
2161ac34a1a3SKAMEZAWA Hiroyuki 			/*
2162ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2163ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2164ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2165ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2166ac34a1a3SKAMEZAWA Hiroyuki 			 */
2167d149e3b2SYing Han 			nr_soft_scanned = 0;
2168d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2169d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2170d149e3b2SYing Han 						&nr_soft_scanned);
2171d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2172ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2173ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2174ac34a1a3SKAMEZAWA Hiroyuki 		}
2175d149e3b2SYing Han 
21769e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
21771da177e4SLinus Torvalds 	}
2178e0c23279SMel Gorman 
21790cee34fdSMel Gorman 	return aborted_reclaim;
2180d1908362SMinchan Kim }
2181d1908362SMinchan Kim 
2182d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2183d1908362SMinchan Kim {
2184d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2185d1908362SMinchan Kim }
2186d1908362SMinchan Kim 
2187929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2188d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2189d1908362SMinchan Kim 		struct scan_control *sc)
2190d1908362SMinchan Kim {
2191d1908362SMinchan Kim 	struct zoneref *z;
2192d1908362SMinchan Kim 	struct zone *zone;
2193d1908362SMinchan Kim 
2194d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2195d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2196d1908362SMinchan Kim 		if (!populated_zone(zone))
2197d1908362SMinchan Kim 			continue;
2198d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2199d1908362SMinchan Kim 			continue;
2200929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2201929bea7cSKOSAKI Motohiro 			return false;
2202d1908362SMinchan Kim 	}
2203d1908362SMinchan Kim 
2204929bea7cSKOSAKI Motohiro 	return true;
22051da177e4SLinus Torvalds }
22061da177e4SLinus Torvalds 
22071da177e4SLinus Torvalds /*
22081da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
22091da177e4SLinus Torvalds  *
22101da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
22111da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
22121da177e4SLinus Torvalds  *
22131da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
22141da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
22155b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
22165b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
22175b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
22185b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2219a41f24eaSNishanth Aravamudan  *
2220a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2221a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
22221da177e4SLinus Torvalds  */
2223dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2224a09ed5e0SYing Han 					struct scan_control *sc,
2225a09ed5e0SYing Han 					struct shrink_control *shrink)
22261da177e4SLinus Torvalds {
222769e05944SAndrew Morton 	unsigned long total_scanned = 0;
22281da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2229dd1a239fSMel Gorman 	struct zoneref *z;
223054a6eb5cSMel Gorman 	struct zone *zone;
223122fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
22320cee34fdSMel Gorman 	bool aborted_reclaim;
22331da177e4SLinus Torvalds 
2234873b4771SKeika Kobayashi 	delayacct_freepages_start();
2235873b4771SKeika Kobayashi 
223689b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2237f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
22381da177e4SLinus Torvalds 
22399e3b2f8cSKonstantin Khlebnikov 	do {
224070ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
224170ddf637SAnton Vorontsov 				sc->priority);
224266e1707bSBalbir Singh 		sc->nr_scanned = 0;
22439e3b2f8cSKonstantin Khlebnikov 		aborted_reclaim = shrink_zones(zonelist, sc);
2244e0c23279SMel Gorman 
224566e1707bSBalbir Singh 		/*
224666e1707bSBalbir Singh 		 * Don't shrink slabs when reclaiming memory from
224766e1707bSBalbir Singh 		 * over limit cgroups
224866e1707bSBalbir Singh 		 */
224989b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2250c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
2251d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2252d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2253c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2254c6a8a8c5SKOSAKI Motohiro 					continue;
2255c6a8a8c5SKOSAKI Motohiro 
2256c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
2257c6a8a8c5SKOSAKI Motohiro 			}
2258c6a8a8c5SKOSAKI Motohiro 
22591495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
22601da177e4SLinus Torvalds 			if (reclaim_state) {
2261a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
22621da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
22631da177e4SLinus Torvalds 			}
226491a45470SKAMEZAWA Hiroyuki 		}
226566e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2266bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
22671da177e4SLinus Torvalds 			goto out;
22681da177e4SLinus Torvalds 
22691da177e4SLinus Torvalds 		/*
22700e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
22710e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
22720e50ce3bSMinchan Kim 		 */
22730e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
22740e50ce3bSMinchan Kim 			sc->may_writepage = 1;
22750e50ce3bSMinchan Kim 
22760e50ce3bSMinchan Kim 		/*
22771da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
22781da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
22791da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
22801da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
22811da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
22821da177e4SLinus Torvalds 		 */
228322fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
228422fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
22850e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
22860e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
228766e1707bSBalbir Singh 			sc->may_writepage = 1;
22881da177e4SLinus Torvalds 		}
22891da177e4SLinus Torvalds 
22901da177e4SLinus Torvalds 		/* Take a nap, wait for some writeback to complete */
22917b51755cSKOSAKI Motohiro 		if (!sc->hibernation_mode && sc->nr_scanned &&
22929e3b2f8cSKonstantin Khlebnikov 		    sc->priority < DEF_PRIORITY - 2) {
22930e093d99SMel Gorman 			struct zone *preferred_zone;
22940e093d99SMel Gorman 
22950e093d99SMel Gorman 			first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2296f33261d7SDavid Rientjes 						&cpuset_current_mems_allowed,
2297f33261d7SDavid Rientjes 						&preferred_zone);
22980e093d99SMel Gorman 			wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
22990e093d99SMel Gorman 		}
23009e3b2f8cSKonstantin Khlebnikov 	} while (--sc->priority >= 0);
2301bb21c7ceSKOSAKI Motohiro 
23021da177e4SLinus Torvalds out:
2303873b4771SKeika Kobayashi 	delayacct_freepages_end();
2304873b4771SKeika Kobayashi 
2305bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2306bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2307bb21c7ceSKOSAKI Motohiro 
2308929bea7cSKOSAKI Motohiro 	/*
2309929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2310929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2311929bea7cSKOSAKI Motohiro 	 * check.
2312929bea7cSKOSAKI Motohiro 	 */
2313929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2314929bea7cSKOSAKI Motohiro 		return 0;
2315929bea7cSKOSAKI Motohiro 
23160cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
23170cee34fdSMel Gorman 	if (aborted_reclaim)
23187335084dSMel Gorman 		return 1;
23197335084dSMel Gorman 
2320bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
232189b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2322bb21c7ceSKOSAKI Motohiro 		return 1;
2323bb21c7ceSKOSAKI Motohiro 
2324bb21c7ceSKOSAKI Motohiro 	return 0;
23251da177e4SLinus Torvalds }
23261da177e4SLinus Torvalds 
23275515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
23285515061dSMel Gorman {
23295515061dSMel Gorman 	struct zone *zone;
23305515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
23315515061dSMel Gorman 	unsigned long free_pages = 0;
23325515061dSMel Gorman 	int i;
23335515061dSMel Gorman 	bool wmark_ok;
23345515061dSMel Gorman 
23355515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
23365515061dSMel Gorman 		zone = &pgdat->node_zones[i];
23375515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
23385515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
23395515061dSMel Gorman 	}
23405515061dSMel Gorman 
23415515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
23425515061dSMel Gorman 
23435515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
23445515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
23455515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
23465515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
23475515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
23485515061dSMel Gorman 	}
23495515061dSMel Gorman 
23505515061dSMel Gorman 	return wmark_ok;
23515515061dSMel Gorman }
23525515061dSMel Gorman 
23535515061dSMel Gorman /*
23545515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
23555515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
23565515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
235750694c28SMel Gorman  * when the low watermark is reached.
235850694c28SMel Gorman  *
235950694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
236050694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
23615515061dSMel Gorman  */
236250694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
23635515061dSMel Gorman 					nodemask_t *nodemask)
23645515061dSMel Gorman {
23655515061dSMel Gorman 	struct zone *zone;
23665515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
23675515061dSMel Gorman 	pg_data_t *pgdat;
23685515061dSMel Gorman 
23695515061dSMel Gorman 	/*
23705515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
23715515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
23725515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
23735515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
23745515061dSMel Gorman 	 * processes to block on log_wait_commit().
23755515061dSMel Gorman 	 */
23765515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
237750694c28SMel Gorman 		goto out;
237850694c28SMel Gorman 
237950694c28SMel Gorman 	/*
238050694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
238150694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
238250694c28SMel Gorman 	 */
238350694c28SMel Gorman 	if (fatal_signal_pending(current))
238450694c28SMel Gorman 		goto out;
23855515061dSMel Gorman 
23865515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
23875515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
23885515061dSMel Gorman 	pgdat = zone->zone_pgdat;
23895515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
239050694c28SMel Gorman 		goto out;
23915515061dSMel Gorman 
239268243e76SMel Gorman 	/* Account for the throttling */
239368243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
239468243e76SMel Gorman 
23955515061dSMel Gorman 	/*
23965515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
23975515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
23985515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
23995515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
24005515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
24015515061dSMel Gorman 	 * second before continuing.
24025515061dSMel Gorman 	 */
24035515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
24045515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
24055515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
240650694c28SMel Gorman 
240750694c28SMel Gorman 		goto check_pending;
24085515061dSMel Gorman 	}
24095515061dSMel Gorman 
24105515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
24115515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
24125515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
241350694c28SMel Gorman 
241450694c28SMel Gorman check_pending:
241550694c28SMel Gorman 	if (fatal_signal_pending(current))
241650694c28SMel Gorman 		return true;
241750694c28SMel Gorman 
241850694c28SMel Gorman out:
241950694c28SMel Gorman 	return false;
24205515061dSMel Gorman }
24215515061dSMel Gorman 
2422dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2423327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
242466e1707bSBalbir Singh {
242533906bc5SMel Gorman 	unsigned long nr_reclaimed;
242666e1707bSBalbir Singh 	struct scan_control sc = {
242721caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
242866e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
242922fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2430a6dc60f8SJohannes Weiner 		.may_unmap = 1,
24312e2e4259SKOSAKI Motohiro 		.may_swap = 1,
243266e1707bSBalbir Singh 		.order = order,
24339e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2434f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2435327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
243666e1707bSBalbir Singh 	};
2437a09ed5e0SYing Han 	struct shrink_control shrink = {
2438a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2439a09ed5e0SYing Han 	};
244066e1707bSBalbir Singh 
24415515061dSMel Gorman 	/*
244250694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
244350694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
244450694c28SMel Gorman 	 * point.
24455515061dSMel Gorman 	 */
244650694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
24475515061dSMel Gorman 		return 1;
24485515061dSMel Gorman 
244933906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
245033906bc5SMel Gorman 				sc.may_writepage,
245133906bc5SMel Gorman 				gfp_mask);
245233906bc5SMel Gorman 
2453a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
245433906bc5SMel Gorman 
245533906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
245633906bc5SMel Gorman 
245733906bc5SMel Gorman 	return nr_reclaimed;
245866e1707bSBalbir Singh }
245966e1707bSBalbir Singh 
2460c255a458SAndrew Morton #ifdef CONFIG_MEMCG
246166e1707bSBalbir Singh 
246272835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
24634e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
24640ae5e89cSYing Han 						struct zone *zone,
24650ae5e89cSYing Han 						unsigned long *nr_scanned)
24664e416953SBalbir Singh {
24674e416953SBalbir Singh 	struct scan_control sc = {
24680ae5e89cSYing Han 		.nr_scanned = 0,
2469b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
24704e416953SBalbir Singh 		.may_writepage = !laptop_mode,
24714e416953SBalbir Singh 		.may_unmap = 1,
24724e416953SBalbir Singh 		.may_swap = !noswap,
24734e416953SBalbir Singh 		.order = 0,
24749e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
247572835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
24764e416953SBalbir Singh 	};
2477f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
24780ae5e89cSYing Han 
24794e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
24804e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2481bdce6d9eSKOSAKI Motohiro 
24829e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2483bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2484bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2485bdce6d9eSKOSAKI Motohiro 
24864e416953SBalbir Singh 	/*
24874e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
24884e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
24894e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
24904e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
24914e416953SBalbir Singh 	 * the priority and make it zero.
24924e416953SBalbir Singh 	 */
2493f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2494bdce6d9eSKOSAKI Motohiro 
2495bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2496bdce6d9eSKOSAKI Motohiro 
24970ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
24984e416953SBalbir Singh 	return sc.nr_reclaimed;
24994e416953SBalbir Singh }
25004e416953SBalbir Singh 
250172835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
25028c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2503185efc0fSJohannes Weiner 					   bool noswap)
250466e1707bSBalbir Singh {
25054e416953SBalbir Singh 	struct zonelist *zonelist;
2506bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2507889976dbSYing Han 	int nid;
250866e1707bSBalbir Singh 	struct scan_control sc = {
250966e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2510a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25112e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
251222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
251366e1707bSBalbir Singh 		.order = 0,
25149e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
251572835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2516327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2517a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2518a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2519a09ed5e0SYing Han 	};
2520a09ed5e0SYing Han 	struct shrink_control shrink = {
2521a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
252266e1707bSBalbir Singh 	};
252366e1707bSBalbir Singh 
2524889976dbSYing Han 	/*
2525889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2526889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2527889976dbSYing Han 	 * scan does not need to be the current node.
2528889976dbSYing Han 	 */
252972835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2530889976dbSYing Han 
2531889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2532bdce6d9eSKOSAKI Motohiro 
2533bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2534bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2535bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2536bdce6d9eSKOSAKI Motohiro 
2537a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2538bdce6d9eSKOSAKI Motohiro 
2539bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2540bdce6d9eSKOSAKI Motohiro 
2541bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
254266e1707bSBalbir Singh }
254366e1707bSBalbir Singh #endif
254466e1707bSBalbir Singh 
25459e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2546f16015fbSJohannes Weiner {
2547b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2548b95a2f2dSJohannes Weiner 
2549b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2550b95a2f2dSJohannes Weiner 		return;
2551b95a2f2dSJohannes Weiner 
2552b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2553b95a2f2dSJohannes Weiner 	do {
2554c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2555f16015fbSJohannes Weiner 
2556c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
25571a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25589e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2559b95a2f2dSJohannes Weiner 
2560b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2561b95a2f2dSJohannes Weiner 	} while (memcg);
2562f16015fbSJohannes Weiner }
2563f16015fbSJohannes Weiner 
256460cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
256560cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
256660cefed4SJohannes Weiner {
256760cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
256860cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
256960cefed4SJohannes Weiner 		return false;
257060cefed4SJohannes Weiner 
2571d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2572d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
257360cefed4SJohannes Weiner 		return false;
257460cefed4SJohannes Weiner 
257560cefed4SJohannes Weiner 	return true;
257660cefed4SJohannes Weiner }
257760cefed4SJohannes Weiner 
25781741c877SMel Gorman /*
25794ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
25804ae0a48bSZlatko Calusic  *
25814ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
25824ae0a48bSZlatko Calusic  *
25834ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
25844ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
25854ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
25864ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
25874ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
25884ae0a48bSZlatko Calusic  * imbalanced zones.
25891741c877SMel Gorman  * The choice of 25% is due to
25901741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
25911741c877SMel Gorman  *     reasonable sized machine
25921741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
259325985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
25941741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
25951741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
25961741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
25971741c877SMel Gorman  */
25984ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
25991741c877SMel Gorman {
2600b40da049SJiang Liu 	unsigned long managed_pages = 0;
26014ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
26021741c877SMel Gorman 	int i;
26031741c877SMel Gorman 
26044ae0a48bSZlatko Calusic 	/* Check the watermark levels */
26054ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
26064ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
26071741c877SMel Gorman 
26084ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
26094ae0a48bSZlatko Calusic 			continue;
26104ae0a48bSZlatko Calusic 
2611b40da049SJiang Liu 		managed_pages += zone->managed_pages;
26124ae0a48bSZlatko Calusic 
26134ae0a48bSZlatko Calusic 		/*
26144ae0a48bSZlatko Calusic 		 * A special case here:
26154ae0a48bSZlatko Calusic 		 *
26164ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
26174ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
26184ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
26194ae0a48bSZlatko Calusic 		 */
26204ae0a48bSZlatko Calusic 		if (zone->all_unreclaimable) {
2621b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
26224ae0a48bSZlatko Calusic 			continue;
26234ae0a48bSZlatko Calusic 		}
26244ae0a48bSZlatko Calusic 
26254ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2626b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
26274ae0a48bSZlatko Calusic 		else if (!order)
26284ae0a48bSZlatko Calusic 			return false;
26294ae0a48bSZlatko Calusic 	}
26304ae0a48bSZlatko Calusic 
26314ae0a48bSZlatko Calusic 	if (order)
2632b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
26334ae0a48bSZlatko Calusic 	else
26344ae0a48bSZlatko Calusic 		return true;
26351741c877SMel Gorman }
26361741c877SMel Gorman 
26375515061dSMel Gorman /*
26385515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
26395515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
26405515061dSMel Gorman  *
26415515061dSMel Gorman  * Returns true if kswapd is ready to sleep
26425515061dSMel Gorman  */
26435515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2644dc83edd9SMel Gorman 					int classzone_idx)
2645f50de2d3SMel Gorman {
2646f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2647f50de2d3SMel Gorman 	if (remaining)
26485515061dSMel Gorman 		return false;
26495515061dSMel Gorman 
26505515061dSMel Gorman 	/*
26515515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
26525515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
26535515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
26545515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
26555515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
26565515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
26575515061dSMel Gorman 	 * kswapd and get throttled again
26585515061dSMel Gorman 	 */
26595515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
26605515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
26615515061dSMel Gorman 		return false;
26625515061dSMel Gorman 	}
2663f50de2d3SMel Gorman 
26644ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2665f50de2d3SMel Gorman }
2666f50de2d3SMel Gorman 
26671da177e4SLinus Torvalds /*
266875485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
266975485363SMel Gorman  * the high watermark.
2670b8e83b94SMel Gorman  *
2671b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2672b8e83b94SMel Gorman  * reclaim. This is used to determine if the scanning priority needs to be
2673b8e83b94SMel Gorman  * raised.
267475485363SMel Gorman  */
2675b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
267675485363SMel Gorman 			       struct scan_control *sc,
26772ab44f43SMel Gorman 			       unsigned long lru_pages,
26782ab44f43SMel Gorman 			       unsigned long *nr_attempted)
267975485363SMel Gorman {
268075485363SMel Gorman 	unsigned long nr_slab;
268175485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
268275485363SMel Gorman 	struct shrink_control shrink = {
268375485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
268475485363SMel Gorman 	};
268575485363SMel Gorman 
268675485363SMel Gorman 	/* Reclaim above the high watermark. */
268775485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
268875485363SMel Gorman 	shrink_zone(zone, sc);
268975485363SMel Gorman 
269075485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
269175485363SMel Gorman 	nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
269275485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
269375485363SMel Gorman 
26942ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
26952ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
26962ab44f43SMel Gorman 
269775485363SMel Gorman 	if (nr_slab == 0 && !zone_reclaimable(zone))
269875485363SMel Gorman 		zone->all_unreclaimable = 1;
2699b8e83b94SMel Gorman 
2700b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
270175485363SMel Gorman }
270275485363SMel Gorman 
270375485363SMel Gorman /*
27041da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
270541858966SMel Gorman  * they are all at high_wmark_pages(zone).
27061da177e4SLinus Torvalds  *
27070abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
27081da177e4SLinus Torvalds  *
27091da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
27101da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
27111da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
27121da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
27131da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
27141da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
27151da177e4SLinus Torvalds  * the zone for when the problem goes away.
27161da177e4SLinus Torvalds  *
27171da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
271841858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
271941858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
272041858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
272141858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
272241858966SMel Gorman  * of pages is balanced across the zones.
27231da177e4SLinus Torvalds  */
272499504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2725dc83edd9SMel Gorman 							int *classzone_idx)
27261da177e4SLinus Torvalds {
27271da177e4SLinus Torvalds 	int i;
272899504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
27290ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
27300ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2731179e9639SAndrew Morton 	struct scan_control sc = {
2732179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2733b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2734a6dc60f8SJohannes Weiner 		.may_unmap = 1,
27352e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2736b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
27375ad333ebSAndy Whitcroft 		.order = order,
2738f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2739179e9639SAndrew Morton 	};
2740f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
27411da177e4SLinus Torvalds 
27429e3b2f8cSKonstantin Khlebnikov 	do {
27431da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
27442ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2745b8e83b94SMel Gorman 		bool raise_priority = true;
27462ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2747b8e83b94SMel Gorman 
2748b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
27491da177e4SLinus Torvalds 
27501da177e4SLinus Torvalds 		/*
27511da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
27521da177e4SLinus Torvalds 		 * zone which needs scanning
27531da177e4SLinus Torvalds 		 */
27541da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
27551da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
27561da177e4SLinus Torvalds 
2757f3fe6512SCon Kolivas 			if (!populated_zone(zone))
27581da177e4SLinus Torvalds 				continue;
27591da177e4SLinus Torvalds 
27609e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
27619e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
27621da177e4SLinus Torvalds 				continue;
27631da177e4SLinus Torvalds 
2764556adecbSRik van Riel 			/*
2765556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2766556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2767556adecbSRik van Riel 			 */
27689e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2769556adecbSRik van Riel 
2770cc715d99SMel Gorman 			/*
2771cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2772cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2773cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2774cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2775cc715d99SMel Gorman 			 */
2776cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2777cc715d99SMel Gorman 				end_zone = i;
2778cc715d99SMel Gorman 				break;
2779cc715d99SMel Gorman 			}
2780cc715d99SMel Gorman 
278160cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
27821da177e4SLinus Torvalds 				end_zone = i;
2783e1dbeda6SAndrew Morton 				break;
2784439423f6SShaohua Li 			} else {
2785*d43006d5SMel Gorman 				/*
2786*d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
2787*d43006d5SMel Gorman 				 * flags
2788*d43006d5SMel Gorman 				 */
2789439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
2790*d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
27911da177e4SLinus Torvalds 			}
27921da177e4SLinus Torvalds 		}
2793dafcb73eSZlatko Calusic 
2794b8e83b94SMel Gorman 		if (i < 0)
27951da177e4SLinus Torvalds 			goto out;
2796e1dbeda6SAndrew Morton 
27971da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
27981da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
27991da177e4SLinus Torvalds 
28002ab44f43SMel Gorman 			if (!populated_zone(zone))
28012ab44f43SMel Gorman 				continue;
28022ab44f43SMel Gorman 
2803adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
28042ab44f43SMel Gorman 
28052ab44f43SMel Gorman 			/*
28062ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
28072ab44f43SMel Gorman 			 * not call compaction as it is expected that the
28082ab44f43SMel Gorman 			 * necessary pages are already available.
28092ab44f43SMel Gorman 			 */
28102ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
28112ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
28122ab44f43SMel Gorman 						low_wmark_pages(zone),
28132ab44f43SMel Gorman 						*classzone_idx, 0))
28142ab44f43SMel Gorman 				pgdat_needs_compaction = false;
28151da177e4SLinus Torvalds 		}
28161da177e4SLinus Torvalds 
28171da177e4SLinus Torvalds 		/*
28181da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
28191da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
28201da177e4SLinus Torvalds 		 *
28211da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
28221da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
28231da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
28241da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
28251da177e4SLinus Torvalds 		 */
28261da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
28271da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
282875485363SMel Gorman 			int testorder;
28298afdceceSMel Gorman 			unsigned long balance_gap;
28301da177e4SLinus Torvalds 
2831f3fe6512SCon Kolivas 			if (!populated_zone(zone))
28321da177e4SLinus Torvalds 				continue;
28331da177e4SLinus Torvalds 
28349e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
28359e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
28361da177e4SLinus Torvalds 				continue;
28371da177e4SLinus Torvalds 
28381da177e4SLinus Torvalds 			sc.nr_scanned = 0;
28394e416953SBalbir Singh 
28400ae5e89cSYing Han 			nr_soft_scanned = 0;
28414e416953SBalbir Singh 			/*
28424e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
28434e416953SBalbir Singh 			 */
28440ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
28450ae5e89cSYing Han 							order, sc.gfp_mask,
28460ae5e89cSYing Han 							&nr_soft_scanned);
28470ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
284800918b6aSKOSAKI Motohiro 
284932a4330dSRik van Riel 			/*
28508afdceceSMel Gorman 			 * We put equal pressure on every zone, unless
28518afdceceSMel Gorman 			 * one zone has way too many pages free
28528afdceceSMel Gorman 			 * already. The "too many pages" is defined
28538afdceceSMel Gorman 			 * as the high wmark plus a "gap" where the
28548afdceceSMel Gorman 			 * gap is either the low watermark or 1%
28558afdceceSMel Gorman 			 * of the zone, whichever is smaller.
285632a4330dSRik van Riel 			 */
28578afdceceSMel Gorman 			balance_gap = min(low_wmark_pages(zone),
2858b40da049SJiang Liu 				(zone->managed_pages +
28598afdceceSMel Gorman 					KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28608afdceceSMel Gorman 				KSWAPD_ZONE_BALANCE_GAP_RATIO);
2861fe2c2a10SRik van Riel 			/*
2862fe2c2a10SRik van Riel 			 * Kswapd reclaims only single pages with compaction
2863fe2c2a10SRik van Riel 			 * enabled. Trying too hard to reclaim until contiguous
2864fe2c2a10SRik van Riel 			 * free pages have become available can hurt performance
2865fe2c2a10SRik van Riel 			 * by evicting too much useful data from memory.
2866fe2c2a10SRik van Riel 			 * Do not reclaim more than needed for compaction.
2867fe2c2a10SRik van Riel 			 */
2868fe2c2a10SRik van Riel 			testorder = order;
2869d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2870fe2c2a10SRik van Riel 					compaction_suitable(zone, order) !=
2871fe2c2a10SRik van Riel 						COMPACT_SKIPPED)
2872fe2c2a10SRik van Riel 				testorder = 0;
2873fe2c2a10SRik van Riel 
2874cc715d99SMel Gorman 			if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
287560cefed4SJohannes Weiner 			    !zone_balanced(zone, testorder,
2876b8e83b94SMel Gorman 					   balance_gap, end_zone)) {
2877b8e83b94SMel Gorman 				/*
2878b8e83b94SMel Gorman 				 * There should be no need to raise the
2879b8e83b94SMel Gorman 				 * scanning priority if enough pages are
2880b8e83b94SMel Gorman 				 * already being scanned that high
2881b8e83b94SMel Gorman 				 * watermark would be met at 100% efficiency.
2882b8e83b94SMel Gorman 				 */
28832ab44f43SMel Gorman 				if (kswapd_shrink_zone(zone, &sc, lru_pages,
28842ab44f43SMel Gorman 						       &nr_attempted))
2885b8e83b94SMel Gorman 					raise_priority = false;
2886b8e83b94SMel Gorman 			}
2887d7868daeSMel Gorman 
28881da177e4SLinus Torvalds 			/*
28890e50ce3bSMinchan Kim 			 * If we're getting trouble reclaiming, start doing
28900e50ce3bSMinchan Kim 			 * writepage even in laptop mode.
28911da177e4SLinus Torvalds 			 */
28920e50ce3bSMinchan Kim 			if (sc.priority < DEF_PRIORITY - 2)
28931da177e4SLinus Torvalds 				sc.may_writepage = 1;
2894bb3ab596SKOSAKI Motohiro 
2895215ddd66SMel Gorman 			if (zone->all_unreclaimable) {
2896215ddd66SMel Gorman 				if (end_zone && end_zone == i)
2897215ddd66SMel Gorman 					end_zone--;
2898d7868daeSMel Gorman 				continue;
2899215ddd66SMel Gorman 			}
2900d7868daeSMel Gorman 
2901258401a6SZlatko Calusic 			if (zone_balanced(zone, testorder, 0, end_zone))
29020e093d99SMel Gorman 				/*
29030e093d99SMel Gorman 				 * If a zone reaches its high watermark,
29040e093d99SMel Gorman 				 * consider it to be no longer congested. It's
29050e093d99SMel Gorman 				 * possible there are dirty pages backed by
29060e093d99SMel Gorman 				 * congested BDIs but as pressure is relieved,
2907ab8704b8SWanpeng Li 				 * speculatively avoid congestion waits
2908*d43006d5SMel Gorman 				 * or writing pages from kswapd context.
29090e093d99SMel Gorman 				 */
29100e093d99SMel Gorman 				zone_clear_flag(zone, ZONE_CONGESTED);
2911*d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
291245973d74SMinchan Kim 		}
2913bb3ab596SKOSAKI Motohiro 
29145515061dSMel Gorman 		/*
29155515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
29165515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
29175515061dSMel Gorman 		 * able to safely make forward progress. Wake them
29185515061dSMel Gorman 		 */
29195515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
29205515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
29215515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
29225515061dSMel Gorman 
29231da177e4SLinus Torvalds 		/*
2924b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
2925b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
2926b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
2927b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
2928b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
2929b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
29301da177e4SLinus Torvalds 		 */
2931b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
293273ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
293373ce02e9SKOSAKI Motohiro 
2934b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
2935b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
2936b8e83b94SMel Gorman 			break;
2937b8e83b94SMel Gorman 
2938b8e83b94SMel Gorman 		/*
29392ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
29402ab44f43SMel Gorman 		 * high watermark number of pages as requsted
29412ab44f43SMel Gorman 		 */
29422ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
29432ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
29442ab44f43SMel Gorman 
29452ab44f43SMel Gorman 		/*
2946b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
2947b8e83b94SMel Gorman 		 * progress in reclaiming pages
2948b8e83b94SMel Gorman 		 */
2949b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
2950b8e83b94SMel Gorman 			sc.priority--;
29519aa41348SMel Gorman 	} while (sc.priority >= 1 &&
2952b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
29531da177e4SLinus Torvalds 
2954b8e83b94SMel Gorman out:
29550abdee2bSMel Gorman 	/*
29565515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
29570abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
29580abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
29590abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
29600abdee2bSMel Gorman 	 */
2961dc83edd9SMel Gorman 	*classzone_idx = end_zone;
29620abdee2bSMel Gorman 	return order;
29631da177e4SLinus Torvalds }
29641da177e4SLinus Torvalds 
2965dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
2966f0bc0a60SKOSAKI Motohiro {
2967f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
2968f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
2969f0bc0a60SKOSAKI Motohiro 
2970f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
2971f0bc0a60SKOSAKI Motohiro 		return;
2972f0bc0a60SKOSAKI Motohiro 
2973f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2974f0bc0a60SKOSAKI Motohiro 
2975f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
29765515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2977f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
2978f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
2979f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2980f0bc0a60SKOSAKI Motohiro 	}
2981f0bc0a60SKOSAKI Motohiro 
2982f0bc0a60SKOSAKI Motohiro 	/*
2983f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
2984f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
2985f0bc0a60SKOSAKI Motohiro 	 */
29865515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2987f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
2988f0bc0a60SKOSAKI Motohiro 
2989f0bc0a60SKOSAKI Motohiro 		/*
2990f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
2991f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
2992f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
2993f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
2994f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
2995f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
2996f0bc0a60SKOSAKI Motohiro 		 */
2997f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
29981c7e7f6cSAaditya Kumar 
299962997027SMel Gorman 		/*
300062997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
300162997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
300262997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
300362997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
300462997027SMel Gorman 		 */
300562997027SMel Gorman 		reset_isolation_suitable(pgdat);
300662997027SMel Gorman 
30071c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3008f0bc0a60SKOSAKI Motohiro 			schedule();
30091c7e7f6cSAaditya Kumar 
3010f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3011f0bc0a60SKOSAKI Motohiro 	} else {
3012f0bc0a60SKOSAKI Motohiro 		if (remaining)
3013f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3014f0bc0a60SKOSAKI Motohiro 		else
3015f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3016f0bc0a60SKOSAKI Motohiro 	}
3017f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3018f0bc0a60SKOSAKI Motohiro }
3019f0bc0a60SKOSAKI Motohiro 
30201da177e4SLinus Torvalds /*
30211da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
30221da177e4SLinus Torvalds  * from the init process.
30231da177e4SLinus Torvalds  *
30241da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
30251da177e4SLinus Torvalds  * free memory available even if there is no other activity
30261da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
30271da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
30281da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
30291da177e4SLinus Torvalds  *
30301da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
30311da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
30321da177e4SLinus Torvalds  */
30331da177e4SLinus Torvalds static int kswapd(void *p)
30341da177e4SLinus Torvalds {
3035215ddd66SMel Gorman 	unsigned long order, new_order;
3036d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3037215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3038d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
30391da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
30401da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3041f0bc0a60SKOSAKI Motohiro 
30421da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
30431da177e4SLinus Torvalds 		.reclaimed_slab = 0,
30441da177e4SLinus Torvalds 	};
3045a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
30461da177e4SLinus Torvalds 
3047cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3048cf40bd16SNick Piggin 
3049174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3050c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
30511da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
30521da177e4SLinus Torvalds 
30531da177e4SLinus Torvalds 	/*
30541da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
30551da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
30561da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
30571da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
30581da177e4SLinus Torvalds 	 *
30591da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
30601da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
30611da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
30621da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
30631da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
30641da177e4SLinus Torvalds 	 */
3065930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
306683144186SRafael J. Wysocki 	set_freezable();
30671da177e4SLinus Torvalds 
3068215ddd66SMel Gorman 	order = new_order = 0;
3069d2ebd0f6SAlex,Shi 	balanced_order = 0;
3070215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3071d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
30721da177e4SLinus Torvalds 	for ( ; ; ) {
30736f6313d4SJeff Liu 		bool ret;
30743e1d1d28SChristoph Lameter 
3075215ddd66SMel Gorman 		/*
3076215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3077215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3078215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3079215ddd66SMel Gorman 		 */
3080d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3081d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
30821da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
308399504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
30841da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3085215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3086215ddd66SMel Gorman 		}
3087215ddd66SMel Gorman 
308899504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
30891da177e4SLinus Torvalds 			/*
30901da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
309199504748SMel Gorman 			 * allocation or has tigher zone constraints
30921da177e4SLinus Torvalds 			 */
30931da177e4SLinus Torvalds 			order = new_order;
309499504748SMel Gorman 			classzone_idx = new_classzone_idx;
30951da177e4SLinus Torvalds 		} else {
3096d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3097d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
30981da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
309999504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3100f0dfcde0SAlex,Shi 			new_order = order;
3101f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
31024d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3103215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
31041da177e4SLinus Torvalds 		}
31051da177e4SLinus Torvalds 
31068fe23e05SDavid Rientjes 		ret = try_to_freeze();
31078fe23e05SDavid Rientjes 		if (kthread_should_stop())
31088fe23e05SDavid Rientjes 			break;
31098fe23e05SDavid Rientjes 
31108fe23e05SDavid Rientjes 		/*
31118fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
31128fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3113b1296cc4SRafael J. Wysocki 		 */
311433906bc5SMel Gorman 		if (!ret) {
311533906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3116d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3117d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3118d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
31191da177e4SLinus Torvalds 		}
312033906bc5SMel Gorman 	}
3121b0a8cc58STakamori Yamaguchi 
3122b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
31231da177e4SLinus Torvalds 	return 0;
31241da177e4SLinus Torvalds }
31251da177e4SLinus Torvalds 
31261da177e4SLinus Torvalds /*
31271da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
31281da177e4SLinus Torvalds  */
312999504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
31301da177e4SLinus Torvalds {
31311da177e4SLinus Torvalds 	pg_data_t *pgdat;
31321da177e4SLinus Torvalds 
3133f3fe6512SCon Kolivas 	if (!populated_zone(zone))
31341da177e4SLinus Torvalds 		return;
31351da177e4SLinus Torvalds 
313602a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
31371da177e4SLinus Torvalds 		return;
313888f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
313999504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
314088f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
314199504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
314299504748SMel Gorman 	}
31438d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
31441da177e4SLinus Torvalds 		return;
314588f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
314688f5acf8SMel Gorman 		return;
314788f5acf8SMel Gorman 
314888f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
31498d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
31501da177e4SLinus Torvalds }
31511da177e4SLinus Torvalds 
3152adea02a1SWu Fengguang /*
3153adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
3154adea02a1SWu Fengguang  * The less reclaimable pages may be
3155adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
3156adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
3157adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
3158adea02a1SWu Fengguang  */
3159adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
31604f98a2feSRik van Riel {
3161adea02a1SWu Fengguang 	int nr;
3162adea02a1SWu Fengguang 
3163adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
3164adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
3165adea02a1SWu Fengguang 
3166ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3167adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
3168adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
3169adea02a1SWu Fengguang 
3170adea02a1SWu Fengguang 	return nr;
3171adea02a1SWu Fengguang }
3172adea02a1SWu Fengguang 
3173adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
3174adea02a1SWu Fengguang {
3175adea02a1SWu Fengguang 	int nr;
3176adea02a1SWu Fengguang 
3177adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3178adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
3179adea02a1SWu Fengguang 
3180ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3181adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3182adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
3183adea02a1SWu Fengguang 
3184adea02a1SWu Fengguang 	return nr;
31854f98a2feSRik van Riel }
31864f98a2feSRik van Riel 
3187c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
31881da177e4SLinus Torvalds /*
31897b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3190d6277db4SRafael J. Wysocki  * freed pages.
3191d6277db4SRafael J. Wysocki  *
3192d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3193d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3194d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
31951da177e4SLinus Torvalds  */
31967b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
31971da177e4SLinus Torvalds {
3198d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3199d6277db4SRafael J. Wysocki 	struct scan_control sc = {
32007b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
32017b51755cSKOSAKI Motohiro 		.may_swap = 1,
32027b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3203d6277db4SRafael J. Wysocki 		.may_writepage = 1,
32047b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
32057b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
32067b51755cSKOSAKI Motohiro 		.order = 0,
32079e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
32081da177e4SLinus Torvalds 	};
3209a09ed5e0SYing Han 	struct shrink_control shrink = {
3210a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3211a09ed5e0SYing Han 	};
32127b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
32137b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
32147b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
32151da177e4SLinus Torvalds 
32167b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
32177b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3218d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
32197b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3220d6277db4SRafael J. Wysocki 
3221a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3222d6277db4SRafael J. Wysocki 
32237b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
32247b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
32257b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3226d6277db4SRafael J. Wysocki 
32277b51755cSKOSAKI Motohiro 	return nr_reclaimed;
32281da177e4SLinus Torvalds }
3229c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
32301da177e4SLinus Torvalds 
32311da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
32321da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
32331da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
32341da177e4SLinus Torvalds    restore their cpu bindings. */
3235fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3236fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
32371da177e4SLinus Torvalds {
323858c0a4a7SYasunori Goto 	int nid;
32391da177e4SLinus Torvalds 
32408bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
324148fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3242c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3243a70f7302SRusty Russell 			const struct cpumask *mask;
3244a70f7302SRusty Russell 
3245a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3246c5f59f08SMike Travis 
32473e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
32481da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3249c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
32501da177e4SLinus Torvalds 		}
32511da177e4SLinus Torvalds 	}
32521da177e4SLinus Torvalds 	return NOTIFY_OK;
32531da177e4SLinus Torvalds }
32541da177e4SLinus Torvalds 
32553218ae14SYasunori Goto /*
32563218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
32573218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
32583218ae14SYasunori Goto  */
32593218ae14SYasunori Goto int kswapd_run(int nid)
32603218ae14SYasunori Goto {
32613218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
32623218ae14SYasunori Goto 	int ret = 0;
32633218ae14SYasunori Goto 
32643218ae14SYasunori Goto 	if (pgdat->kswapd)
32653218ae14SYasunori Goto 		return 0;
32663218ae14SYasunori Goto 
32673218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
32683218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
32693218ae14SYasunori Goto 		/* failure at boot is fatal */
32703218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3271d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3272d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3273d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
32743218ae14SYasunori Goto 	}
32753218ae14SYasunori Goto 	return ret;
32763218ae14SYasunori Goto }
32773218ae14SYasunori Goto 
32788fe23e05SDavid Rientjes /*
3279d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3280d8adde17SJiang Liu  * hold lock_memory_hotplug().
32818fe23e05SDavid Rientjes  */
32828fe23e05SDavid Rientjes void kswapd_stop(int nid)
32838fe23e05SDavid Rientjes {
32848fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
32858fe23e05SDavid Rientjes 
3286d8adde17SJiang Liu 	if (kswapd) {
32878fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3288d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3289d8adde17SJiang Liu 	}
32908fe23e05SDavid Rientjes }
32918fe23e05SDavid Rientjes 
32921da177e4SLinus Torvalds static int __init kswapd_init(void)
32931da177e4SLinus Torvalds {
32943218ae14SYasunori Goto 	int nid;
329569e05944SAndrew Morton 
32961da177e4SLinus Torvalds 	swap_setup();
329748fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
32983218ae14SYasunori Goto  		kswapd_run(nid);
32991da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
33001da177e4SLinus Torvalds 	return 0;
33011da177e4SLinus Torvalds }
33021da177e4SLinus Torvalds 
33031da177e4SLinus Torvalds module_init(kswapd_init)
33049eeff239SChristoph Lameter 
33059eeff239SChristoph Lameter #ifdef CONFIG_NUMA
33069eeff239SChristoph Lameter /*
33079eeff239SChristoph Lameter  * Zone reclaim mode
33089eeff239SChristoph Lameter  *
33099eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
33109eeff239SChristoph Lameter  * the watermarks.
33119eeff239SChristoph Lameter  */
33129eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
33139eeff239SChristoph Lameter 
33141b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
33157d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
33161b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
33171b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
33181b2ffb78SChristoph Lameter 
33199eeff239SChristoph Lameter /*
3320a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3321a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3322a92f7126SChristoph Lameter  * a zone.
3323a92f7126SChristoph Lameter  */
3324a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3325a92f7126SChristoph Lameter 
33269eeff239SChristoph Lameter /*
33279614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
33289614634fSChristoph Lameter  * occur.
33299614634fSChristoph Lameter  */
33309614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
33319614634fSChristoph Lameter 
33329614634fSChristoph Lameter /*
33330ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
33340ff38490SChristoph Lameter  * slab reclaim needs to occur.
33350ff38490SChristoph Lameter  */
33360ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
33370ff38490SChristoph Lameter 
333890afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
333990afa5deSMel Gorman {
334090afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
334190afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
334290afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
334390afa5deSMel Gorman 
334490afa5deSMel Gorman 	/*
334590afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
334690afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
334790afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
334890afa5deSMel Gorman 	 */
334990afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
335090afa5deSMel Gorman }
335190afa5deSMel Gorman 
335290afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
335390afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
335490afa5deSMel Gorman {
335590afa5deSMel Gorman 	long nr_pagecache_reclaimable;
335690afa5deSMel Gorman 	long delta = 0;
335790afa5deSMel Gorman 
335890afa5deSMel Gorman 	/*
335990afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
336090afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
336190afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
336290afa5deSMel Gorman 	 * a better estimate
336390afa5deSMel Gorman 	 */
336490afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
336590afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
336690afa5deSMel Gorman 	else
336790afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
336890afa5deSMel Gorman 
336990afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
337090afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
337190afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
337290afa5deSMel Gorman 
337390afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
337490afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
337590afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
337690afa5deSMel Gorman 
337790afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
337890afa5deSMel Gorman }
337990afa5deSMel Gorman 
33800ff38490SChristoph Lameter /*
33819eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
33829eeff239SChristoph Lameter  */
3383179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
33849eeff239SChristoph Lameter {
33857fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
338669e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
33879eeff239SChristoph Lameter 	struct task_struct *p = current;
33889eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3389179e9639SAndrew Morton 	struct scan_control sc = {
3390179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3391a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
33922e2e4259SKOSAKI Motohiro 		.may_swap = 1,
339362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
339421caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3395bd2f6199SJohannes Weiner 		.order = order,
33969e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3397179e9639SAndrew Morton 	};
3398a09ed5e0SYing Han 	struct shrink_control shrink = {
3399a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3400a09ed5e0SYing Han 	};
340115748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
34029eeff239SChristoph Lameter 
34039eeff239SChristoph Lameter 	cond_resched();
3404d4f7796eSChristoph Lameter 	/*
3405d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3406d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3407d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3408d4f7796eSChristoph Lameter 	 */
3409d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
341076ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
34119eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
34129eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3413c84db23cSChristoph Lameter 
341490afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3415a92f7126SChristoph Lameter 		/*
34160ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
34170ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3418a92f7126SChristoph Lameter 		 */
3419a92f7126SChristoph Lameter 		do {
34209e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
34219e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
34220ff38490SChristoph Lameter 	}
3423a92f7126SChristoph Lameter 
342415748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
342515748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
34262a16e3f4SChristoph Lameter 		/*
34277fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
34280ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
34290ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
34300ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
34310ff38490SChristoph Lameter 		 * pages.
34322a16e3f4SChristoph Lameter 		 *
34330ff38490SChristoph Lameter 		 * Note that shrink_slab will free memory on all zones and may
34340ff38490SChristoph Lameter 		 * take a long time.
34352a16e3f4SChristoph Lameter 		 */
34364dc4b3d9SKOSAKI Motohiro 		for (;;) {
34374dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
34384dc4b3d9SKOSAKI Motohiro 
34394dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
34401495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
34414dc4b3d9SKOSAKI Motohiro 				break;
34424dc4b3d9SKOSAKI Motohiro 
34434dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
34444dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
34454dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
34464dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
34474dc4b3d9SKOSAKI Motohiro 				break;
34484dc4b3d9SKOSAKI Motohiro 		}
344983e33a47SChristoph Lameter 
345083e33a47SChristoph Lameter 		/*
345183e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
345283e33a47SChristoph Lameter 		 * reclaimed from this zone.
345383e33a47SChristoph Lameter 		 */
345415748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
345515748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
345615748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
34572a16e3f4SChristoph Lameter 	}
34582a16e3f4SChristoph Lameter 
34599eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3460d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
346176ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3462a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
34639eeff239SChristoph Lameter }
3464179e9639SAndrew Morton 
3465179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3466179e9639SAndrew Morton {
3467179e9639SAndrew Morton 	int node_id;
3468d773ed6bSDavid Rientjes 	int ret;
3469179e9639SAndrew Morton 
3470179e9639SAndrew Morton 	/*
34710ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
34720ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
347334aa1330SChristoph Lameter 	 *
34749614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
34759614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
34769614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
34779614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
34789614634fSChristoph Lameter 	 * unmapped file backed pages.
3479179e9639SAndrew Morton 	 */
348090afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
348190afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3482fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3483179e9639SAndrew Morton 
348493e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3485fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3486d773ed6bSDavid Rientjes 
3487179e9639SAndrew Morton 	/*
3488d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3489179e9639SAndrew Morton 	 */
3490d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3491fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3492179e9639SAndrew Morton 
3493179e9639SAndrew Morton 	/*
3494179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3495179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3496179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3497179e9639SAndrew Morton 	 * as wide as possible.
3498179e9639SAndrew Morton 	 */
349989fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
350037c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3501fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3502d773ed6bSDavid Rientjes 
3503d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3504fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3505fa5e084eSMel Gorman 
3506d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3507d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3508d773ed6bSDavid Rientjes 
350924cf7251SMel Gorman 	if (!ret)
351024cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
351124cf7251SMel Gorman 
3512d773ed6bSDavid Rientjes 	return ret;
3513179e9639SAndrew Morton }
35149eeff239SChristoph Lameter #endif
3515894bc310SLee Schermerhorn 
3516894bc310SLee Schermerhorn /*
3517894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3518894bc310SLee Schermerhorn  * @page: the page to test
3519894bc310SLee Schermerhorn  *
3520894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
352139b5f29aSHugh Dickins  * lists vs unevictable list.
3522894bc310SLee Schermerhorn  *
3523894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3524ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3525b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3526ba9ddf49SLee Schermerhorn  *
3527894bc310SLee Schermerhorn  */
352839b5f29aSHugh Dickins int page_evictable(struct page *page)
3529894bc310SLee Schermerhorn {
353039b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3531894bc310SLee Schermerhorn }
353289e004eaSLee Schermerhorn 
353385046579SHugh Dickins #ifdef CONFIG_SHMEM
353489e004eaSLee Schermerhorn /**
353524513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
353624513264SHugh Dickins  * @pages:	array of pages to check
353724513264SHugh Dickins  * @nr_pages:	number of pages to check
353889e004eaSLee Schermerhorn  *
353924513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
354085046579SHugh Dickins  *
354185046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
354289e004eaSLee Schermerhorn  */
354324513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
354489e004eaSLee Schermerhorn {
3545925b7673SJohannes Weiner 	struct lruvec *lruvec;
354624513264SHugh Dickins 	struct zone *zone = NULL;
354724513264SHugh Dickins 	int pgscanned = 0;
354824513264SHugh Dickins 	int pgrescued = 0;
354989e004eaSLee Schermerhorn 	int i;
355089e004eaSLee Schermerhorn 
355124513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
355224513264SHugh Dickins 		struct page *page = pages[i];
355324513264SHugh Dickins 		struct zone *pagezone;
355489e004eaSLee Schermerhorn 
355524513264SHugh Dickins 		pgscanned++;
355624513264SHugh Dickins 		pagezone = page_zone(page);
355789e004eaSLee Schermerhorn 		if (pagezone != zone) {
355889e004eaSLee Schermerhorn 			if (zone)
355989e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
356089e004eaSLee Schermerhorn 			zone = pagezone;
356189e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
356289e004eaSLee Schermerhorn 		}
3563fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
356489e004eaSLee Schermerhorn 
356524513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
356624513264SHugh Dickins 			continue;
356789e004eaSLee Schermerhorn 
356839b5f29aSHugh Dickins 		if (page_evictable(page)) {
356924513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
357024513264SHugh Dickins 
357124513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
357224513264SHugh Dickins 			ClearPageUnevictable(page);
3573fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3574fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
357524513264SHugh Dickins 			pgrescued++;
357689e004eaSLee Schermerhorn 		}
357789e004eaSLee Schermerhorn 	}
357824513264SHugh Dickins 
357924513264SHugh Dickins 	if (zone) {
358024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
358124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
358224513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
358324513264SHugh Dickins 	}
358485046579SHugh Dickins }
358585046579SHugh Dickins #endif /* CONFIG_SHMEM */
3586af936a16SLee Schermerhorn 
3587264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3588af936a16SLee Schermerhorn {
3589264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
359025bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3591264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
359225bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
359325bd91bdSKOSAKI Motohiro 		    current->comm);
3594af936a16SLee Schermerhorn }
3595af936a16SLee Schermerhorn 
3596af936a16SLee Schermerhorn /*
3597af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3598af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3599af936a16SLee Schermerhorn  */
3600af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3601af936a16SLee Schermerhorn 
3602af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
36038d65af78SAlexey Dobriyan 			   void __user *buffer,
3604af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3605af936a16SLee Schermerhorn {
3606264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
36078d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3608af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3609af936a16SLee Schermerhorn 	return 0;
3610af936a16SLee Schermerhorn }
3611af936a16SLee Schermerhorn 
3612e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3613af936a16SLee Schermerhorn /*
3614af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3615af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3616af936a16SLee Schermerhorn  */
3617af936a16SLee Schermerhorn 
361810fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
361910fbcf4cSKay Sievers 					  struct device_attribute *attr,
3620af936a16SLee Schermerhorn 					  char *buf)
3621af936a16SLee Schermerhorn {
3622264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3623af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3624af936a16SLee Schermerhorn }
3625af936a16SLee Schermerhorn 
362610fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
362710fbcf4cSKay Sievers 					   struct device_attribute *attr,
3628af936a16SLee Schermerhorn 					const char *buf, size_t count)
3629af936a16SLee Schermerhorn {
3630264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3631af936a16SLee Schermerhorn 	return 1;
3632af936a16SLee Schermerhorn }
3633af936a16SLee Schermerhorn 
3634af936a16SLee Schermerhorn 
363510fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3636af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3637af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3638af936a16SLee Schermerhorn 
3639af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3640af936a16SLee Schermerhorn {
364110fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3642af936a16SLee Schermerhorn }
3643af936a16SLee Schermerhorn 
3644af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3645af936a16SLee Schermerhorn {
364610fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3647af936a16SLee Schermerhorn }
3648e4455abbSThadeu Lima de Souza Cascardo #endif
3649