xref: /openbmc/linux/mm/vmscan.c (revision b1a6f21e3b2315d46ae8af88a8f4eb8ea2763107)
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 
672e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
673e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
674e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
675e2be15f6SMel Gorman {
676e2be15f6SMel Gorman 	/*
677e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
678e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
679e2be15f6SMel Gorman 	 */
680e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
681e2be15f6SMel Gorman 		*dirty = false;
682e2be15f6SMel Gorman 		*writeback = false;
683e2be15f6SMel Gorman 		return;
684e2be15f6SMel Gorman 	}
685e2be15f6SMel Gorman 
686e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
687e2be15f6SMel Gorman 	*dirty = PageDirty(page);
688e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
689e2be15f6SMel Gorman }
690e2be15f6SMel Gorman 
691e286781dSNick Piggin /*
6921742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
6931da177e4SLinus Torvalds  */
6941742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
6956a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
696f84f6e2bSMel Gorman 				      struct scan_control *sc,
69702c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
698d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
69902c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
700*b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
70102c6de8dSMinchan Kim 				      bool force_reclaim)
7021da177e4SLinus Torvalds {
7031da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
704abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
7051da177e4SLinus Torvalds 	int pgactivate = 0;
706d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
7070e093d99SMel Gorman 	unsigned long nr_dirty = 0;
7080e093d99SMel Gorman 	unsigned long nr_congested = 0;
70905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
71092df3a72SMel Gorman 	unsigned long nr_writeback = 0;
711*b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
7121da177e4SLinus Torvalds 
7131da177e4SLinus Torvalds 	cond_resched();
7141da177e4SLinus Torvalds 
71569980e31STim Chen 	mem_cgroup_uncharge_start();
7161da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
7171da177e4SLinus Torvalds 		struct address_space *mapping;
7181da177e4SLinus Torvalds 		struct page *page;
7191da177e4SLinus Torvalds 		int may_enter_fs;
72002c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
721e2be15f6SMel Gorman 		bool dirty, writeback;
7221da177e4SLinus Torvalds 
7231da177e4SLinus Torvalds 		cond_resched();
7241da177e4SLinus Torvalds 
7251da177e4SLinus Torvalds 		page = lru_to_page(page_list);
7261da177e4SLinus Torvalds 		list_del(&page->lru);
7271da177e4SLinus Torvalds 
728529ae9aaSNick Piggin 		if (!trylock_page(page))
7291da177e4SLinus Torvalds 			goto keep;
7301da177e4SLinus Torvalds 
731725d704eSNick Piggin 		VM_BUG_ON(PageActive(page));
7326a18adb3SKonstantin Khlebnikov 		VM_BUG_ON(page_zone(page) != zone);
7331da177e4SLinus Torvalds 
7341da177e4SLinus Torvalds 		sc->nr_scanned++;
73580e43426SChristoph Lameter 
73639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
737b291f000SNick Piggin 			goto cull_mlocked;
738894bc310SLee Schermerhorn 
739a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
74080e43426SChristoph Lameter 			goto keep_locked;
74180e43426SChristoph Lameter 
7421da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
7431da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
7441da177e4SLinus Torvalds 			sc->nr_scanned++;
7451da177e4SLinus Torvalds 
746c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
747c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
748c661b078SAndy Whitcroft 
749e62e384eSMichal Hocko 		/*
750e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
751e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
752e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
753e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
754e2be15f6SMel Gorman 		 */
755e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
756e2be15f6SMel Gorman 		if (dirty || writeback)
757e2be15f6SMel Gorman 			nr_dirty++;
758e2be15f6SMel Gorman 
759e2be15f6SMel Gorman 		if (dirty && !writeback)
760e2be15f6SMel Gorman 			nr_unqueued_dirty++;
761e2be15f6SMel Gorman 
762e2be15f6SMel Gorman 		/* Treat this page as congested if underlying BDI is */
763e2be15f6SMel Gorman 		mapping = page_mapping(page);
764e2be15f6SMel Gorman 		if (mapping && bdi_write_congested(mapping->backing_dev_info))
765e2be15f6SMel Gorman 			nr_congested++;
766e2be15f6SMel Gorman 
767e2be15f6SMel Gorman 		/*
768283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
769283aba9fSMel Gorman 		 * are three cases to consider.
770e62e384eSMichal Hocko 		 *
771283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
772283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
773283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
774283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
775283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
776283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
777283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
778*b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
779*b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
780c3b94f44SHugh Dickins 		 *
781283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
782283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
783283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
784283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
785283aba9fSMel Gorman 		 *
786283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
787283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
788283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
789283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
790283aba9fSMel Gorman 		 *    would probably show more reasons.
791283aba9fSMel Gorman 		 *
792283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
793283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
794283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
795283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
796283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
797283aba9fSMel Gorman 		 *
798283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
799283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
800283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
801283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
802283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
803e62e384eSMichal Hocko 		 */
804283aba9fSMel Gorman 		if (PageWriteback(page)) {
805283aba9fSMel Gorman 			/* Case 1 above */
806283aba9fSMel Gorman 			if (current_is_kswapd() &&
807283aba9fSMel Gorman 			    PageReclaim(page) &&
808283aba9fSMel Gorman 			    zone_is_reclaim_writeback(zone)) {
809*b1a6f21eSMel Gorman 				nr_immediate++;
810*b1a6f21eSMel Gorman 				goto keep_locked;
811283aba9fSMel Gorman 
812283aba9fSMel Gorman 			/* Case 2 above */
813283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
814c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
815c3b94f44SHugh Dickins 				/*
816c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
817c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
818c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
819c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
820c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
821c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
822c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
823c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
824c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
825c3b94f44SHugh Dickins 				 */
826c3b94f44SHugh Dickins 				SetPageReclaim(page);
82792df3a72SMel Gorman 				nr_writeback++;
828283aba9fSMel Gorman 
829c3b94f44SHugh Dickins 				goto keep_locked;
830283aba9fSMel Gorman 
831283aba9fSMel Gorman 			/* Case 3 above */
832283aba9fSMel Gorman 			} else {
833c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
834e62e384eSMichal Hocko 			}
835283aba9fSMel Gorman 		}
8361da177e4SLinus Torvalds 
83702c6de8dSMinchan Kim 		if (!force_reclaim)
8386a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
83902c6de8dSMinchan Kim 
840dfc8d636SJohannes Weiner 		switch (references) {
841dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
8421da177e4SLinus Torvalds 			goto activate_locked;
84364574746SJohannes Weiner 		case PAGEREF_KEEP:
84464574746SJohannes Weiner 			goto keep_locked;
845dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
846dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
847dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
848dfc8d636SJohannes Weiner 		}
8491da177e4SLinus Torvalds 
8501da177e4SLinus Torvalds 		/*
8511da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
8521da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
8531da177e4SLinus Torvalds 		 */
854b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
85563eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
85663eb6b93SHugh Dickins 				goto keep_locked;
8575bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
8581da177e4SLinus Torvalds 				goto activate_locked;
85963eb6b93SHugh Dickins 			may_enter_fs = 1;
8601da177e4SLinus Torvalds 
861e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
8621da177e4SLinus Torvalds 			mapping = page_mapping(page);
863e2be15f6SMel Gorman 		}
8641da177e4SLinus Torvalds 
8651da177e4SLinus Torvalds 		/*
8661da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
8671da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
8681da177e4SLinus Torvalds 		 */
8691da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
87002c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
8711da177e4SLinus Torvalds 			case SWAP_FAIL:
8721da177e4SLinus Torvalds 				goto activate_locked;
8731da177e4SLinus Torvalds 			case SWAP_AGAIN:
8741da177e4SLinus Torvalds 				goto keep_locked;
875b291f000SNick Piggin 			case SWAP_MLOCK:
876b291f000SNick Piggin 				goto cull_mlocked;
8771da177e4SLinus Torvalds 			case SWAP_SUCCESS:
8781da177e4SLinus Torvalds 				; /* try to free the page below */
8791da177e4SLinus Torvalds 			}
8801da177e4SLinus Torvalds 		}
8811da177e4SLinus Torvalds 
8821da177e4SLinus Torvalds 		if (PageDirty(page)) {
883ee72886dSMel Gorman 			/*
884ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
885d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
886d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
887ee72886dSMel Gorman 			 */
888f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
8899e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
890d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
89149ea7eb6SMel Gorman 				/*
89249ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
89349ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
89449ea7eb6SMel Gorman 				 * except we already have the page isolated
89549ea7eb6SMel Gorman 				 * and know it's dirty
89649ea7eb6SMel Gorman 				 */
89749ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
89849ea7eb6SMel Gorman 				SetPageReclaim(page);
89949ea7eb6SMel Gorman 
900ee72886dSMel Gorman 				goto keep_locked;
901ee72886dSMel Gorman 			}
902ee72886dSMel Gorman 
903dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
9041da177e4SLinus Torvalds 				goto keep_locked;
9054dd4b920SAndrew Morton 			if (!may_enter_fs)
9061da177e4SLinus Torvalds 				goto keep_locked;
90752a8363eSChristoph Lameter 			if (!sc->may_writepage)
9081da177e4SLinus Torvalds 				goto keep_locked;
9091da177e4SLinus Torvalds 
9101da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
9117d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
9121da177e4SLinus Torvalds 			case PAGE_KEEP:
9131da177e4SLinus Torvalds 				goto keep_locked;
9141da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
9151da177e4SLinus Torvalds 				goto activate_locked;
9161da177e4SLinus Torvalds 			case PAGE_SUCCESS:
9177d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
91841ac1999SMel Gorman 					goto keep;
9197d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
9201da177e4SLinus Torvalds 					goto keep;
9217d3579e8SKOSAKI Motohiro 
9221da177e4SLinus Torvalds 				/*
9231da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
9241da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
9251da177e4SLinus Torvalds 				 */
926529ae9aaSNick Piggin 				if (!trylock_page(page))
9271da177e4SLinus Torvalds 					goto keep;
9281da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
9291da177e4SLinus Torvalds 					goto keep_locked;
9301da177e4SLinus Torvalds 				mapping = page_mapping(page);
9311da177e4SLinus Torvalds 			case PAGE_CLEAN:
9321da177e4SLinus Torvalds 				; /* try to free the page below */
9331da177e4SLinus Torvalds 			}
9341da177e4SLinus Torvalds 		}
9351da177e4SLinus Torvalds 
9361da177e4SLinus Torvalds 		/*
9371da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
9381da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
9391da177e4SLinus Torvalds 		 * the page as well.
9401da177e4SLinus Torvalds 		 *
9411da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
9421da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
9431da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
9441da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
9451da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
9461da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
9471da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
9481da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
9491da177e4SLinus Torvalds 		 *
9501da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
9511da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
9521da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
9531da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
9541da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
9551da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
9561da177e4SLinus Torvalds 		 */
957266cf658SDavid Howells 		if (page_has_private(page)) {
9581da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
9591da177e4SLinus Torvalds 				goto activate_locked;
960e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
961e286781dSNick Piggin 				unlock_page(page);
962e286781dSNick Piggin 				if (put_page_testzero(page))
9631da177e4SLinus Torvalds 					goto free_it;
964e286781dSNick Piggin 				else {
965e286781dSNick Piggin 					/*
966e286781dSNick Piggin 					 * rare race with speculative reference.
967e286781dSNick Piggin 					 * the speculative reference will free
968e286781dSNick Piggin 					 * this page shortly, so we may
969e286781dSNick Piggin 					 * increment nr_reclaimed here (and
970e286781dSNick Piggin 					 * leave it off the LRU).
971e286781dSNick Piggin 					 */
972e286781dSNick Piggin 					nr_reclaimed++;
973e286781dSNick Piggin 					continue;
974e286781dSNick Piggin 				}
975e286781dSNick Piggin 			}
9761da177e4SLinus Torvalds 		}
9771da177e4SLinus Torvalds 
978e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
97949d2e9ccSChristoph Lameter 			goto keep_locked;
9801da177e4SLinus Torvalds 
981a978d6f5SNick Piggin 		/*
982a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
983a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
984a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
985a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
986a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
987a978d6f5SNick Piggin 		 */
988a978d6f5SNick Piggin 		__clear_page_locked(page);
989e286781dSNick Piggin free_it:
99005ff5137SAndrew Morton 		nr_reclaimed++;
991abe4c3b5SMel Gorman 
992abe4c3b5SMel Gorman 		/*
993abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
994abe4c3b5SMel Gorman 		 * appear not as the counts should be low
995abe4c3b5SMel Gorman 		 */
996abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
9971da177e4SLinus Torvalds 		continue;
9981da177e4SLinus Torvalds 
999b291f000SNick Piggin cull_mlocked:
100063d6c5adSHugh Dickins 		if (PageSwapCache(page))
100163d6c5adSHugh Dickins 			try_to_free_swap(page);
1002b291f000SNick Piggin 		unlock_page(page);
1003b291f000SNick Piggin 		putback_lru_page(page);
1004b291f000SNick Piggin 		continue;
1005b291f000SNick Piggin 
10061da177e4SLinus Torvalds activate_locked:
100768a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
100868a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1009a2c43eedSHugh Dickins 			try_to_free_swap(page);
1010894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
10111da177e4SLinus Torvalds 		SetPageActive(page);
10121da177e4SLinus Torvalds 		pgactivate++;
10131da177e4SLinus Torvalds keep_locked:
10141da177e4SLinus Torvalds 		unlock_page(page);
10151da177e4SLinus Torvalds keep:
10161da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1017b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
10181da177e4SLinus Torvalds 	}
1019abe4c3b5SMel Gorman 
10200e093d99SMel Gorman 	/*
10210e093d99SMel Gorman 	 * Tag a zone as congested if all the dirty pages encountered were
10220e093d99SMel Gorman 	 * backed by a congested BDI. In this case, reclaimers should just
10230e093d99SMel Gorman 	 * back off and wait for congestion to clear because further reclaim
10240e093d99SMel Gorman 	 * will encounter the same problem
10250e093d99SMel Gorman 	 */
102689b5fae5SJohannes Weiner 	if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
10276a18adb3SKonstantin Khlebnikov 		zone_set_flag(zone, ZONE_CONGESTED);
10280e093d99SMel Gorman 
1029cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
1030abe4c3b5SMel Gorman 
10311da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1032f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
103369980e31STim Chen 	mem_cgroup_uncharge_end();
1034d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
103592df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1036*b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
103705ff5137SAndrew Morton 	return nr_reclaimed;
10381da177e4SLinus Torvalds }
10391da177e4SLinus Torvalds 
104002c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
104102c6de8dSMinchan Kim 					    struct list_head *page_list)
104202c6de8dSMinchan Kim {
104302c6de8dSMinchan Kim 	struct scan_control sc = {
104402c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
104502c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
104602c6de8dSMinchan Kim 		.may_unmap = 1,
104702c6de8dSMinchan Kim 	};
1048*b1a6f21eSMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3;
104902c6de8dSMinchan Kim 	struct page *page, *next;
105002c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
105102c6de8dSMinchan Kim 
105202c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
105302c6de8dSMinchan Kim 		if (page_is_file_cache(page) && !PageDirty(page)) {
105402c6de8dSMinchan Kim 			ClearPageActive(page);
105502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
105602c6de8dSMinchan Kim 		}
105702c6de8dSMinchan Kim 	}
105802c6de8dSMinchan Kim 
105902c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
106002c6de8dSMinchan Kim 				TTU_UNMAP|TTU_IGNORE_ACCESS,
1061*b1a6f21eSMel Gorman 				&dummy1, &dummy2, &dummy3, true);
106202c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
106302c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
106402c6de8dSMinchan Kim 	return ret;
106502c6de8dSMinchan Kim }
106602c6de8dSMinchan Kim 
10675ad333ebSAndy Whitcroft /*
10685ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
10695ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
10705ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
10715ad333ebSAndy Whitcroft  *
10725ad333ebSAndy Whitcroft  * page:	page to consider
10735ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
10745ad333ebSAndy Whitcroft  *
10755ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
10765ad333ebSAndy Whitcroft  */
1077f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
10785ad333ebSAndy Whitcroft {
10795ad333ebSAndy Whitcroft 	int ret = -EINVAL;
10805ad333ebSAndy Whitcroft 
10815ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
10825ad333ebSAndy Whitcroft 	if (!PageLRU(page))
10835ad333ebSAndy Whitcroft 		return ret;
10845ad333ebSAndy Whitcroft 
1085e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1086e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1087894bc310SLee Schermerhorn 		return ret;
1088894bc310SLee Schermerhorn 
10895ad333ebSAndy Whitcroft 	ret = -EBUSY;
109008e552c6SKAMEZAWA Hiroyuki 
1091c8244935SMel Gorman 	/*
1092c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1093c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1094c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1095c8244935SMel Gorman 	 *
1096c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1097c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1098c8244935SMel Gorman 	 *
1099c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1100c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1101c8244935SMel Gorman 	 */
1102c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1103c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1104c8244935SMel Gorman 		if (PageWriteback(page))
110539deaf85SMinchan Kim 			return ret;
110639deaf85SMinchan Kim 
1107c8244935SMel Gorman 		if (PageDirty(page)) {
1108c8244935SMel Gorman 			struct address_space *mapping;
1109c8244935SMel Gorman 
1110c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1111c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1112c8244935SMel Gorman 				return ret;
1113c8244935SMel Gorman 
1114c8244935SMel Gorman 			/*
1115c8244935SMel Gorman 			 * Only pages without mappings or that have a
1116c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1117c8244935SMel Gorman 			 * without blocking
1118c8244935SMel Gorman 			 */
1119c8244935SMel Gorman 			mapping = page_mapping(page);
1120c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1121c8244935SMel Gorman 				return ret;
1122c8244935SMel Gorman 		}
1123c8244935SMel Gorman 	}
1124c8244935SMel Gorman 
1125f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1126f80c0673SMinchan Kim 		return ret;
1127f80c0673SMinchan Kim 
11285ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
11295ad333ebSAndy Whitcroft 		/*
11305ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
11315ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
11325ad333ebSAndy Whitcroft 		 * page release code relies on it.
11335ad333ebSAndy Whitcroft 		 */
11345ad333ebSAndy Whitcroft 		ClearPageLRU(page);
11355ad333ebSAndy Whitcroft 		ret = 0;
11365ad333ebSAndy Whitcroft 	}
11375ad333ebSAndy Whitcroft 
11385ad333ebSAndy Whitcroft 	return ret;
11395ad333ebSAndy Whitcroft }
11405ad333ebSAndy Whitcroft 
114149d2e9ccSChristoph Lameter /*
11421da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
11431da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
11441da177e4SLinus Torvalds  * and working on them outside the LRU lock.
11451da177e4SLinus Torvalds  *
11461da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
11471da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
11481da177e4SLinus Torvalds  *
11491da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
11501da177e4SLinus Torvalds  *
11511da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
11525dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
11531da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1154f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1155fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
11565ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
11573cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
11581da177e4SLinus Torvalds  *
11591da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
11601da177e4SLinus Torvalds  */
116169e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
11625dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1163fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
11643cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
11651da177e4SLinus Torvalds {
116675b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
116769e05944SAndrew Morton 	unsigned long nr_taken = 0;
1168c9b02d97SWu Fengguang 	unsigned long scan;
11691da177e4SLinus Torvalds 
1170c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
11715ad333ebSAndy Whitcroft 		struct page *page;
1172fa9add64SHugh Dickins 		int nr_pages;
11735ad333ebSAndy Whitcroft 
11741da177e4SLinus Torvalds 		page = lru_to_page(src);
11751da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
11761da177e4SLinus Torvalds 
1177725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
11788d438f96SNick Piggin 
1179f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
11805ad333ebSAndy Whitcroft 		case 0:
1181fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1182fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
11835ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1184fa9add64SHugh Dickins 			nr_taken += nr_pages;
11855ad333ebSAndy Whitcroft 			break;
11867c8ee9a8SNick Piggin 
11875ad333ebSAndy Whitcroft 		case -EBUSY:
11885ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
11895ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
11905ad333ebSAndy Whitcroft 			continue;
11915ad333ebSAndy Whitcroft 
11925ad333ebSAndy Whitcroft 		default:
11935ad333ebSAndy Whitcroft 			BUG();
11945ad333ebSAndy Whitcroft 		}
11955ad333ebSAndy Whitcroft 	}
11961da177e4SLinus Torvalds 
1197f626012dSHugh Dickins 	*nr_scanned = scan;
119875b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
119975b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
12001da177e4SLinus Torvalds 	return nr_taken;
12011da177e4SLinus Torvalds }
12021da177e4SLinus Torvalds 
120362695a84SNick Piggin /**
120462695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
120562695a84SNick Piggin  * @page: page to isolate from its LRU list
120662695a84SNick Piggin  *
120762695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
120862695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
120962695a84SNick Piggin  *
121062695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
121162695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
121262695a84SNick Piggin  *
121362695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1214894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1215894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1216894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
121762695a84SNick Piggin  *
121862695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
121962695a84SNick Piggin  * found will be decremented.
122062695a84SNick Piggin  *
122162695a84SNick Piggin  * Restrictions:
122262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
122362695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
122462695a84SNick Piggin  *     without a stable reference).
122562695a84SNick Piggin  * (2) the lru_lock must not be held.
122662695a84SNick Piggin  * (3) interrupts must be enabled.
122762695a84SNick Piggin  */
122862695a84SNick Piggin int isolate_lru_page(struct page *page)
122962695a84SNick Piggin {
123062695a84SNick Piggin 	int ret = -EBUSY;
123162695a84SNick Piggin 
12320c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
12330c917313SKonstantin Khlebnikov 
123462695a84SNick Piggin 	if (PageLRU(page)) {
123562695a84SNick Piggin 		struct zone *zone = page_zone(page);
1236fa9add64SHugh Dickins 		struct lruvec *lruvec;
123762695a84SNick Piggin 
123862695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1239fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
12400c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1241894bc310SLee Schermerhorn 			int lru = page_lru(page);
12420c917313SKonstantin Khlebnikov 			get_page(page);
124362695a84SNick Piggin 			ClearPageLRU(page);
1244fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1245fa9add64SHugh Dickins 			ret = 0;
124662695a84SNick Piggin 		}
124762695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
124862695a84SNick Piggin 	}
124962695a84SNick Piggin 	return ret;
125062695a84SNick Piggin }
125162695a84SNick Piggin 
12525ad333ebSAndy Whitcroft /*
1253d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1254d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1255d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1256d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1257d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
125835cd7815SRik van Riel  */
125935cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
126035cd7815SRik van Riel 		struct scan_control *sc)
126135cd7815SRik van Riel {
126235cd7815SRik van Riel 	unsigned long inactive, isolated;
126335cd7815SRik van Riel 
126435cd7815SRik van Riel 	if (current_is_kswapd())
126535cd7815SRik van Riel 		return 0;
126635cd7815SRik van Riel 
126789b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
126835cd7815SRik van Riel 		return 0;
126935cd7815SRik van Riel 
127035cd7815SRik van Riel 	if (file) {
127135cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
127235cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
127335cd7815SRik van Riel 	} else {
127435cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
127535cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
127635cd7815SRik van Riel 	}
127735cd7815SRik van Riel 
12783cf23841SFengguang Wu 	/*
12793cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
12803cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
12813cf23841SFengguang Wu 	 * deadlock.
12823cf23841SFengguang Wu 	 */
12833cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
12843cf23841SFengguang Wu 		inactive >>= 3;
12853cf23841SFengguang Wu 
128635cd7815SRik van Riel 	return isolated > inactive;
128735cd7815SRik van Riel }
128835cd7815SRik van Riel 
128966635629SMel Gorman static noinline_for_stack void
129075b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
129166635629SMel Gorman {
129227ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
129327ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
12943f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
129566635629SMel Gorman 
129666635629SMel Gorman 	/*
129766635629SMel Gorman 	 * Put back any unfreeable pages.
129866635629SMel Gorman 	 */
129966635629SMel Gorman 	while (!list_empty(page_list)) {
13003f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
130166635629SMel Gorman 		int lru;
13023f79768fSHugh Dickins 
130366635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
130466635629SMel Gorman 		list_del(&page->lru);
130539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
130666635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
130766635629SMel Gorman 			putback_lru_page(page);
130866635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
130966635629SMel Gorman 			continue;
131066635629SMel Gorman 		}
1311fa9add64SHugh Dickins 
1312fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1313fa9add64SHugh Dickins 
13147a608572SLinus Torvalds 		SetPageLRU(page);
131566635629SMel Gorman 		lru = page_lru(page);
1316fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1317fa9add64SHugh Dickins 
131866635629SMel Gorman 		if (is_active_lru(lru)) {
131966635629SMel Gorman 			int file = is_file_lru(lru);
13209992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
13219992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
132266635629SMel Gorman 		}
13232bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
13242bcf8879SHugh Dickins 			__ClearPageLRU(page);
13252bcf8879SHugh Dickins 			__ClearPageActive(page);
1326fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
13272bcf8879SHugh Dickins 
13282bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
132966635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
13302bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
133166635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
13322bcf8879SHugh Dickins 			} else
13332bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
133466635629SMel Gorman 		}
133566635629SMel Gorman 	}
133666635629SMel Gorman 
13373f79768fSHugh Dickins 	/*
13383f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
13393f79768fSHugh Dickins 	 */
13403f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
134166635629SMel Gorman }
134266635629SMel Gorman 
134366635629SMel Gorman /*
13441742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
13451742f19fSAndrew Morton  * of reclaimed pages
13461da177e4SLinus Torvalds  */
134766635629SMel Gorman static noinline_for_stack unsigned long
13481a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
13499e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
13501da177e4SLinus Torvalds {
13511da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1352e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
135305ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1354e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1355e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
135692df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1357*b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1358f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
13593cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
13601a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13611a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
136278dc583dSKOSAKI Motohiro 
136335cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
136458355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
136535cd7815SRik van Riel 
136635cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
136735cd7815SRik van Riel 		if (fatal_signal_pending(current))
136835cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
136935cd7815SRik van Riel 	}
137035cd7815SRik van Riel 
13711da177e4SLinus Torvalds 	lru_add_drain();
1372f80c0673SMinchan Kim 
1373f80c0673SMinchan Kim 	if (!sc->may_unmap)
137461317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1375f80c0673SMinchan Kim 	if (!sc->may_writepage)
137661317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1377f80c0673SMinchan Kim 
13781da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
13791da177e4SLinus Torvalds 
13805dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
13815dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
138295d918fcSKonstantin Khlebnikov 
138395d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
138495d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
138595d918fcSKonstantin Khlebnikov 
138689b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1387e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1388b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
138975b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1390b35ea17bSKOSAKI Motohiro 		else
139175b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1392b35ea17bSKOSAKI Motohiro 	}
139366635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1394d563c050SHillf Danton 
1395d563c050SHillf Danton 	if (nr_taken == 0)
139666635629SMel Gorman 		return 0;
1397b35ea17bSKOSAKI Motohiro 
139802c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
1399*b1a6f21eSMel Gorman 			&nr_unqueued_dirty, &nr_writeback, &nr_immediate,
1400*b1a6f21eSMel Gorman 			false);
1401c661b078SAndy Whitcroft 
14023f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
14033f79768fSHugh Dickins 
140495d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1405d563c050SHillf Danton 
1406904249aaSYing Han 	if (global_reclaim(sc)) {
1407b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1408904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1409904249aaSYing Han 					       nr_reclaimed);
1410904249aaSYing Han 		else
1411904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1412904249aaSYing Han 					       nr_reclaimed);
1413904249aaSYing Han 	}
1414a74609faSNick Piggin 
141527ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
14163f79768fSHugh Dickins 
141795d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
14183f79768fSHugh Dickins 
14193f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
14203f79768fSHugh Dickins 
14213f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1422e11da5b4SMel Gorman 
142392df3a72SMel Gorman 	/*
142492df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
142592df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
142692df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
142792df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
142892df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
142992df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
143092df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
143192df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
143292df3a72SMel Gorman 	 *
143392df3a72SMel Gorman 	 * This scales the number of dirty pages that must be under writeback
143492df3a72SMel Gorman 	 * before throttling depending on priority. It is a simple backoff
143592df3a72SMel Gorman 	 * function that has the most effect in the range DEF_PRIORITY to
143692df3a72SMel Gorman 	 * DEF_PRIORITY-2 which is the priority reclaim is considered to be
143792df3a72SMel Gorman 	 * in trouble and reclaim is considered to be in trouble.
143892df3a72SMel Gorman 	 *
143992df3a72SMel Gorman 	 * DEF_PRIORITY   100% isolated pages must be PageWriteback to throttle
144092df3a72SMel Gorman 	 * DEF_PRIORITY-1  50% must be PageWriteback
144192df3a72SMel Gorman 	 * DEF_PRIORITY-2  25% must be PageWriteback, kswapd in trouble
144292df3a72SMel Gorman 	 * ...
144392df3a72SMel Gorman 	 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
144492df3a72SMel Gorman 	 *                     isolated page is PageWriteback
144592df3a72SMel Gorman 	 */
14469e3b2f8cSKonstantin Khlebnikov 	if (nr_writeback && nr_writeback >=
1447283aba9fSMel Gorman 			(nr_taken >> (DEF_PRIORITY - sc->priority))) {
144892df3a72SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1449283aba9fSMel Gorman 		zone_set_flag(zone, ZONE_WRITEBACK);
1450283aba9fSMel Gorman 	}
145192df3a72SMel Gorman 
1452d43006d5SMel Gorman 	/*
1453*b1a6f21eSMel Gorman 	 * memcg will stall in page writeback so only consider forcibly
1454*b1a6f21eSMel Gorman 	 * stalling for global reclaim
1455d43006d5SMel Gorman 	 */
1456*b1a6f21eSMel Gorman 	if (global_reclaim(sc)) {
1457*b1a6f21eSMel Gorman 		/*
1458*b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1459*b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1460*b1a6f21eSMel Gorman 		 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1461*b1a6f21eSMel Gorman 		 * pages from reclaim context. It will forcibly stall in the
1462*b1a6f21eSMel Gorman 		 * next check.
1463*b1a6f21eSMel Gorman 		 */
1464*b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1465d43006d5SMel Gorman 			zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1466*b1a6f21eSMel Gorman 
1467*b1a6f21eSMel Gorman 		/*
1468*b1a6f21eSMel Gorman 		 * In addition, if kswapd scans pages marked marked for
1469*b1a6f21eSMel Gorman 		 * immediate reclaim and under writeback (nr_immediate), it
1470*b1a6f21eSMel Gorman 		 * implies that pages are cycling through the LRU faster than
1471*b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1472*b1a6f21eSMel Gorman 		 */
1473*b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken || nr_immediate)
1474*b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1475e2be15f6SMel Gorman 	}
1476d43006d5SMel Gorman 
1477e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1478e11da5b4SMel Gorman 		zone_idx(zone),
1479e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
14809e3b2f8cSKonstantin Khlebnikov 		sc->priority,
148123b9da55SMel Gorman 		trace_shrink_flags(file));
148205ff5137SAndrew Morton 	return nr_reclaimed;
14831da177e4SLinus Torvalds }
14841da177e4SLinus Torvalds 
14853bb1a852SMartin Bligh /*
14861cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
14871cfb419bSKAMEZAWA Hiroyuki  *
14881cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
14891cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
14901cfb419bSKAMEZAWA Hiroyuki  *
14911cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
14921cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
14931cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
14941cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
14951cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
14961cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
14971cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
14981cfb419bSKAMEZAWA Hiroyuki  *
14991cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
15001cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
15011cfb419bSKAMEZAWA Hiroyuki  */
15021cfb419bSKAMEZAWA Hiroyuki 
1503fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
15043eb4140fSWu Fengguang 				     struct list_head *list,
15052bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
15063eb4140fSWu Fengguang 				     enum lru_list lru)
15073eb4140fSWu Fengguang {
1508fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
15093eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
15103eb4140fSWu Fengguang 	struct page *page;
1511fa9add64SHugh Dickins 	int nr_pages;
15123eb4140fSWu Fengguang 
15133eb4140fSWu Fengguang 	while (!list_empty(list)) {
15143eb4140fSWu Fengguang 		page = lru_to_page(list);
1515fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
15163eb4140fSWu Fengguang 
15173eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
15183eb4140fSWu Fengguang 		SetPageLRU(page);
15193eb4140fSWu Fengguang 
1520fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1521fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1522925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1523fa9add64SHugh Dickins 		pgmoved += nr_pages;
15243eb4140fSWu Fengguang 
15252bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15262bcf8879SHugh Dickins 			__ClearPageLRU(page);
15272bcf8879SHugh Dickins 			__ClearPageActive(page);
1528fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15292bcf8879SHugh Dickins 
15302bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
15313eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
15322bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
15333eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
15342bcf8879SHugh Dickins 			} else
15352bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
15363eb4140fSWu Fengguang 		}
15373eb4140fSWu Fengguang 	}
15383eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
15393eb4140fSWu Fengguang 	if (!is_active_lru(lru))
15403eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
15413eb4140fSWu Fengguang }
15421cfb419bSKAMEZAWA Hiroyuki 
1543f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
15441a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1545f16015fbSJohannes Weiner 			       struct scan_control *sc,
15469e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
15471cfb419bSKAMEZAWA Hiroyuki {
154844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1549f626012dSHugh Dickins 	unsigned long nr_scanned;
15506fe6b7e3SWu Fengguang 	unsigned long vm_flags;
15511cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
15528cab4754SWu Fengguang 	LIST_HEAD(l_active);
1553b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
15541cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
15551a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
155644c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1557f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
15583cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
15591a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
15601cfb419bSKAMEZAWA Hiroyuki 
15611da177e4SLinus Torvalds 	lru_add_drain();
1562f80c0673SMinchan Kim 
1563f80c0673SMinchan Kim 	if (!sc->may_unmap)
156461317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1565f80c0673SMinchan Kim 	if (!sc->may_writepage)
156661317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1567f80c0673SMinchan Kim 
15681da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1569925b7673SJohannes Weiner 
15705dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
15715dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
157289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1573f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
157489b5fae5SJohannes Weiner 
1575b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
15761cfb419bSKAMEZAWA Hiroyuki 
1577f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
15783cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1579a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
15801da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
15811da177e4SLinus Torvalds 
15821da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
15831da177e4SLinus Torvalds 		cond_resched();
15841da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
15851da177e4SLinus Torvalds 		list_del(&page->lru);
15867e9cd484SRik van Riel 
158739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1588894bc310SLee Schermerhorn 			putback_lru_page(page);
1589894bc310SLee Schermerhorn 			continue;
1590894bc310SLee Schermerhorn 		}
1591894bc310SLee Schermerhorn 
1592cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1593cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1594cc715d99SMel Gorman 				if (page_has_private(page))
1595cc715d99SMel Gorman 					try_to_release_page(page, 0);
1596cc715d99SMel Gorman 				unlock_page(page);
1597cc715d99SMel Gorman 			}
1598cc715d99SMel Gorman 		}
1599cc715d99SMel Gorman 
1600c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1601c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
16029992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
16038cab4754SWu Fengguang 			/*
16048cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
16058cab4754SWu Fengguang 			 * give them one more trip around the active list. So
16068cab4754SWu Fengguang 			 * that executable code get better chances to stay in
16078cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
16088cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
16098cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
16108cab4754SWu Fengguang 			 * so we ignore them here.
16118cab4754SWu Fengguang 			 */
161241e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
16138cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
16148cab4754SWu Fengguang 				continue;
16158cab4754SWu Fengguang 			}
16168cab4754SWu Fengguang 		}
16177e9cd484SRik van Riel 
16185205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
16191da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
16201da177e4SLinus Torvalds 	}
16211da177e4SLinus Torvalds 
1622b555749aSAndrew Morton 	/*
16238cab4754SWu Fengguang 	 * Move pages back to the lru list.
1624b555749aSAndrew Morton 	 */
16252a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
16264f98a2feSRik van Riel 	/*
16278cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
16288cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
16298cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
16308cab4754SWu Fengguang 	 * get_scan_ratio.
1631556adecbSRik van Riel 	 */
1632b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1633556adecbSRik van Riel 
1634fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1635fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1636a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1637f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
16382bcf8879SHugh Dickins 
16392bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
16401da177e4SLinus Torvalds }
16411da177e4SLinus Torvalds 
164274e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
164314797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1644f89eb90eSKOSAKI Motohiro {
1645f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1646f89eb90eSKOSAKI Motohiro 
1647f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1648f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1649f89eb90eSKOSAKI Motohiro 
1650f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1651f89eb90eSKOSAKI Motohiro 		return 1;
1652f89eb90eSKOSAKI Motohiro 
1653f89eb90eSKOSAKI Motohiro 	return 0;
1654f89eb90eSKOSAKI Motohiro }
1655f89eb90eSKOSAKI Motohiro 
165614797e23SKOSAKI Motohiro /**
165714797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1658c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
165914797e23SKOSAKI Motohiro  *
166014797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
166114797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
166214797e23SKOSAKI Motohiro  */
1663c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
166414797e23SKOSAKI Motohiro {
166574e3f3c3SMinchan Kim 	/*
166674e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
166774e3f3c3SMinchan Kim 	 * is pointless.
166874e3f3c3SMinchan Kim 	 */
166974e3f3c3SMinchan Kim 	if (!total_swap_pages)
167074e3f3c3SMinchan Kim 		return 0;
167174e3f3c3SMinchan Kim 
1672c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1673c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1674f16015fbSJohannes Weiner 
1675c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
167614797e23SKOSAKI Motohiro }
167774e3f3c3SMinchan Kim #else
1678c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
167974e3f3c3SMinchan Kim {
168074e3f3c3SMinchan Kim 	return 0;
168174e3f3c3SMinchan Kim }
168274e3f3c3SMinchan Kim #endif
168314797e23SKOSAKI Motohiro 
168456e49d21SRik van Riel /**
168556e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1686c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
168756e49d21SRik van Riel  *
168856e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
168956e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
169056e49d21SRik van Riel  * than half of the file pages are on the inactive list.
169156e49d21SRik van Riel  *
169256e49d21SRik van Riel  * Once we get to that situation, protect the system's working
169356e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
169456e49d21SRik van Riel  *
169556e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
169656e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
169756e49d21SRik van Riel  */
1698c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
169956e49d21SRik van Riel {
1700e3790144SJohannes Weiner 	unsigned long inactive;
1701e3790144SJohannes Weiner 	unsigned long active;
170256e49d21SRik van Riel 
1703e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1704e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1705e3790144SJohannes Weiner 
1706e3790144SJohannes Weiner 	return active > inactive;
170756e49d21SRik van Riel }
170856e49d21SRik van Riel 
170975b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1710b39415b2SRik van Riel {
171175b00af7SHugh Dickins 	if (is_file_lru(lru))
1712c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1713b39415b2SRik van Riel 	else
1714c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1715b39415b2SRik van Riel }
1716b39415b2SRik van Riel 
17174f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
17181a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1719b69408e8SChristoph Lameter {
1720b39415b2SRik van Riel 	if (is_active_lru(lru)) {
172175b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
17221a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1723556adecbSRik van Riel 		return 0;
1724556adecbSRik van Riel 	}
1725556adecbSRik van Riel 
17261a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1727b69408e8SChristoph Lameter }
1728b69408e8SChristoph Lameter 
17293d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
17301f4c025bSKAMEZAWA Hiroyuki {
173189b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17321f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
17333d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
17341f4c025bSKAMEZAWA Hiroyuki }
17351f4c025bSKAMEZAWA Hiroyuki 
17369a265114SJohannes Weiner enum scan_balance {
17379a265114SJohannes Weiner 	SCAN_EQUAL,
17389a265114SJohannes Weiner 	SCAN_FRACT,
17399a265114SJohannes Weiner 	SCAN_ANON,
17409a265114SJohannes Weiner 	SCAN_FILE,
17419a265114SJohannes Weiner };
17429a265114SJohannes Weiner 
17431da177e4SLinus Torvalds /*
17444f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
17454f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
17464f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
17474f98a2feSRik van Riel  * onto the active list instead of evict.
17484f98a2feSRik van Riel  *
1749be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1750be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
17514f98a2feSRik van Riel  */
175290126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
17539e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
17544f98a2feSRik van Riel {
175590126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
17569a265114SJohannes Weiner 	u64 fraction[2];
17579a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
175890126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
17599a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
17609a265114SJohannes Weiner 	enum scan_balance scan_balance;
17619a265114SJohannes Weiner 	unsigned long anon, file, free;
17629a265114SJohannes Weiner 	bool force_scan = false;
17639a265114SJohannes Weiner 	unsigned long ap, fp;
17649a265114SJohannes Weiner 	enum lru_list lru;
1765246e87a9SKAMEZAWA Hiroyuki 
1766f11c0ca5SJohannes Weiner 	/*
1767f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1768f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1769f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1770f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1771f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1772f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1773f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1774f11c0ca5SJohannes Weiner 	 * well.
1775f11c0ca5SJohannes Weiner 	 */
177690126375SKonstantin Khlebnikov 	if (current_is_kswapd() && zone->all_unreclaimable)
1777a4d3e9e7SJohannes Weiner 		force_scan = true;
177889b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1779a4d3e9e7SJohannes Weiner 		force_scan = true;
178076a33fc3SShaohua Li 
178176a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1782ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
17839a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
178476a33fc3SShaohua Li 		goto out;
178576a33fc3SShaohua Li 	}
17864f98a2feSRik van Riel 
178710316b31SJohannes Weiner 	/*
178810316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
178910316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
179010316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
179110316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
179210316b31SJohannes Weiner 	 * too expensive.
179310316b31SJohannes Weiner 	 */
179410316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
17959a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
179610316b31SJohannes Weiner 		goto out;
179710316b31SJohannes Weiner 	}
179810316b31SJohannes Weiner 
179910316b31SJohannes Weiner 	/*
180010316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
180110316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
180210316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
180310316b31SJohannes Weiner 	 */
180410316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
18059a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
180610316b31SJohannes Weiner 		goto out;
180710316b31SJohannes Weiner 	}
180810316b31SJohannes Weiner 
18094d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
18104d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
18114d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
18124d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1813a4d3e9e7SJohannes Weiner 
181411d16c25SJohannes Weiner 	/*
181511d16c25SJohannes Weiner 	 * If it's foreseeable that reclaiming the file cache won't be
181611d16c25SJohannes Weiner 	 * enough to get the zone back into a desirable shape, we have
181711d16c25SJohannes Weiner 	 * to swap.  Better start now and leave the - probably heavily
181811d16c25SJohannes Weiner 	 * thrashing - remaining file pages alone.
181911d16c25SJohannes Weiner 	 */
182089b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
182190126375SKonstantin Khlebnikov 		free = zone_page_state(zone, NR_FREE_PAGES);
182290126375SKonstantin Khlebnikov 		if (unlikely(file + free <= high_wmark_pages(zone))) {
18239a265114SJohannes Weiner 			scan_balance = SCAN_ANON;
182476a33fc3SShaohua Li 			goto out;
18257c5bd705SJohannes Weiner 		}
18267c5bd705SJohannes Weiner 	}
18277c5bd705SJohannes Weiner 
1828e9868505SRik van Riel 	/*
18297c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
18307c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1831e9868505SRik van Riel 	 */
18327c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
18339a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1834e9868505SRik van Riel 		goto out;
18354f98a2feSRik van Riel 	}
18364f98a2feSRik van Riel 
18379a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
18389a265114SJohannes Weiner 
18394f98a2feSRik van Riel 	/*
184058c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
184158c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
184258c37f6eSKOSAKI Motohiro 	 */
18433d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
184475b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
184558c37f6eSKOSAKI Motohiro 
184658c37f6eSKOSAKI Motohiro 	/*
18474f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
18484f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
18494f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
18504f98a2feSRik van Riel 	 *
18514f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
18524f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
18534f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
18544f98a2feSRik van Riel 	 *
18554f98a2feSRik van Riel 	 * anon in [0], file in [1]
18564f98a2feSRik van Riel 	 */
185790126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
185858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
18596e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
18606e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
18614f98a2feSRik van Riel 	}
18624f98a2feSRik van Riel 
18636e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
18646e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
18656e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
18664f98a2feSRik van Riel 	}
18674f98a2feSRik van Riel 
18684f98a2feSRik van Riel 	/*
186900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
187000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
187100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
18724f98a2feSRik van Riel 	 */
1873fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
18746e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
18754f98a2feSRik van Riel 
1876fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
18776e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
187890126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
18794f98a2feSRik van Riel 
188076a33fc3SShaohua Li 	fraction[0] = ap;
188176a33fc3SShaohua Li 	fraction[1] = fp;
188276a33fc3SShaohua Li 	denominator = ap + fp + 1;
188376a33fc3SShaohua Li out:
18844111304dSHugh Dickins 	for_each_evictable_lru(lru) {
18854111304dSHugh Dickins 		int file = is_file_lru(lru);
1886d778df51SJohannes Weiner 		unsigned long size;
188776a33fc3SShaohua Li 		unsigned long scan;
188876a33fc3SShaohua Li 
1889d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1890d778df51SJohannes Weiner 		scan = size >> sc->priority;
18919a265114SJohannes Weiner 
1892f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1893d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
18949a265114SJohannes Weiner 
18959a265114SJohannes Weiner 		switch (scan_balance) {
18969a265114SJohannes Weiner 		case SCAN_EQUAL:
18979a265114SJohannes Weiner 			/* Scan lists relative to size */
18989a265114SJohannes Weiner 			break;
18999a265114SJohannes Weiner 		case SCAN_FRACT:
19009a265114SJohannes Weiner 			/*
19019a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
19029a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
19039a265114SJohannes Weiner 			 */
190476a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
19059a265114SJohannes Weiner 			break;
19069a265114SJohannes Weiner 		case SCAN_FILE:
19079a265114SJohannes Weiner 		case SCAN_ANON:
19089a265114SJohannes Weiner 			/* Scan one type exclusively */
19099a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
19109a265114SJohannes Weiner 				scan = 0;
19119a265114SJohannes Weiner 			break;
19129a265114SJohannes Weiner 		default:
19139a265114SJohannes Weiner 			/* Look ma, no brain */
19149a265114SJohannes Weiner 			BUG();
19159a265114SJohannes Weiner 		}
19164111304dSHugh Dickins 		nr[lru] = scan;
191776a33fc3SShaohua Li 	}
19186e08a369SWu Fengguang }
19194f98a2feSRik van Riel 
19209b4f98cdSJohannes Weiner /*
19219b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
19229b4f98cdSJohannes Weiner  */
19239b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
19249b4f98cdSJohannes Weiner {
19259b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
1926e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
19279b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
19289b4f98cdSJohannes Weiner 	enum lru_list lru;
19299b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
19309b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
19319b4f98cdSJohannes Weiner 	struct blk_plug plug;
1932e82e0561SMel Gorman 	bool scan_adjusted = false;
19339b4f98cdSJohannes Weiner 
19349b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
19359b4f98cdSJohannes Weiner 
1936e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
1937e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
1938e82e0561SMel Gorman 
19399b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
19409b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
19419b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
1942e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
1943e82e0561SMel Gorman 		unsigned long nr_scanned;
1944e82e0561SMel Gorman 
19459b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
19469b4f98cdSJohannes Weiner 			if (nr[lru]) {
19479b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
19489b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
19499b4f98cdSJohannes Weiner 
19509b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
19519b4f98cdSJohannes Weiner 							    lruvec, sc);
19529b4f98cdSJohannes Weiner 			}
19539b4f98cdSJohannes Weiner 		}
1954e82e0561SMel Gorman 
1955e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
1956e82e0561SMel Gorman 			continue;
1957e82e0561SMel Gorman 
19589b4f98cdSJohannes Weiner 		/*
1959e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
1960e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
1961e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
1962e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
19639b4f98cdSJohannes Weiner 		 */
1964e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
19659b4f98cdSJohannes Weiner 			break;
1966e82e0561SMel Gorman 
1967e82e0561SMel Gorman 		/*
1968e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
1969e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
1970e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
1971e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
1972e82e0561SMel Gorman 		 * proportional to the original scan target.
1973e82e0561SMel Gorman 		 */
1974e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
1975e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
1976e82e0561SMel Gorman 
1977e82e0561SMel Gorman 		if (nr_file > nr_anon) {
1978e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
1979e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
1980e82e0561SMel Gorman 			lru = LRU_BASE;
1981e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
1982e82e0561SMel Gorman 		} else {
1983e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
1984e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
1985e82e0561SMel Gorman 			lru = LRU_FILE;
1986e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
1987e82e0561SMel Gorman 		}
1988e82e0561SMel Gorman 
1989e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
1990e82e0561SMel Gorman 		nr[lru] = 0;
1991e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
1992e82e0561SMel Gorman 
1993e82e0561SMel Gorman 		/*
1994e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
1995e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
1996e82e0561SMel Gorman 		 */
1997e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
1998e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
1999e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2000e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2001e82e0561SMel Gorman 
2002e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2003e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2004e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2005e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2006e82e0561SMel Gorman 
2007e82e0561SMel Gorman 		scan_adjusted = true;
20089b4f98cdSJohannes Weiner 	}
20099b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
20109b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
20119b4f98cdSJohannes Weiner 
20129b4f98cdSJohannes Weiner 	/*
20139b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
20149b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
20159b4f98cdSJohannes Weiner 	 */
20169b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
20179b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
20189b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
20199b4f98cdSJohannes Weiner 
20209b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
20219b4f98cdSJohannes Weiner }
20229b4f98cdSJohannes Weiner 
202323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
20249e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
202523b9da55SMel Gorman {
2026d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
202723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
20289e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
202923b9da55SMel Gorman 		return true;
203023b9da55SMel Gorman 
203123b9da55SMel Gorman 	return false;
203223b9da55SMel Gorman }
203323b9da55SMel Gorman 
20344f98a2feSRik van Riel /*
203523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
203623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
203723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
203823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
203923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
20403e7d3449SMel Gorman  */
20419b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
20423e7d3449SMel Gorman 					unsigned long nr_reclaimed,
20433e7d3449SMel Gorman 					unsigned long nr_scanned,
20443e7d3449SMel Gorman 					struct scan_control *sc)
20453e7d3449SMel Gorman {
20463e7d3449SMel Gorman 	unsigned long pages_for_compaction;
20473e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
20483e7d3449SMel Gorman 
20493e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
20509e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
20513e7d3449SMel Gorman 		return false;
20523e7d3449SMel Gorman 
20532876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
20542876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
20553e7d3449SMel Gorman 		/*
20562876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
20572876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
20582876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
20592876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
20603e7d3449SMel Gorman 		 */
20613e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
20623e7d3449SMel Gorman 			return false;
20632876592fSMel Gorman 	} else {
20642876592fSMel Gorman 		/*
20652876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
20662876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
20672876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
20682876592fSMel Gorman 		 * pages that were scanned. This will return to the
20692876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
20702876592fSMel Gorman 		 * the resulting allocation attempt fails
20712876592fSMel Gorman 		 */
20722876592fSMel Gorman 		if (!nr_reclaimed)
20732876592fSMel Gorman 			return false;
20742876592fSMel Gorman 	}
20753e7d3449SMel Gorman 
20763e7d3449SMel Gorman 	/*
20773e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
20783e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
20793e7d3449SMel Gorman 	 */
20803e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
20819b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2082ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
20839b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
20843e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
20853e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
20863e7d3449SMel Gorman 		return true;
20873e7d3449SMel Gorman 
20883e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
20899b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
20903e7d3449SMel Gorman 	case COMPACT_PARTIAL:
20913e7d3449SMel Gorman 	case COMPACT_CONTINUE:
20923e7d3449SMel Gorman 		return false;
20933e7d3449SMel Gorman 	default:
20943e7d3449SMel Gorman 		return true;
20953e7d3449SMel Gorman 	}
20963e7d3449SMel Gorman }
20973e7d3449SMel Gorman 
20989e3b2f8cSKonstantin Khlebnikov static void shrink_zone(struct zone *zone, struct scan_control *sc)
2099f16015fbSJohannes Weiner {
21009b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
21019b4f98cdSJohannes Weiner 
21029b4f98cdSJohannes Weiner 	do {
21035660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
21045660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
21055660048cSJohannes Weiner 			.zone = zone,
21069e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
21075660048cSJohannes Weiner 		};
21085660048cSJohannes Weiner 		struct mem_cgroup *memcg;
21095660048cSJohannes Weiner 
21109b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
21119b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
21129b4f98cdSJohannes Weiner 
21135660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
21145660048cSJohannes Weiner 		do {
21159b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
21169b4f98cdSJohannes Weiner 
21179b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
21185660048cSJohannes Weiner 
2119f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2120f9be23d6SKonstantin Khlebnikov 
21215660048cSJohannes Weiner 			/*
2122a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2123a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
21249b4f98cdSJohannes Weiner 			 * zone.
2125a394cb8eSMichal Hocko 			 *
2126a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2127a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2128a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2129a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
21305660048cSJohannes Weiner 			 */
2131a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2132a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
21335660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
21345660048cSJohannes Weiner 				break;
21355660048cSJohannes Weiner 			}
21365660048cSJohannes Weiner 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
21375660048cSJohannes Weiner 		} while (memcg);
213870ddf637SAnton Vorontsov 
213970ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
214070ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
214170ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
214270ddf637SAnton Vorontsov 
21439b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
21449b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2145f16015fbSJohannes Weiner }
2146f16015fbSJohannes Weiner 
2147fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2148fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2149fe4b1b24SMel Gorman {
2150fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2151fe4b1b24SMel Gorman 	bool watermark_ok;
2152fe4b1b24SMel Gorman 
2153fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2154fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2155fe4b1b24SMel Gorman 		return false;
2156fe4b1b24SMel Gorman 
2157fe4b1b24SMel Gorman 	/*
2158fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2159fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2160fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2161fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2162fe4b1b24SMel Gorman 	 */
2163fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2164b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2165fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2166fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2167fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2168fe4b1b24SMel Gorman 
2169fe4b1b24SMel Gorman 	/*
2170fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2171fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2172fe4b1b24SMel Gorman 	 */
2173aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2174fe4b1b24SMel Gorman 		return watermark_ok;
2175fe4b1b24SMel Gorman 
2176fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2177fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2178fe4b1b24SMel Gorman 		return false;
2179fe4b1b24SMel Gorman 
2180fe4b1b24SMel Gorman 	return watermark_ok;
2181fe4b1b24SMel Gorman }
2182fe4b1b24SMel Gorman 
21831da177e4SLinus Torvalds /*
21841da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
21851da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
21861da177e4SLinus Torvalds  * request.
21871da177e4SLinus Torvalds  *
218841858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
218941858966SMel Gorman  * Because:
21901da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
21911da177e4SLinus Torvalds  *    allocation or
219241858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
219341858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
219441858966SMel Gorman  *    zone defense algorithm.
21951da177e4SLinus Torvalds  *
21961da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
21971da177e4SLinus Torvalds  * scan then give up on it.
2198e0c23279SMel Gorman  *
2199e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2200fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
22010cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
22020cee34fdSMel Gorman  * further reclaim.
22031da177e4SLinus Torvalds  */
22049e3b2f8cSKonstantin Khlebnikov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
22051da177e4SLinus Torvalds {
2206dd1a239fSMel Gorman 	struct zoneref *z;
220754a6eb5cSMel Gorman 	struct zone *zone;
2208d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2209d149e3b2SYing Han 	unsigned long nr_soft_scanned;
22100cee34fdSMel Gorman 	bool aborted_reclaim = false;
22111cfb419bSKAMEZAWA Hiroyuki 
2212cc715d99SMel Gorman 	/*
2213cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2214cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2215cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2216cc715d99SMel Gorman 	 */
2217cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2218cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2219cc715d99SMel Gorman 
2220d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2221d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2222f3fe6512SCon Kolivas 		if (!populated_zone(zone))
22231da177e4SLinus Torvalds 			continue;
22241cfb419bSKAMEZAWA Hiroyuki 		/*
22251cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
22261cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
22271cfb419bSKAMEZAWA Hiroyuki 		 */
222889b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
222902a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
22301da177e4SLinus Torvalds 				continue;
22319e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
22329e3b2f8cSKonstantin Khlebnikov 					sc->priority != DEF_PRIORITY)
22331da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2234d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2235e0887c19SRik van Riel 				/*
2236e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2237e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2238e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2239e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2240e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2241c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2242c7cfa37bSCopot Alexandru 				 * page allocations.
2243e0887c19SRik van Riel 				 */
2244fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
22450cee34fdSMel Gorman 					aborted_reclaim = true;
2246e0887c19SRik van Riel 					continue;
2247e0887c19SRik van Riel 				}
2248e0c23279SMel Gorman 			}
2249ac34a1a3SKAMEZAWA Hiroyuki 			/*
2250ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2251ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2252ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2253ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2254ac34a1a3SKAMEZAWA Hiroyuki 			 */
2255d149e3b2SYing Han 			nr_soft_scanned = 0;
2256d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2257d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2258d149e3b2SYing Han 						&nr_soft_scanned);
2259d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2260ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2261ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2262ac34a1a3SKAMEZAWA Hiroyuki 		}
2263d149e3b2SYing Han 
22649e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
22651da177e4SLinus Torvalds 	}
2266e0c23279SMel Gorman 
22670cee34fdSMel Gorman 	return aborted_reclaim;
2268d1908362SMinchan Kim }
2269d1908362SMinchan Kim 
2270d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2271d1908362SMinchan Kim {
2272d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2273d1908362SMinchan Kim }
2274d1908362SMinchan Kim 
2275929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2276d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2277d1908362SMinchan Kim 		struct scan_control *sc)
2278d1908362SMinchan Kim {
2279d1908362SMinchan Kim 	struct zoneref *z;
2280d1908362SMinchan Kim 	struct zone *zone;
2281d1908362SMinchan Kim 
2282d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2283d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2284d1908362SMinchan Kim 		if (!populated_zone(zone))
2285d1908362SMinchan Kim 			continue;
2286d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2287d1908362SMinchan Kim 			continue;
2288929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2289929bea7cSKOSAKI Motohiro 			return false;
2290d1908362SMinchan Kim 	}
2291d1908362SMinchan Kim 
2292929bea7cSKOSAKI Motohiro 	return true;
22931da177e4SLinus Torvalds }
22941da177e4SLinus Torvalds 
22951da177e4SLinus Torvalds /*
22961da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
22971da177e4SLinus Torvalds  *
22981da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
22991da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
23001da177e4SLinus Torvalds  *
23011da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
23021da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
23035b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
23045b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
23055b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
23065b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2307a41f24eaSNishanth Aravamudan  *
2308a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2309a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
23101da177e4SLinus Torvalds  */
2311dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2312a09ed5e0SYing Han 					struct scan_control *sc,
2313a09ed5e0SYing Han 					struct shrink_control *shrink)
23141da177e4SLinus Torvalds {
231569e05944SAndrew Morton 	unsigned long total_scanned = 0;
23161da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2317dd1a239fSMel Gorman 	struct zoneref *z;
231854a6eb5cSMel Gorman 	struct zone *zone;
231922fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
23200cee34fdSMel Gorman 	bool aborted_reclaim;
23211da177e4SLinus Torvalds 
2322873b4771SKeika Kobayashi 	delayacct_freepages_start();
2323873b4771SKeika Kobayashi 
232489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2325f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
23261da177e4SLinus Torvalds 
23279e3b2f8cSKonstantin Khlebnikov 	do {
232870ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
232970ddf637SAnton Vorontsov 				sc->priority);
233066e1707bSBalbir Singh 		sc->nr_scanned = 0;
23319e3b2f8cSKonstantin Khlebnikov 		aborted_reclaim = shrink_zones(zonelist, sc);
2332e0c23279SMel Gorman 
233366e1707bSBalbir Singh 		/*
233466e1707bSBalbir Singh 		 * Don't shrink slabs when reclaiming memory from
233566e1707bSBalbir Singh 		 * over limit cgroups
233666e1707bSBalbir Singh 		 */
233789b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2338c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
2339d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2340d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2341c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2342c6a8a8c5SKOSAKI Motohiro 					continue;
2343c6a8a8c5SKOSAKI Motohiro 
2344c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
2345c6a8a8c5SKOSAKI Motohiro 			}
2346c6a8a8c5SKOSAKI Motohiro 
23471495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
23481da177e4SLinus Torvalds 			if (reclaim_state) {
2349a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
23501da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
23511da177e4SLinus Torvalds 			}
235291a45470SKAMEZAWA Hiroyuki 		}
235366e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2354bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
23551da177e4SLinus Torvalds 			goto out;
23561da177e4SLinus Torvalds 
23571da177e4SLinus Torvalds 		/*
23580e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
23590e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
23600e50ce3bSMinchan Kim 		 */
23610e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
23620e50ce3bSMinchan Kim 			sc->may_writepage = 1;
23630e50ce3bSMinchan Kim 
23640e50ce3bSMinchan Kim 		/*
23651da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
23661da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
23671da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
23681da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
23691da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
23701da177e4SLinus Torvalds 		 */
237122fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
237222fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
23730e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
23740e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
237566e1707bSBalbir Singh 			sc->may_writepage = 1;
23761da177e4SLinus Torvalds 		}
23771da177e4SLinus Torvalds 
23781da177e4SLinus Torvalds 		/* Take a nap, wait for some writeback to complete */
23797b51755cSKOSAKI Motohiro 		if (!sc->hibernation_mode && sc->nr_scanned &&
23809e3b2f8cSKonstantin Khlebnikov 		    sc->priority < DEF_PRIORITY - 2) {
23810e093d99SMel Gorman 			struct zone *preferred_zone;
23820e093d99SMel Gorman 
23830e093d99SMel Gorman 			first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2384f33261d7SDavid Rientjes 						&cpuset_current_mems_allowed,
2385f33261d7SDavid Rientjes 						&preferred_zone);
23860e093d99SMel Gorman 			wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
23870e093d99SMel Gorman 		}
23889e3b2f8cSKonstantin Khlebnikov 	} while (--sc->priority >= 0);
2389bb21c7ceSKOSAKI Motohiro 
23901da177e4SLinus Torvalds out:
2391873b4771SKeika Kobayashi 	delayacct_freepages_end();
2392873b4771SKeika Kobayashi 
2393bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2394bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2395bb21c7ceSKOSAKI Motohiro 
2396929bea7cSKOSAKI Motohiro 	/*
2397929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2398929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2399929bea7cSKOSAKI Motohiro 	 * check.
2400929bea7cSKOSAKI Motohiro 	 */
2401929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2402929bea7cSKOSAKI Motohiro 		return 0;
2403929bea7cSKOSAKI Motohiro 
24040cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
24050cee34fdSMel Gorman 	if (aborted_reclaim)
24067335084dSMel Gorman 		return 1;
24077335084dSMel Gorman 
2408bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
240989b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2410bb21c7ceSKOSAKI Motohiro 		return 1;
2411bb21c7ceSKOSAKI Motohiro 
2412bb21c7ceSKOSAKI Motohiro 	return 0;
24131da177e4SLinus Torvalds }
24141da177e4SLinus Torvalds 
24155515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
24165515061dSMel Gorman {
24175515061dSMel Gorman 	struct zone *zone;
24185515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
24195515061dSMel Gorman 	unsigned long free_pages = 0;
24205515061dSMel Gorman 	int i;
24215515061dSMel Gorman 	bool wmark_ok;
24225515061dSMel Gorman 
24235515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
24245515061dSMel Gorman 		zone = &pgdat->node_zones[i];
24255515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
24265515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
24275515061dSMel Gorman 	}
24285515061dSMel Gorman 
24295515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
24305515061dSMel Gorman 
24315515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
24325515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
24335515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
24345515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
24355515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
24365515061dSMel Gorman 	}
24375515061dSMel Gorman 
24385515061dSMel Gorman 	return wmark_ok;
24395515061dSMel Gorman }
24405515061dSMel Gorman 
24415515061dSMel Gorman /*
24425515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
24435515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
24445515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
244550694c28SMel Gorman  * when the low watermark is reached.
244650694c28SMel Gorman  *
244750694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
244850694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
24495515061dSMel Gorman  */
245050694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
24515515061dSMel Gorman 					nodemask_t *nodemask)
24525515061dSMel Gorman {
24535515061dSMel Gorman 	struct zone *zone;
24545515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
24555515061dSMel Gorman 	pg_data_t *pgdat;
24565515061dSMel Gorman 
24575515061dSMel Gorman 	/*
24585515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
24595515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
24605515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
24615515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
24625515061dSMel Gorman 	 * processes to block on log_wait_commit().
24635515061dSMel Gorman 	 */
24645515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
246550694c28SMel Gorman 		goto out;
246650694c28SMel Gorman 
246750694c28SMel Gorman 	/*
246850694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
246950694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
247050694c28SMel Gorman 	 */
247150694c28SMel Gorman 	if (fatal_signal_pending(current))
247250694c28SMel Gorman 		goto out;
24735515061dSMel Gorman 
24745515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
24755515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
24765515061dSMel Gorman 	pgdat = zone->zone_pgdat;
24775515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
247850694c28SMel Gorman 		goto out;
24795515061dSMel Gorman 
248068243e76SMel Gorman 	/* Account for the throttling */
248168243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
248268243e76SMel Gorman 
24835515061dSMel Gorman 	/*
24845515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
24855515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
24865515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
24875515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
24885515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
24895515061dSMel Gorman 	 * second before continuing.
24905515061dSMel Gorman 	 */
24915515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
24925515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
24935515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
249450694c28SMel Gorman 
249550694c28SMel Gorman 		goto check_pending;
24965515061dSMel Gorman 	}
24975515061dSMel Gorman 
24985515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
24995515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
25005515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
250150694c28SMel Gorman 
250250694c28SMel Gorman check_pending:
250350694c28SMel Gorman 	if (fatal_signal_pending(current))
250450694c28SMel Gorman 		return true;
250550694c28SMel Gorman 
250650694c28SMel Gorman out:
250750694c28SMel Gorman 	return false;
25085515061dSMel Gorman }
25095515061dSMel Gorman 
2510dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2511327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
251266e1707bSBalbir Singh {
251333906bc5SMel Gorman 	unsigned long nr_reclaimed;
251466e1707bSBalbir Singh 	struct scan_control sc = {
251521caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
251666e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
251722fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2518a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25192e2e4259SKOSAKI Motohiro 		.may_swap = 1,
252066e1707bSBalbir Singh 		.order = order,
25219e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2522f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2523327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
252466e1707bSBalbir Singh 	};
2525a09ed5e0SYing Han 	struct shrink_control shrink = {
2526a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2527a09ed5e0SYing Han 	};
252866e1707bSBalbir Singh 
25295515061dSMel Gorman 	/*
253050694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
253150694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
253250694c28SMel Gorman 	 * point.
25335515061dSMel Gorman 	 */
253450694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
25355515061dSMel Gorman 		return 1;
25365515061dSMel Gorman 
253733906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
253833906bc5SMel Gorman 				sc.may_writepage,
253933906bc5SMel Gorman 				gfp_mask);
254033906bc5SMel Gorman 
2541a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
254233906bc5SMel Gorman 
254333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
254433906bc5SMel Gorman 
254533906bc5SMel Gorman 	return nr_reclaimed;
254666e1707bSBalbir Singh }
254766e1707bSBalbir Singh 
2548c255a458SAndrew Morton #ifdef CONFIG_MEMCG
254966e1707bSBalbir Singh 
255072835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
25514e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
25520ae5e89cSYing Han 						struct zone *zone,
25530ae5e89cSYing Han 						unsigned long *nr_scanned)
25544e416953SBalbir Singh {
25554e416953SBalbir Singh 	struct scan_control sc = {
25560ae5e89cSYing Han 		.nr_scanned = 0,
2557b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
25584e416953SBalbir Singh 		.may_writepage = !laptop_mode,
25594e416953SBalbir Singh 		.may_unmap = 1,
25604e416953SBalbir Singh 		.may_swap = !noswap,
25614e416953SBalbir Singh 		.order = 0,
25629e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
256372835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
25644e416953SBalbir Singh 	};
2565f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
25660ae5e89cSYing Han 
25674e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
25684e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2569bdce6d9eSKOSAKI Motohiro 
25709e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2571bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2572bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2573bdce6d9eSKOSAKI Motohiro 
25744e416953SBalbir Singh 	/*
25754e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
25764e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
25774e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
25784e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
25794e416953SBalbir Singh 	 * the priority and make it zero.
25804e416953SBalbir Singh 	 */
2581f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2582bdce6d9eSKOSAKI Motohiro 
2583bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2584bdce6d9eSKOSAKI Motohiro 
25850ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
25864e416953SBalbir Singh 	return sc.nr_reclaimed;
25874e416953SBalbir Singh }
25884e416953SBalbir Singh 
258972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
25908c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2591185efc0fSJohannes Weiner 					   bool noswap)
259266e1707bSBalbir Singh {
25934e416953SBalbir Singh 	struct zonelist *zonelist;
2594bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2595889976dbSYing Han 	int nid;
259666e1707bSBalbir Singh 	struct scan_control sc = {
259766e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2598a6dc60f8SJohannes Weiner 		.may_unmap = 1,
25992e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
260022fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
260166e1707bSBalbir Singh 		.order = 0,
26029e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
260372835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2604327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2605a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2606a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2607a09ed5e0SYing Han 	};
2608a09ed5e0SYing Han 	struct shrink_control shrink = {
2609a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
261066e1707bSBalbir Singh 	};
261166e1707bSBalbir Singh 
2612889976dbSYing Han 	/*
2613889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2614889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2615889976dbSYing Han 	 * scan does not need to be the current node.
2616889976dbSYing Han 	 */
261772835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2618889976dbSYing Han 
2619889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2620bdce6d9eSKOSAKI Motohiro 
2621bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2622bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2623bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2624bdce6d9eSKOSAKI Motohiro 
2625a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2626bdce6d9eSKOSAKI Motohiro 
2627bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2628bdce6d9eSKOSAKI Motohiro 
2629bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
263066e1707bSBalbir Singh }
263166e1707bSBalbir Singh #endif
263266e1707bSBalbir Singh 
26339e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2634f16015fbSJohannes Weiner {
2635b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2636b95a2f2dSJohannes Weiner 
2637b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2638b95a2f2dSJohannes Weiner 		return;
2639b95a2f2dSJohannes Weiner 
2640b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2641b95a2f2dSJohannes Weiner 	do {
2642c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2643f16015fbSJohannes Weiner 
2644c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
26451a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26469e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2647b95a2f2dSJohannes Weiner 
2648b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2649b95a2f2dSJohannes Weiner 	} while (memcg);
2650f16015fbSJohannes Weiner }
2651f16015fbSJohannes Weiner 
265260cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
265360cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
265460cefed4SJohannes Weiner {
265560cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
265660cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
265760cefed4SJohannes Weiner 		return false;
265860cefed4SJohannes Weiner 
2659d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2660d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
266160cefed4SJohannes Weiner 		return false;
266260cefed4SJohannes Weiner 
266360cefed4SJohannes Weiner 	return true;
266460cefed4SJohannes Weiner }
266560cefed4SJohannes Weiner 
26661741c877SMel Gorman /*
26674ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
26684ae0a48bSZlatko Calusic  *
26694ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
26704ae0a48bSZlatko Calusic  *
26714ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
26724ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
26734ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
26744ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
26754ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
26764ae0a48bSZlatko Calusic  * imbalanced zones.
26771741c877SMel Gorman  * The choice of 25% is due to
26781741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
26791741c877SMel Gorman  *     reasonable sized machine
26801741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
268125985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
26821741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
26831741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
26841741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
26851741c877SMel Gorman  */
26864ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
26871741c877SMel Gorman {
2688b40da049SJiang Liu 	unsigned long managed_pages = 0;
26894ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
26901741c877SMel Gorman 	int i;
26911741c877SMel Gorman 
26924ae0a48bSZlatko Calusic 	/* Check the watermark levels */
26934ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
26944ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
26951741c877SMel Gorman 
26964ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
26974ae0a48bSZlatko Calusic 			continue;
26984ae0a48bSZlatko Calusic 
2699b40da049SJiang Liu 		managed_pages += zone->managed_pages;
27004ae0a48bSZlatko Calusic 
27014ae0a48bSZlatko Calusic 		/*
27024ae0a48bSZlatko Calusic 		 * A special case here:
27034ae0a48bSZlatko Calusic 		 *
27044ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
27054ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
27064ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
27074ae0a48bSZlatko Calusic 		 */
27084ae0a48bSZlatko Calusic 		if (zone->all_unreclaimable) {
2709b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27104ae0a48bSZlatko Calusic 			continue;
27114ae0a48bSZlatko Calusic 		}
27124ae0a48bSZlatko Calusic 
27134ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2714b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27154ae0a48bSZlatko Calusic 		else if (!order)
27164ae0a48bSZlatko Calusic 			return false;
27174ae0a48bSZlatko Calusic 	}
27184ae0a48bSZlatko Calusic 
27194ae0a48bSZlatko Calusic 	if (order)
2720b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
27214ae0a48bSZlatko Calusic 	else
27224ae0a48bSZlatko Calusic 		return true;
27231741c877SMel Gorman }
27241741c877SMel Gorman 
27255515061dSMel Gorman /*
27265515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
27275515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
27285515061dSMel Gorman  *
27295515061dSMel Gorman  * Returns true if kswapd is ready to sleep
27305515061dSMel Gorman  */
27315515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2732dc83edd9SMel Gorman 					int classzone_idx)
2733f50de2d3SMel Gorman {
2734f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2735f50de2d3SMel Gorman 	if (remaining)
27365515061dSMel Gorman 		return false;
27375515061dSMel Gorman 
27385515061dSMel Gorman 	/*
27395515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
27405515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
27415515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
27425515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
27435515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
27445515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
27455515061dSMel Gorman 	 * kswapd and get throttled again
27465515061dSMel Gorman 	 */
27475515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
27485515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
27495515061dSMel Gorman 		return false;
27505515061dSMel Gorman 	}
2751f50de2d3SMel Gorman 
27524ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2753f50de2d3SMel Gorman }
2754f50de2d3SMel Gorman 
27551da177e4SLinus Torvalds /*
275675485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
275775485363SMel Gorman  * the high watermark.
2758b8e83b94SMel Gorman  *
2759b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2760283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2761283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
276275485363SMel Gorman  */
2763b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
27647c954f6dSMel Gorman 			       int classzone_idx,
276575485363SMel Gorman 			       struct scan_control *sc,
27662ab44f43SMel Gorman 			       unsigned long lru_pages,
27672ab44f43SMel Gorman 			       unsigned long *nr_attempted)
276875485363SMel Gorman {
276975485363SMel Gorman 	unsigned long nr_slab;
27707c954f6dSMel Gorman 	int testorder = sc->order;
27717c954f6dSMel Gorman 	unsigned long balance_gap;
277275485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
277375485363SMel Gorman 	struct shrink_control shrink = {
277475485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
277575485363SMel Gorman 	};
27767c954f6dSMel Gorman 	bool lowmem_pressure;
277775485363SMel Gorman 
277875485363SMel Gorman 	/* Reclaim above the high watermark. */
277975485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
27807c954f6dSMel Gorman 
27817c954f6dSMel Gorman 	/*
27827c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
27837c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
27847c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
27857c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
27867c954f6dSMel Gorman 	 */
27877c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
27887c954f6dSMel Gorman 			compaction_suitable(zone, sc->order) !=
27897c954f6dSMel Gorman 				COMPACT_SKIPPED)
27907c954f6dSMel Gorman 		testorder = 0;
27917c954f6dSMel Gorman 
27927c954f6dSMel Gorman 	/*
27937c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
27947c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
27957c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
27967c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
27977c954f6dSMel Gorman 	 */
27987c954f6dSMel Gorman 	balance_gap = min(low_wmark_pages(zone),
27997c954f6dSMel Gorman 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28007c954f6dSMel Gorman 		KSWAPD_ZONE_BALANCE_GAP_RATIO);
28017c954f6dSMel Gorman 
28027c954f6dSMel Gorman 	/*
28037c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
28047c954f6dSMel Gorman 	 * reclaim is necessary
28057c954f6dSMel Gorman 	 */
28067c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
28077c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
28087c954f6dSMel Gorman 						balance_gap, classzone_idx))
28097c954f6dSMel Gorman 		return true;
28107c954f6dSMel Gorman 
281175485363SMel Gorman 	shrink_zone(zone, sc);
281275485363SMel Gorman 
281375485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
281475485363SMel Gorman 	nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
281575485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
281675485363SMel Gorman 
28172ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
28182ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
28192ab44f43SMel Gorman 
282075485363SMel Gorman 	if (nr_slab == 0 && !zone_reclaimable(zone))
282175485363SMel Gorman 		zone->all_unreclaimable = 1;
2822b8e83b94SMel Gorman 
2823283aba9fSMel Gorman 	zone_clear_flag(zone, ZONE_WRITEBACK);
2824283aba9fSMel Gorman 
28257c954f6dSMel Gorman 	/*
28267c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
28277c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
28287c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
28297c954f6dSMel Gorman 	 * waits.
28307c954f6dSMel Gorman 	 */
28317c954f6dSMel Gorman 	if (!zone->all_unreclaimable &&
28327c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
28337c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_CONGESTED);
28347c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
28357c954f6dSMel Gorman 	}
28367c954f6dSMel Gorman 
2837b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
283875485363SMel Gorman }
283975485363SMel Gorman 
284075485363SMel Gorman /*
28411da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
284241858966SMel Gorman  * they are all at high_wmark_pages(zone).
28431da177e4SLinus Torvalds  *
28440abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
28451da177e4SLinus Torvalds  *
28461da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
28471da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
28481da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
28491da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
28501da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
28511da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
28521da177e4SLinus Torvalds  * the zone for when the problem goes away.
28531da177e4SLinus Torvalds  *
28541da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
285541858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
285641858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
285741858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
285841858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
285941858966SMel Gorman  * of pages is balanced across the zones.
28601da177e4SLinus Torvalds  */
286199504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2862dc83edd9SMel Gorman 							int *classzone_idx)
28631da177e4SLinus Torvalds {
28641da177e4SLinus Torvalds 	int i;
286599504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
28660ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
28670ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2868179e9639SAndrew Morton 	struct scan_control sc = {
2869179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2870b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2871a6dc60f8SJohannes Weiner 		.may_unmap = 1,
28722e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2873b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
28745ad333ebSAndy Whitcroft 		.order = order,
2875f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2876179e9639SAndrew Morton 	};
2877f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
28781da177e4SLinus Torvalds 
28799e3b2f8cSKonstantin Khlebnikov 	do {
28801da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
28812ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2882b8e83b94SMel Gorman 		bool raise_priority = true;
28832ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2884b8e83b94SMel Gorman 
2885b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
28861da177e4SLinus Torvalds 
28871da177e4SLinus Torvalds 		/*
28881da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
28891da177e4SLinus Torvalds 		 * zone which needs scanning
28901da177e4SLinus Torvalds 		 */
28911da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
28921da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
28931da177e4SLinus Torvalds 
2894f3fe6512SCon Kolivas 			if (!populated_zone(zone))
28951da177e4SLinus Torvalds 				continue;
28961da177e4SLinus Torvalds 
28979e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
28989e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
28991da177e4SLinus Torvalds 				continue;
29001da177e4SLinus Torvalds 
2901556adecbSRik van Riel 			/*
2902556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2903556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2904556adecbSRik van Riel 			 */
29059e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2906556adecbSRik van Riel 
2907cc715d99SMel Gorman 			/*
2908cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2909cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2910cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2911cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2912cc715d99SMel Gorman 			 */
2913cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2914cc715d99SMel Gorman 				end_zone = i;
2915cc715d99SMel Gorman 				break;
2916cc715d99SMel Gorman 			}
2917cc715d99SMel Gorman 
291860cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
29191da177e4SLinus Torvalds 				end_zone = i;
2920e1dbeda6SAndrew Morton 				break;
2921439423f6SShaohua Li 			} else {
2922d43006d5SMel Gorman 				/*
2923d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
2924d43006d5SMel Gorman 				 * flags
2925d43006d5SMel Gorman 				 */
2926439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
2927d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
29281da177e4SLinus Torvalds 			}
29291da177e4SLinus Torvalds 		}
2930dafcb73eSZlatko Calusic 
2931b8e83b94SMel Gorman 		if (i < 0)
29321da177e4SLinus Torvalds 			goto out;
2933e1dbeda6SAndrew Morton 
29341da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
29351da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29361da177e4SLinus Torvalds 
29372ab44f43SMel Gorman 			if (!populated_zone(zone))
29382ab44f43SMel Gorman 				continue;
29392ab44f43SMel Gorman 
2940adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
29412ab44f43SMel Gorman 
29422ab44f43SMel Gorman 			/*
29432ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
29442ab44f43SMel Gorman 			 * not call compaction as it is expected that the
29452ab44f43SMel Gorman 			 * necessary pages are already available.
29462ab44f43SMel Gorman 			 */
29472ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
29482ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
29492ab44f43SMel Gorman 						low_wmark_pages(zone),
29502ab44f43SMel Gorman 						*classzone_idx, 0))
29512ab44f43SMel Gorman 				pgdat_needs_compaction = false;
29521da177e4SLinus Torvalds 		}
29531da177e4SLinus Torvalds 
29541da177e4SLinus Torvalds 		/*
2955b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
2956b7ea3c41SMel Gorman 		 * even in laptop mode.
2957b7ea3c41SMel Gorman 		 */
2958b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
2959b7ea3c41SMel Gorman 			sc.may_writepage = 1;
2960b7ea3c41SMel Gorman 
2961b7ea3c41SMel Gorman 		/*
29621da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
29631da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
29641da177e4SLinus Torvalds 		 *
29651da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
29661da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
29671da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
29681da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
29691da177e4SLinus Torvalds 		 */
29701da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
29711da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29721da177e4SLinus Torvalds 
2973f3fe6512SCon Kolivas 			if (!populated_zone(zone))
29741da177e4SLinus Torvalds 				continue;
29751da177e4SLinus Torvalds 
29769e3b2f8cSKonstantin Khlebnikov 			if (zone->all_unreclaimable &&
29779e3b2f8cSKonstantin Khlebnikov 			    sc.priority != DEF_PRIORITY)
29781da177e4SLinus Torvalds 				continue;
29791da177e4SLinus Torvalds 
29801da177e4SLinus Torvalds 			sc.nr_scanned = 0;
29814e416953SBalbir Singh 
29820ae5e89cSYing Han 			nr_soft_scanned = 0;
29834e416953SBalbir Singh 			/*
29844e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
29854e416953SBalbir Singh 			 */
29860ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
29870ae5e89cSYing Han 							order, sc.gfp_mask,
29880ae5e89cSYing Han 							&nr_soft_scanned);
29890ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
299000918b6aSKOSAKI Motohiro 
299132a4330dSRik van Riel 			/*
29927c954f6dSMel Gorman 			 * There should be no need to raise the scanning
29937c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
29947c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
29957c954f6dSMel Gorman 			 * efficiency.
299632a4330dSRik van Riel 			 */
29977c954f6dSMel Gorman 			if (kswapd_shrink_zone(zone, end_zone, &sc,
29987c954f6dSMel Gorman 					lru_pages, &nr_attempted))
2999b8e83b94SMel Gorman 				raise_priority = false;
3000b8e83b94SMel Gorman 		}
3001d7868daeSMel Gorman 
30025515061dSMel Gorman 		/*
30035515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
30045515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
30055515061dSMel Gorman 		 * able to safely make forward progress. Wake them
30065515061dSMel Gorman 		 */
30075515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
30085515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
30095515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
30105515061dSMel Gorman 
30111da177e4SLinus Torvalds 		/*
3012b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3013b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3014b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3015b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3016b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3017b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
30181da177e4SLinus Torvalds 		 */
3019b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
302073ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
302173ce02e9SKOSAKI Motohiro 
3022b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3023b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3024b8e83b94SMel Gorman 			break;
3025b8e83b94SMel Gorman 
3026b8e83b94SMel Gorman 		/*
30272ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
30282ab44f43SMel Gorman 		 * high watermark number of pages as requsted
30292ab44f43SMel Gorman 		 */
30302ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
30312ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
30322ab44f43SMel Gorman 
30332ab44f43SMel Gorman 		/*
3034b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3035b8e83b94SMel Gorman 		 * progress in reclaiming pages
3036b8e83b94SMel Gorman 		 */
3037b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3038b8e83b94SMel Gorman 			sc.priority--;
30399aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3040b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
30411da177e4SLinus Torvalds 
3042b8e83b94SMel Gorman out:
30430abdee2bSMel Gorman 	/*
30445515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
30450abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
30460abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
30470abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
30480abdee2bSMel Gorman 	 */
3049dc83edd9SMel Gorman 	*classzone_idx = end_zone;
30500abdee2bSMel Gorman 	return order;
30511da177e4SLinus Torvalds }
30521da177e4SLinus Torvalds 
3053dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3054f0bc0a60SKOSAKI Motohiro {
3055f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3056f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3057f0bc0a60SKOSAKI Motohiro 
3058f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3059f0bc0a60SKOSAKI Motohiro 		return;
3060f0bc0a60SKOSAKI Motohiro 
3061f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3062f0bc0a60SKOSAKI Motohiro 
3063f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
30645515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3065f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3066f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3067f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3068f0bc0a60SKOSAKI Motohiro 	}
3069f0bc0a60SKOSAKI Motohiro 
3070f0bc0a60SKOSAKI Motohiro 	/*
3071f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3072f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3073f0bc0a60SKOSAKI Motohiro 	 */
30745515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3075f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3076f0bc0a60SKOSAKI Motohiro 
3077f0bc0a60SKOSAKI Motohiro 		/*
3078f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3079f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3080f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3081f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3082f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3083f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3084f0bc0a60SKOSAKI Motohiro 		 */
3085f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
30861c7e7f6cSAaditya Kumar 
308762997027SMel Gorman 		/*
308862997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
308962997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
309062997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
309162997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
309262997027SMel Gorman 		 */
309362997027SMel Gorman 		reset_isolation_suitable(pgdat);
309462997027SMel Gorman 
30951c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3096f0bc0a60SKOSAKI Motohiro 			schedule();
30971c7e7f6cSAaditya Kumar 
3098f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3099f0bc0a60SKOSAKI Motohiro 	} else {
3100f0bc0a60SKOSAKI Motohiro 		if (remaining)
3101f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3102f0bc0a60SKOSAKI Motohiro 		else
3103f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3104f0bc0a60SKOSAKI Motohiro 	}
3105f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3106f0bc0a60SKOSAKI Motohiro }
3107f0bc0a60SKOSAKI Motohiro 
31081da177e4SLinus Torvalds /*
31091da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
31101da177e4SLinus Torvalds  * from the init process.
31111da177e4SLinus Torvalds  *
31121da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
31131da177e4SLinus Torvalds  * free memory available even if there is no other activity
31141da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
31151da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
31161da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
31171da177e4SLinus Torvalds  *
31181da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
31191da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
31201da177e4SLinus Torvalds  */
31211da177e4SLinus Torvalds static int kswapd(void *p)
31221da177e4SLinus Torvalds {
3123215ddd66SMel Gorman 	unsigned long order, new_order;
3124d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3125215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3126d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
31271da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
31281da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3129f0bc0a60SKOSAKI Motohiro 
31301da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
31311da177e4SLinus Torvalds 		.reclaimed_slab = 0,
31321da177e4SLinus Torvalds 	};
3133a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
31341da177e4SLinus Torvalds 
3135cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3136cf40bd16SNick Piggin 
3137174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3138c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
31391da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
31401da177e4SLinus Torvalds 
31411da177e4SLinus Torvalds 	/*
31421da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
31431da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
31441da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
31451da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
31461da177e4SLinus Torvalds 	 *
31471da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
31481da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
31491da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
31501da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
31511da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
31521da177e4SLinus Torvalds 	 */
3153930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
315483144186SRafael J. Wysocki 	set_freezable();
31551da177e4SLinus Torvalds 
3156215ddd66SMel Gorman 	order = new_order = 0;
3157d2ebd0f6SAlex,Shi 	balanced_order = 0;
3158215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3159d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
31601da177e4SLinus Torvalds 	for ( ; ; ) {
31616f6313d4SJeff Liu 		bool ret;
31623e1d1d28SChristoph Lameter 
3163215ddd66SMel Gorman 		/*
3164215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3165215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3166215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3167215ddd66SMel Gorman 		 */
3168d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3169d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
31701da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
317199504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
31721da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3173215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3174215ddd66SMel Gorman 		}
3175215ddd66SMel Gorman 
317699504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
31771da177e4SLinus Torvalds 			/*
31781da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
317999504748SMel Gorman 			 * allocation or has tigher zone constraints
31801da177e4SLinus Torvalds 			 */
31811da177e4SLinus Torvalds 			order = new_order;
318299504748SMel Gorman 			classzone_idx = new_classzone_idx;
31831da177e4SLinus Torvalds 		} else {
3184d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3185d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
31861da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
318799504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3188f0dfcde0SAlex,Shi 			new_order = order;
3189f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
31904d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3191215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
31921da177e4SLinus Torvalds 		}
31931da177e4SLinus Torvalds 
31948fe23e05SDavid Rientjes 		ret = try_to_freeze();
31958fe23e05SDavid Rientjes 		if (kthread_should_stop())
31968fe23e05SDavid Rientjes 			break;
31978fe23e05SDavid Rientjes 
31988fe23e05SDavid Rientjes 		/*
31998fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
32008fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3201b1296cc4SRafael J. Wysocki 		 */
320233906bc5SMel Gorman 		if (!ret) {
320333906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3204d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3205d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3206d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
32071da177e4SLinus Torvalds 		}
320833906bc5SMel Gorman 	}
3209b0a8cc58STakamori Yamaguchi 
3210b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
32111da177e4SLinus Torvalds 	return 0;
32121da177e4SLinus Torvalds }
32131da177e4SLinus Torvalds 
32141da177e4SLinus Torvalds /*
32151da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
32161da177e4SLinus Torvalds  */
321799504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
32181da177e4SLinus Torvalds {
32191da177e4SLinus Torvalds 	pg_data_t *pgdat;
32201da177e4SLinus Torvalds 
3221f3fe6512SCon Kolivas 	if (!populated_zone(zone))
32221da177e4SLinus Torvalds 		return;
32231da177e4SLinus Torvalds 
322402a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
32251da177e4SLinus Torvalds 		return;
322688f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
322799504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
322888f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
322999504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
323099504748SMel Gorman 	}
32318d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
32321da177e4SLinus Torvalds 		return;
323388f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
323488f5acf8SMel Gorman 		return;
323588f5acf8SMel Gorman 
323688f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
32378d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
32381da177e4SLinus Torvalds }
32391da177e4SLinus Torvalds 
3240adea02a1SWu Fengguang /*
3241adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
3242adea02a1SWu Fengguang  * The less reclaimable pages may be
3243adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
3244adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
3245adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
3246adea02a1SWu Fengguang  */
3247adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
32484f98a2feSRik van Riel {
3249adea02a1SWu Fengguang 	int nr;
3250adea02a1SWu Fengguang 
3251adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
3252adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
3253adea02a1SWu Fengguang 
3254ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3255adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
3256adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
3257adea02a1SWu Fengguang 
3258adea02a1SWu Fengguang 	return nr;
3259adea02a1SWu Fengguang }
3260adea02a1SWu Fengguang 
3261adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
3262adea02a1SWu Fengguang {
3263adea02a1SWu Fengguang 	int nr;
3264adea02a1SWu Fengguang 
3265adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3266adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
3267adea02a1SWu Fengguang 
3268ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
3269adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3270adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
3271adea02a1SWu Fengguang 
3272adea02a1SWu Fengguang 	return nr;
32734f98a2feSRik van Riel }
32744f98a2feSRik van Riel 
3275c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
32761da177e4SLinus Torvalds /*
32777b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3278d6277db4SRafael J. Wysocki  * freed pages.
3279d6277db4SRafael J. Wysocki  *
3280d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3281d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3282d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
32831da177e4SLinus Torvalds  */
32847b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
32851da177e4SLinus Torvalds {
3286d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3287d6277db4SRafael J. Wysocki 	struct scan_control sc = {
32887b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
32897b51755cSKOSAKI Motohiro 		.may_swap = 1,
32907b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3291d6277db4SRafael J. Wysocki 		.may_writepage = 1,
32927b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
32937b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
32947b51755cSKOSAKI Motohiro 		.order = 0,
32959e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
32961da177e4SLinus Torvalds 	};
3297a09ed5e0SYing Han 	struct shrink_control shrink = {
3298a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3299a09ed5e0SYing Han 	};
33007b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
33017b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
33027b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
33031da177e4SLinus Torvalds 
33047b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
33057b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3306d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
33077b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3308d6277db4SRafael J. Wysocki 
3309a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3310d6277db4SRafael J. Wysocki 
33117b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
33127b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
33137b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3314d6277db4SRafael J. Wysocki 
33157b51755cSKOSAKI Motohiro 	return nr_reclaimed;
33161da177e4SLinus Torvalds }
3317c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
33181da177e4SLinus Torvalds 
33191da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
33201da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
33211da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
33221da177e4SLinus Torvalds    restore their cpu bindings. */
3323fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3324fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
33251da177e4SLinus Torvalds {
332658c0a4a7SYasunori Goto 	int nid;
33271da177e4SLinus Torvalds 
33288bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
332948fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3330c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3331a70f7302SRusty Russell 			const struct cpumask *mask;
3332a70f7302SRusty Russell 
3333a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3334c5f59f08SMike Travis 
33353e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
33361da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3337c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
33381da177e4SLinus Torvalds 		}
33391da177e4SLinus Torvalds 	}
33401da177e4SLinus Torvalds 	return NOTIFY_OK;
33411da177e4SLinus Torvalds }
33421da177e4SLinus Torvalds 
33433218ae14SYasunori Goto /*
33443218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
33453218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
33463218ae14SYasunori Goto  */
33473218ae14SYasunori Goto int kswapd_run(int nid)
33483218ae14SYasunori Goto {
33493218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
33503218ae14SYasunori Goto 	int ret = 0;
33513218ae14SYasunori Goto 
33523218ae14SYasunori Goto 	if (pgdat->kswapd)
33533218ae14SYasunori Goto 		return 0;
33543218ae14SYasunori Goto 
33553218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
33563218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
33573218ae14SYasunori Goto 		/* failure at boot is fatal */
33583218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3359d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3360d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3361d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
33623218ae14SYasunori Goto 	}
33633218ae14SYasunori Goto 	return ret;
33643218ae14SYasunori Goto }
33653218ae14SYasunori Goto 
33668fe23e05SDavid Rientjes /*
3367d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3368d8adde17SJiang Liu  * hold lock_memory_hotplug().
33698fe23e05SDavid Rientjes  */
33708fe23e05SDavid Rientjes void kswapd_stop(int nid)
33718fe23e05SDavid Rientjes {
33728fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
33738fe23e05SDavid Rientjes 
3374d8adde17SJiang Liu 	if (kswapd) {
33758fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3376d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3377d8adde17SJiang Liu 	}
33788fe23e05SDavid Rientjes }
33798fe23e05SDavid Rientjes 
33801da177e4SLinus Torvalds static int __init kswapd_init(void)
33811da177e4SLinus Torvalds {
33823218ae14SYasunori Goto 	int nid;
338369e05944SAndrew Morton 
33841da177e4SLinus Torvalds 	swap_setup();
338548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
33863218ae14SYasunori Goto  		kswapd_run(nid);
33871da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
33881da177e4SLinus Torvalds 	return 0;
33891da177e4SLinus Torvalds }
33901da177e4SLinus Torvalds 
33911da177e4SLinus Torvalds module_init(kswapd_init)
33929eeff239SChristoph Lameter 
33939eeff239SChristoph Lameter #ifdef CONFIG_NUMA
33949eeff239SChristoph Lameter /*
33959eeff239SChristoph Lameter  * Zone reclaim mode
33969eeff239SChristoph Lameter  *
33979eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
33989eeff239SChristoph Lameter  * the watermarks.
33999eeff239SChristoph Lameter  */
34009eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
34019eeff239SChristoph Lameter 
34021b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
34037d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
34041b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
34051b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
34061b2ffb78SChristoph Lameter 
34079eeff239SChristoph Lameter /*
3408a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3409a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3410a92f7126SChristoph Lameter  * a zone.
3411a92f7126SChristoph Lameter  */
3412a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3413a92f7126SChristoph Lameter 
34149eeff239SChristoph Lameter /*
34159614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
34169614634fSChristoph Lameter  * occur.
34179614634fSChristoph Lameter  */
34189614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
34199614634fSChristoph Lameter 
34209614634fSChristoph Lameter /*
34210ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
34220ff38490SChristoph Lameter  * slab reclaim needs to occur.
34230ff38490SChristoph Lameter  */
34240ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
34250ff38490SChristoph Lameter 
342690afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
342790afa5deSMel Gorman {
342890afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
342990afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
343090afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
343190afa5deSMel Gorman 
343290afa5deSMel Gorman 	/*
343390afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
343490afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
343590afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
343690afa5deSMel Gorman 	 */
343790afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
343890afa5deSMel Gorman }
343990afa5deSMel Gorman 
344090afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
344190afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
344290afa5deSMel Gorman {
344390afa5deSMel Gorman 	long nr_pagecache_reclaimable;
344490afa5deSMel Gorman 	long delta = 0;
344590afa5deSMel Gorman 
344690afa5deSMel Gorman 	/*
344790afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
344890afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
344990afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
345090afa5deSMel Gorman 	 * a better estimate
345190afa5deSMel Gorman 	 */
345290afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
345390afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
345490afa5deSMel Gorman 	else
345590afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
345690afa5deSMel Gorman 
345790afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
345890afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
345990afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
346090afa5deSMel Gorman 
346190afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
346290afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
346390afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
346490afa5deSMel Gorman 
346590afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
346690afa5deSMel Gorman }
346790afa5deSMel Gorman 
34680ff38490SChristoph Lameter /*
34699eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
34709eeff239SChristoph Lameter  */
3471179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
34729eeff239SChristoph Lameter {
34737fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
347469e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
34759eeff239SChristoph Lameter 	struct task_struct *p = current;
34769eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3477179e9639SAndrew Morton 	struct scan_control sc = {
3478179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3479a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
34802e2e4259SKOSAKI Motohiro 		.may_swap = 1,
348162b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
348221caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3483bd2f6199SJohannes Weiner 		.order = order,
34849e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3485179e9639SAndrew Morton 	};
3486a09ed5e0SYing Han 	struct shrink_control shrink = {
3487a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3488a09ed5e0SYing Han 	};
348915748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
34909eeff239SChristoph Lameter 
34919eeff239SChristoph Lameter 	cond_resched();
3492d4f7796eSChristoph Lameter 	/*
3493d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3494d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3495d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3496d4f7796eSChristoph Lameter 	 */
3497d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
349876ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
34999eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
35009eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3501c84db23cSChristoph Lameter 
350290afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3503a92f7126SChristoph Lameter 		/*
35040ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
35050ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3506a92f7126SChristoph Lameter 		 */
3507a92f7126SChristoph Lameter 		do {
35089e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
35099e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
35100ff38490SChristoph Lameter 	}
3511a92f7126SChristoph Lameter 
351215748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
351315748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
35142a16e3f4SChristoph Lameter 		/*
35157fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
35160ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
35170ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
35180ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
35190ff38490SChristoph Lameter 		 * pages.
35202a16e3f4SChristoph Lameter 		 *
35210ff38490SChristoph Lameter 		 * Note that shrink_slab will free memory on all zones and may
35220ff38490SChristoph Lameter 		 * take a long time.
35232a16e3f4SChristoph Lameter 		 */
35244dc4b3d9SKOSAKI Motohiro 		for (;;) {
35254dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
35264dc4b3d9SKOSAKI Motohiro 
35274dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
35281495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
35294dc4b3d9SKOSAKI Motohiro 				break;
35304dc4b3d9SKOSAKI Motohiro 
35314dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
35324dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
35334dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
35344dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
35354dc4b3d9SKOSAKI Motohiro 				break;
35364dc4b3d9SKOSAKI Motohiro 		}
353783e33a47SChristoph Lameter 
353883e33a47SChristoph Lameter 		/*
353983e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
354083e33a47SChristoph Lameter 		 * reclaimed from this zone.
354183e33a47SChristoph Lameter 		 */
354215748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
354315748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
354415748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
35452a16e3f4SChristoph Lameter 	}
35462a16e3f4SChristoph Lameter 
35479eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3548d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
354976ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3550a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
35519eeff239SChristoph Lameter }
3552179e9639SAndrew Morton 
3553179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3554179e9639SAndrew Morton {
3555179e9639SAndrew Morton 	int node_id;
3556d773ed6bSDavid Rientjes 	int ret;
3557179e9639SAndrew Morton 
3558179e9639SAndrew Morton 	/*
35590ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
35600ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
356134aa1330SChristoph Lameter 	 *
35629614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
35639614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
35649614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
35659614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
35669614634fSChristoph Lameter 	 * unmapped file backed pages.
3567179e9639SAndrew Morton 	 */
356890afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
356990afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3570fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3571179e9639SAndrew Morton 
357293e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3573fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3574d773ed6bSDavid Rientjes 
3575179e9639SAndrew Morton 	/*
3576d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3577179e9639SAndrew Morton 	 */
3578d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3579fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3580179e9639SAndrew Morton 
3581179e9639SAndrew Morton 	/*
3582179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3583179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3584179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3585179e9639SAndrew Morton 	 * as wide as possible.
3586179e9639SAndrew Morton 	 */
358789fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
358837c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3589fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3590d773ed6bSDavid Rientjes 
3591d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3592fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3593fa5e084eSMel Gorman 
3594d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3595d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3596d773ed6bSDavid Rientjes 
359724cf7251SMel Gorman 	if (!ret)
359824cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
359924cf7251SMel Gorman 
3600d773ed6bSDavid Rientjes 	return ret;
3601179e9639SAndrew Morton }
36029eeff239SChristoph Lameter #endif
3603894bc310SLee Schermerhorn 
3604894bc310SLee Schermerhorn /*
3605894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3606894bc310SLee Schermerhorn  * @page: the page to test
3607894bc310SLee Schermerhorn  *
3608894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
360939b5f29aSHugh Dickins  * lists vs unevictable list.
3610894bc310SLee Schermerhorn  *
3611894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3612ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3613b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3614ba9ddf49SLee Schermerhorn  *
3615894bc310SLee Schermerhorn  */
361639b5f29aSHugh Dickins int page_evictable(struct page *page)
3617894bc310SLee Schermerhorn {
361839b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3619894bc310SLee Schermerhorn }
362089e004eaSLee Schermerhorn 
362185046579SHugh Dickins #ifdef CONFIG_SHMEM
362289e004eaSLee Schermerhorn /**
362324513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
362424513264SHugh Dickins  * @pages:	array of pages to check
362524513264SHugh Dickins  * @nr_pages:	number of pages to check
362689e004eaSLee Schermerhorn  *
362724513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
362885046579SHugh Dickins  *
362985046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
363089e004eaSLee Schermerhorn  */
363124513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
363289e004eaSLee Schermerhorn {
3633925b7673SJohannes Weiner 	struct lruvec *lruvec;
363424513264SHugh Dickins 	struct zone *zone = NULL;
363524513264SHugh Dickins 	int pgscanned = 0;
363624513264SHugh Dickins 	int pgrescued = 0;
363789e004eaSLee Schermerhorn 	int i;
363889e004eaSLee Schermerhorn 
363924513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
364024513264SHugh Dickins 		struct page *page = pages[i];
364124513264SHugh Dickins 		struct zone *pagezone;
364289e004eaSLee Schermerhorn 
364324513264SHugh Dickins 		pgscanned++;
364424513264SHugh Dickins 		pagezone = page_zone(page);
364589e004eaSLee Schermerhorn 		if (pagezone != zone) {
364689e004eaSLee Schermerhorn 			if (zone)
364789e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
364889e004eaSLee Schermerhorn 			zone = pagezone;
364989e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
365089e004eaSLee Schermerhorn 		}
3651fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
365289e004eaSLee Schermerhorn 
365324513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
365424513264SHugh Dickins 			continue;
365589e004eaSLee Schermerhorn 
365639b5f29aSHugh Dickins 		if (page_evictable(page)) {
365724513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
365824513264SHugh Dickins 
365924513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
366024513264SHugh Dickins 			ClearPageUnevictable(page);
3661fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3662fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
366324513264SHugh Dickins 			pgrescued++;
366489e004eaSLee Schermerhorn 		}
366589e004eaSLee Schermerhorn 	}
366624513264SHugh Dickins 
366724513264SHugh Dickins 	if (zone) {
366824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
366924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
367024513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
367124513264SHugh Dickins 	}
367285046579SHugh Dickins }
367385046579SHugh Dickins #endif /* CONFIG_SHMEM */
3674af936a16SLee Schermerhorn 
3675264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3676af936a16SLee Schermerhorn {
3677264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
367825bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3679264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
368025bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
368125bd91bdSKOSAKI Motohiro 		    current->comm);
3682af936a16SLee Schermerhorn }
3683af936a16SLee Schermerhorn 
3684af936a16SLee Schermerhorn /*
3685af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3686af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3687af936a16SLee Schermerhorn  */
3688af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3689af936a16SLee Schermerhorn 
3690af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
36918d65af78SAlexey Dobriyan 			   void __user *buffer,
3692af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3693af936a16SLee Schermerhorn {
3694264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
36958d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3696af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3697af936a16SLee Schermerhorn 	return 0;
3698af936a16SLee Schermerhorn }
3699af936a16SLee Schermerhorn 
3700e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3701af936a16SLee Schermerhorn /*
3702af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3703af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3704af936a16SLee Schermerhorn  */
3705af936a16SLee Schermerhorn 
370610fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
370710fbcf4cSKay Sievers 					  struct device_attribute *attr,
3708af936a16SLee Schermerhorn 					  char *buf)
3709af936a16SLee Schermerhorn {
3710264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3711af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3712af936a16SLee Schermerhorn }
3713af936a16SLee Schermerhorn 
371410fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
371510fbcf4cSKay Sievers 					   struct device_attribute *attr,
3716af936a16SLee Schermerhorn 					const char *buf, size_t count)
3717af936a16SLee Schermerhorn {
3718264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3719af936a16SLee Schermerhorn 	return 1;
3720af936a16SLee Schermerhorn }
3721af936a16SLee Schermerhorn 
3722af936a16SLee Schermerhorn 
372310fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3724af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3725af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3726af936a16SLee Schermerhorn 
3727af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3728af936a16SLee Schermerhorn {
372910fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3730af936a16SLee Schermerhorn }
3731af936a16SLee Schermerhorn 
3732af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3733af936a16SLee Schermerhorn {
373410fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3735af936a16SLee Schermerhorn }
3736e4455abbSThadeu Lima de Souza Cascardo #endif
3737