xref: /openbmc/linux/mm/vmscan.c (revision e48982734ea0500d1eba4f9d96195acc5406cad6)
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>
22e129b5c2SAndrew Morton #include <linux/vmstat.h>
231da177e4SLinus Torvalds #include <linux/file.h>
241da177e4SLinus Torvalds #include <linux/writeback.h>
251da177e4SLinus Torvalds #include <linux/blkdev.h>
261da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
271da177e4SLinus Torvalds 					buffer_heads_over_limit */
281da177e4SLinus Torvalds #include <linux/mm_inline.h>
291da177e4SLinus Torvalds #include <linux/backing-dev.h>
301da177e4SLinus Torvalds #include <linux/rmap.h>
311da177e4SLinus Torvalds #include <linux/topology.h>
321da177e4SLinus Torvalds #include <linux/cpu.h>
331da177e4SLinus Torvalds #include <linux/cpuset.h>
343e7d3449SMel Gorman #include <linux/compaction.h>
351da177e4SLinus Torvalds #include <linux/notifier.h>
361da177e4SLinus Torvalds #include <linux/rwsem.h>
37248a0301SRafael J. Wysocki #include <linux/delay.h>
383218ae14SYasunori Goto #include <linux/kthread.h>
397dfb7103SNigel Cunningham #include <linux/freezer.h>
4066e1707bSBalbir Singh #include <linux/memcontrol.h>
41873b4771SKeika Kobayashi #include <linux/delayacct.h>
42af936a16SLee Schermerhorn #include <linux/sysctl.h>
43929bea7cSKOSAKI Motohiro #include <linux/oom.h>
44268bb0ceSLinus Torvalds #include <linux/prefetch.h>
451da177e4SLinus Torvalds 
461da177e4SLinus Torvalds #include <asm/tlbflush.h>
471da177e4SLinus Torvalds #include <asm/div64.h>
481da177e4SLinus Torvalds 
491da177e4SLinus Torvalds #include <linux/swapops.h>
501da177e4SLinus Torvalds 
510f8053a5SNick Piggin #include "internal.h"
520f8053a5SNick Piggin 
5333906bc5SMel Gorman #define CREATE_TRACE_POINTS
5433906bc5SMel Gorman #include <trace/events/vmscan.h>
5533906bc5SMel Gorman 
561da177e4SLinus Torvalds struct scan_control {
571da177e4SLinus Torvalds 	/* Incremented by the number of inactive pages that were scanned */
581da177e4SLinus Torvalds 	unsigned long nr_scanned;
591da177e4SLinus Torvalds 
60a79311c1SRik van Riel 	/* Number of pages freed so far during a call to shrink_zones() */
61a79311c1SRik van Riel 	unsigned long nr_reclaimed;
62a79311c1SRik van Riel 
6322fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6422fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6522fba335SKOSAKI Motohiro 
667b51755cSKOSAKI Motohiro 	unsigned long hibernation_mode;
677b51755cSKOSAKI Motohiro 
681da177e4SLinus Torvalds 	/* This context's GFP mask */
696daa0e28SAl Viro 	gfp_t gfp_mask;
701da177e4SLinus Torvalds 
711da177e4SLinus Torvalds 	int may_writepage;
721da177e4SLinus Torvalds 
73a6dc60f8SJohannes Weiner 	/* Can mapped pages be reclaimed? */
74a6dc60f8SJohannes Weiner 	int may_unmap;
75f1fd1067SChristoph Lameter 
762e2e4259SKOSAKI Motohiro 	/* Can pages be swapped as part of reclaim? */
772e2e4259SKOSAKI Motohiro 	int may_swap;
782e2e4259SKOSAKI Motohiro 
795ad333ebSAndy Whitcroft 	int order;
8066e1707bSBalbir Singh 
815f53e762SKOSAKI Motohiro 	/*
82f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
83f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
84f16015fbSJohannes Weiner 	 */
85f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8666e1707bSBalbir Singh 
87327c0e96SKAMEZAWA Hiroyuki 	/*
88327c0e96SKAMEZAWA Hiroyuki 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
89327c0e96SKAMEZAWA Hiroyuki 	 * are scanned.
90327c0e96SKAMEZAWA Hiroyuki 	 */
91327c0e96SKAMEZAWA Hiroyuki 	nodemask_t	*nodemask;
921da177e4SLinus Torvalds };
931da177e4SLinus Torvalds 
94f16015fbSJohannes Weiner struct mem_cgroup_zone {
95f16015fbSJohannes Weiner 	struct mem_cgroup *mem_cgroup;
96f16015fbSJohannes Weiner 	struct zone *zone;
97f16015fbSJohannes Weiner };
98f16015fbSJohannes Weiner 
991da177e4SLinus Torvalds #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
1001da177e4SLinus Torvalds 
1011da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1021da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1031da177e4SLinus Torvalds 	do {								\
1041da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1051da177e4SLinus Torvalds 			struct page *prev;				\
1061da177e4SLinus Torvalds 									\
1071da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1081da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1091da177e4SLinus Torvalds 		}							\
1101da177e4SLinus Torvalds 	} while (0)
1111da177e4SLinus Torvalds #else
1121da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1131da177e4SLinus Torvalds #endif
1141da177e4SLinus Torvalds 
1151da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1161da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1171da177e4SLinus Torvalds 	do {								\
1181da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1191da177e4SLinus Torvalds 			struct page *prev;				\
1201da177e4SLinus Torvalds 									\
1211da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1221da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1231da177e4SLinus Torvalds 		}							\
1241da177e4SLinus Torvalds 	} while (0)
1251da177e4SLinus Torvalds #else
1261da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1271da177e4SLinus Torvalds #endif
1281da177e4SLinus Torvalds 
1291da177e4SLinus Torvalds /*
1301da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1311da177e4SLinus Torvalds  */
1321da177e4SLinus Torvalds int vm_swappiness = 60;
133bd1e22b8SAndrew Morton long vm_total_pages;	/* The total number of pages which the VM controls */
1341da177e4SLinus Torvalds 
1351da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1361da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1371da177e4SLinus Torvalds 
13800f0b825SBalbir Singh #ifdef CONFIG_CGROUP_MEM_RES_CTLR
13989b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
14089b5fae5SJohannes Weiner {
141f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
14289b5fae5SJohannes Weiner }
14389b5fae5SJohannes Weiner 
144f16015fbSJohannes Weiner static bool scanning_global_lru(struct mem_cgroup_zone *mz)
14589b5fae5SJohannes Weiner {
146f16015fbSJohannes Weiner 	return !mz->mem_cgroup;
14789b5fae5SJohannes Weiner }
14891a45470SKAMEZAWA Hiroyuki #else
14989b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15089b5fae5SJohannes Weiner {
15189b5fae5SJohannes Weiner 	return true;
15289b5fae5SJohannes Weiner }
15389b5fae5SJohannes Weiner 
154f16015fbSJohannes Weiner static bool scanning_global_lru(struct mem_cgroup_zone *mz)
15589b5fae5SJohannes Weiner {
15689b5fae5SJohannes Weiner 	return true;
15789b5fae5SJohannes Weiner }
15891a45470SKAMEZAWA Hiroyuki #endif
15991a45470SKAMEZAWA Hiroyuki 
160f16015fbSJohannes Weiner static struct zone_reclaim_stat *get_reclaim_stat(struct mem_cgroup_zone *mz)
1616e901571SKOSAKI Motohiro {
162f16015fbSJohannes Weiner 	if (!scanning_global_lru(mz))
163f16015fbSJohannes Weiner 		return mem_cgroup_get_reclaim_stat(mz->mem_cgroup, mz->zone);
1643e2f41f1SKOSAKI Motohiro 
165f16015fbSJohannes Weiner 	return &mz->zone->reclaim_stat;
1666e901571SKOSAKI Motohiro }
1676e901571SKOSAKI Motohiro 
168f16015fbSJohannes Weiner static unsigned long zone_nr_lru_pages(struct mem_cgroup_zone *mz,
169f16015fbSJohannes Weiner 				       enum lru_list lru)
170c9f299d9SKOSAKI Motohiro {
171f16015fbSJohannes Weiner 	if (!scanning_global_lru(mz))
172f16015fbSJohannes Weiner 		return mem_cgroup_zone_nr_lru_pages(mz->mem_cgroup,
173f16015fbSJohannes Weiner 						    zone_to_nid(mz->zone),
174f16015fbSJohannes Weiner 						    zone_idx(mz->zone),
175f16015fbSJohannes Weiner 						    BIT(lru));
176a3d8e054SKOSAKI Motohiro 
177f16015fbSJohannes Weiner 	return zone_page_state(mz->zone, NR_LRU_BASE + lru);
178c9f299d9SKOSAKI Motohiro }
179c9f299d9SKOSAKI Motohiro 
180c9f299d9SKOSAKI Motohiro 
1811da177e4SLinus Torvalds /*
1821da177e4SLinus Torvalds  * Add a shrinker callback to be called from the vm
1831da177e4SLinus Torvalds  */
1848e1f936bSRusty Russell void register_shrinker(struct shrinker *shrinker)
1851da177e4SLinus Torvalds {
18683aeeadaSKonstantin Khlebnikov 	atomic_long_set(&shrinker->nr_in_batch, 0);
1871da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1881da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
1891da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
1901da177e4SLinus Torvalds }
1918e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
1921da177e4SLinus Torvalds 
1931da177e4SLinus Torvalds /*
1941da177e4SLinus Torvalds  * Remove one
1951da177e4SLinus Torvalds  */
1968e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
1971da177e4SLinus Torvalds {
1981da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
1991da177e4SLinus Torvalds 	list_del(&shrinker->list);
2001da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2011da177e4SLinus Torvalds }
2028e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2031da177e4SLinus Torvalds 
2041495f230SYing Han static inline int do_shrinker_shrink(struct shrinker *shrinker,
2051495f230SYing Han 				     struct shrink_control *sc,
2061495f230SYing Han 				     unsigned long nr_to_scan)
2071495f230SYing Han {
2081495f230SYing Han 	sc->nr_to_scan = nr_to_scan;
2091495f230SYing Han 	return (*shrinker->shrink)(shrinker, sc);
2101495f230SYing Han }
2111495f230SYing Han 
2121da177e4SLinus Torvalds #define SHRINK_BATCH 128
2131da177e4SLinus Torvalds /*
2141da177e4SLinus Torvalds  * Call the shrink functions to age shrinkable caches
2151da177e4SLinus Torvalds  *
2161da177e4SLinus Torvalds  * Here we assume it costs one seek to replace a lru page and that it also
2171da177e4SLinus Torvalds  * takes a seek to recreate a cache object.  With this in mind we age equal
2181da177e4SLinus Torvalds  * percentages of the lru and ageable caches.  This should balance the seeks
2191da177e4SLinus Torvalds  * generated by these structures.
2201da177e4SLinus Torvalds  *
221183ff22bSSimon Arlott  * If the vm encountered mapped pages on the LRU it increase the pressure on
2221da177e4SLinus Torvalds  * slab to avoid swapping.
2231da177e4SLinus Torvalds  *
2241da177e4SLinus Torvalds  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
2251da177e4SLinus Torvalds  *
2261da177e4SLinus Torvalds  * `lru_pages' represents the number of on-LRU pages in all the zones which
2271da177e4SLinus Torvalds  * are eligible for the caller's allocation attempt.  It is used for balancing
2281da177e4SLinus Torvalds  * slab reclaim versus page reclaim.
229b15e0905Sakpm@osdl.org  *
230b15e0905Sakpm@osdl.org  * Returns the number of slab objects which we shrunk.
2311da177e4SLinus Torvalds  */
232a09ed5e0SYing Han unsigned long shrink_slab(struct shrink_control *shrink,
2331495f230SYing Han 			  unsigned long nr_pages_scanned,
23469e05944SAndrew Morton 			  unsigned long lru_pages)
2351da177e4SLinus Torvalds {
2361da177e4SLinus Torvalds 	struct shrinker *shrinker;
23769e05944SAndrew Morton 	unsigned long ret = 0;
2381da177e4SLinus Torvalds 
2391495f230SYing Han 	if (nr_pages_scanned == 0)
2401495f230SYing Han 		nr_pages_scanned = SWAP_CLUSTER_MAX;
2411da177e4SLinus Torvalds 
242f06590bdSMinchan Kim 	if (!down_read_trylock(&shrinker_rwsem)) {
243f06590bdSMinchan Kim 		/* Assume we'll be able to shrink next time */
244f06590bdSMinchan Kim 		ret = 1;
245f06590bdSMinchan Kim 		goto out;
246f06590bdSMinchan Kim 	}
2471da177e4SLinus Torvalds 
2481da177e4SLinus Torvalds 	list_for_each_entry(shrinker, &shrinker_list, list) {
2491da177e4SLinus Torvalds 		unsigned long long delta;
250635697c6SKonstantin Khlebnikov 		long total_scan;
251635697c6SKonstantin Khlebnikov 		long max_pass;
25209576073SDave Chinner 		int shrink_ret = 0;
253acf92b48SDave Chinner 		long nr;
254acf92b48SDave Chinner 		long new_nr;
255e9299f50SDave Chinner 		long batch_size = shrinker->batch ? shrinker->batch
256e9299f50SDave Chinner 						  : SHRINK_BATCH;
2571da177e4SLinus Torvalds 
258635697c6SKonstantin Khlebnikov 		max_pass = do_shrinker_shrink(shrinker, shrink, 0);
259635697c6SKonstantin Khlebnikov 		if (max_pass <= 0)
260635697c6SKonstantin Khlebnikov 			continue;
261635697c6SKonstantin Khlebnikov 
262acf92b48SDave Chinner 		/*
263acf92b48SDave Chinner 		 * copy the current shrinker scan count into a local variable
264acf92b48SDave Chinner 		 * and zero it so that other concurrent shrinker invocations
265acf92b48SDave Chinner 		 * don't also do this scanning work.
266acf92b48SDave Chinner 		 */
26783aeeadaSKonstantin Khlebnikov 		nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
268acf92b48SDave Chinner 
269acf92b48SDave Chinner 		total_scan = nr;
2701495f230SYing Han 		delta = (4 * nr_pages_scanned) / shrinker->seeks;
271ea164d73SAndrea Arcangeli 		delta *= max_pass;
2721da177e4SLinus Torvalds 		do_div(delta, lru_pages + 1);
273acf92b48SDave Chinner 		total_scan += delta;
274acf92b48SDave Chinner 		if (total_scan < 0) {
27588c3bd70SDavid Rientjes 			printk(KERN_ERR "shrink_slab: %pF negative objects to "
27688c3bd70SDavid Rientjes 			       "delete nr=%ld\n",
277acf92b48SDave Chinner 			       shrinker->shrink, total_scan);
278acf92b48SDave Chinner 			total_scan = max_pass;
279ea164d73SAndrea Arcangeli 		}
280ea164d73SAndrea Arcangeli 
281ea164d73SAndrea Arcangeli 		/*
2823567b59aSDave Chinner 		 * We need to avoid excessive windup on filesystem shrinkers
2833567b59aSDave Chinner 		 * due to large numbers of GFP_NOFS allocations causing the
2843567b59aSDave Chinner 		 * shrinkers to return -1 all the time. This results in a large
2853567b59aSDave Chinner 		 * nr being built up so when a shrink that can do some work
2863567b59aSDave Chinner 		 * comes along it empties the entire cache due to nr >>>
2873567b59aSDave Chinner 		 * max_pass.  This is bad for sustaining a working set in
2883567b59aSDave Chinner 		 * memory.
2893567b59aSDave Chinner 		 *
2903567b59aSDave Chinner 		 * Hence only allow the shrinker to scan the entire cache when
2913567b59aSDave Chinner 		 * a large delta change is calculated directly.
2923567b59aSDave Chinner 		 */
2933567b59aSDave Chinner 		if (delta < max_pass / 4)
2943567b59aSDave Chinner 			total_scan = min(total_scan, max_pass / 2);
2953567b59aSDave Chinner 
2963567b59aSDave Chinner 		/*
297ea164d73SAndrea Arcangeli 		 * Avoid risking looping forever due to too large nr value:
298ea164d73SAndrea Arcangeli 		 * never try to free more than twice the estimate number of
299ea164d73SAndrea Arcangeli 		 * freeable entries.
300ea164d73SAndrea Arcangeli 		 */
301acf92b48SDave Chinner 		if (total_scan > max_pass * 2)
302acf92b48SDave Chinner 			total_scan = max_pass * 2;
3031da177e4SLinus Torvalds 
304acf92b48SDave Chinner 		trace_mm_shrink_slab_start(shrinker, shrink, nr,
30509576073SDave Chinner 					nr_pages_scanned, lru_pages,
30609576073SDave Chinner 					max_pass, delta, total_scan);
30709576073SDave Chinner 
308e9299f50SDave Chinner 		while (total_scan >= batch_size) {
309b15e0905Sakpm@osdl.org 			int nr_before;
3101da177e4SLinus Torvalds 
3111495f230SYing Han 			nr_before = do_shrinker_shrink(shrinker, shrink, 0);
3121495f230SYing Han 			shrink_ret = do_shrinker_shrink(shrinker, shrink,
313e9299f50SDave Chinner 							batch_size);
3141da177e4SLinus Torvalds 			if (shrink_ret == -1)
3151da177e4SLinus Torvalds 				break;
316b15e0905Sakpm@osdl.org 			if (shrink_ret < nr_before)
317b15e0905Sakpm@osdl.org 				ret += nr_before - shrink_ret;
318e9299f50SDave Chinner 			count_vm_events(SLABS_SCANNED, batch_size);
319e9299f50SDave Chinner 			total_scan -= batch_size;
3201da177e4SLinus Torvalds 
3211da177e4SLinus Torvalds 			cond_resched();
3221da177e4SLinus Torvalds 		}
3231da177e4SLinus Torvalds 
324acf92b48SDave Chinner 		/*
325acf92b48SDave Chinner 		 * move the unused scan count back into the shrinker in a
326acf92b48SDave Chinner 		 * manner that handles concurrent updates. If we exhausted the
327acf92b48SDave Chinner 		 * scan, there is no need to do an update.
328acf92b48SDave Chinner 		 */
32983aeeadaSKonstantin Khlebnikov 		if (total_scan > 0)
33083aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_add_return(total_scan,
33183aeeadaSKonstantin Khlebnikov 					&shrinker->nr_in_batch);
33283aeeadaSKonstantin Khlebnikov 		else
33383aeeadaSKonstantin Khlebnikov 			new_nr = atomic_long_read(&shrinker->nr_in_batch);
334acf92b48SDave Chinner 
335acf92b48SDave Chinner 		trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
3361da177e4SLinus Torvalds 	}
3371da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
338f06590bdSMinchan Kim out:
339f06590bdSMinchan Kim 	cond_resched();
340b15e0905Sakpm@osdl.org 	return ret;
3411da177e4SLinus Torvalds }
3421da177e4SLinus Torvalds 
3431da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
3441da177e4SLinus Torvalds {
345ceddc3a5SJohannes Weiner 	/*
346ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
347ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
348ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
349ceddc3a5SJohannes Weiner 	 */
350edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
3511da177e4SLinus Torvalds }
3521da177e4SLinus Torvalds 
3537d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
3547d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
3551da177e4SLinus Torvalds {
356930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
3571da177e4SLinus Torvalds 		return 1;
3581da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
3591da177e4SLinus Torvalds 		return 1;
3601da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
3611da177e4SLinus Torvalds 		return 1;
3621da177e4SLinus Torvalds 	return 0;
3631da177e4SLinus Torvalds }
3641da177e4SLinus Torvalds 
3651da177e4SLinus Torvalds /*
3661da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
3671da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
3681da177e4SLinus Torvalds  * fsync(), msync() or close().
3691da177e4SLinus Torvalds  *
3701da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
3711da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
3721da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
3731da177e4SLinus Torvalds  *
3741da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
3751da177e4SLinus Torvalds  * __GFP_FS.
3761da177e4SLinus Torvalds  */
3771da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
3781da177e4SLinus Torvalds 				struct page *page, int error)
3791da177e4SLinus Torvalds {
3807eaceaccSJens Axboe 	lock_page(page);
3813e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
3823e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
3831da177e4SLinus Torvalds 	unlock_page(page);
3841da177e4SLinus Torvalds }
3851da177e4SLinus Torvalds 
38604e62a29SChristoph Lameter /* possible outcome of pageout() */
38704e62a29SChristoph Lameter typedef enum {
38804e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
38904e62a29SChristoph Lameter 	PAGE_KEEP,
39004e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
39104e62a29SChristoph Lameter 	PAGE_ACTIVATE,
39204e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
39304e62a29SChristoph Lameter 	PAGE_SUCCESS,
39404e62a29SChristoph Lameter 	/* page is clean and locked */
39504e62a29SChristoph Lameter 	PAGE_CLEAN,
39604e62a29SChristoph Lameter } pageout_t;
39704e62a29SChristoph Lameter 
3981da177e4SLinus Torvalds /*
3991742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
4001742f19fSAndrew Morton  * Calls ->writepage().
4011da177e4SLinus Torvalds  */
402c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
4037d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
4041da177e4SLinus Torvalds {
4051da177e4SLinus Torvalds 	/*
4061da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
4071da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
4081da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
4091da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
4101da177e4SLinus Torvalds 	 * PagePrivate for that.
4111da177e4SLinus Torvalds 	 *
4126aceb53bSVincent Li 	 * If this process is currently in __generic_file_aio_write() against
4131da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
4141da177e4SLinus Torvalds 	 * will block.
4151da177e4SLinus Torvalds 	 *
4161da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
4171da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
4181da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
4191da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
4201da177e4SLinus Torvalds 	 */
4211da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
4221da177e4SLinus Torvalds 		return PAGE_KEEP;
4231da177e4SLinus Torvalds 	if (!mapping) {
4241da177e4SLinus Torvalds 		/*
4251da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4261da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4271da177e4SLinus Torvalds 		 */
428266cf658SDavid Howells 		if (page_has_private(page)) {
4291da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4301da177e4SLinus Torvalds 				ClearPageDirty(page);
431d40cee24SHarvey Harrison 				printk("%s: orphaned page\n", __func__);
4321da177e4SLinus Torvalds 				return PAGE_CLEAN;
4331da177e4SLinus Torvalds 			}
4341da177e4SLinus Torvalds 		}
4351da177e4SLinus Torvalds 		return PAGE_KEEP;
4361da177e4SLinus Torvalds 	}
4371da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4381da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4390e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
4401da177e4SLinus Torvalds 		return PAGE_KEEP;
4411da177e4SLinus Torvalds 
4421da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
4431da177e4SLinus Torvalds 		int res;
4441da177e4SLinus Torvalds 		struct writeback_control wbc = {
4451da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
4461da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
447111ebb6eSOGAWA Hirofumi 			.range_start = 0,
448111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
4491da177e4SLinus Torvalds 			.for_reclaim = 1,
4501da177e4SLinus Torvalds 		};
4511da177e4SLinus Torvalds 
4521da177e4SLinus Torvalds 		SetPageReclaim(page);
4531da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
4541da177e4SLinus Torvalds 		if (res < 0)
4551da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
456994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
4571da177e4SLinus Torvalds 			ClearPageReclaim(page);
4581da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
4591da177e4SLinus Torvalds 		}
460c661b078SAndy Whitcroft 
4611da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
4621da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
4631da177e4SLinus Torvalds 			ClearPageReclaim(page);
4641da177e4SLinus Torvalds 		}
46523b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
466e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
4671da177e4SLinus Torvalds 		return PAGE_SUCCESS;
4681da177e4SLinus Torvalds 	}
4691da177e4SLinus Torvalds 
4701da177e4SLinus Torvalds 	return PAGE_CLEAN;
4711da177e4SLinus Torvalds }
4721da177e4SLinus Torvalds 
473a649fd92SAndrew Morton /*
474e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
475e286781dSNick Piggin  * gets returned with a refcount of 0.
476a649fd92SAndrew Morton  */
477e286781dSNick Piggin static int __remove_mapping(struct address_space *mapping, struct page *page)
47849d2e9ccSChristoph Lameter {
47928e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
48028e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
48149d2e9ccSChristoph Lameter 
48219fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
48349d2e9ccSChristoph Lameter 	/*
4840fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
4850fd0e6b0SNick Piggin 	 *
4860fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
4870fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
4880fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
4890fd0e6b0SNick Piggin 	 * here, then the following race may occur:
4900fd0e6b0SNick Piggin 	 *
4910fd0e6b0SNick Piggin 	 * get_user_pages(&page);
4920fd0e6b0SNick Piggin 	 * [user mapping goes away]
4930fd0e6b0SNick Piggin 	 * write_to(page);
4940fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
4950fd0e6b0SNick Piggin 	 * SetPageDirty(page);
4960fd0e6b0SNick Piggin 	 * put_page(page);
4970fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
4980fd0e6b0SNick Piggin 	 *
4990fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
5000fd0e6b0SNick Piggin 	 *
5010fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
5020fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
5030fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
5040fd0e6b0SNick Piggin 	 *
5050fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
5060fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
50749d2e9ccSChristoph Lameter 	 */
508e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
50949d2e9ccSChristoph Lameter 		goto cannot_free;
510e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
511e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
512e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
51349d2e9ccSChristoph Lameter 		goto cannot_free;
514e286781dSNick Piggin 	}
51549d2e9ccSChristoph Lameter 
51649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
51749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
51849d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
51919fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
520cb4b86baSKAMEZAWA Hiroyuki 		swapcache_free(swap, page);
521e286781dSNick Piggin 	} else {
5226072d13cSLinus Torvalds 		void (*freepage)(struct page *);
5236072d13cSLinus Torvalds 
5246072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
5256072d13cSLinus Torvalds 
526e64a782fSMinchan Kim 		__delete_from_page_cache(page);
52719fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
528e767e056SDaisuke Nishimura 		mem_cgroup_uncharge_cache_page(page);
5296072d13cSLinus Torvalds 
5306072d13cSLinus Torvalds 		if (freepage != NULL)
5316072d13cSLinus Torvalds 			freepage(page);
532e286781dSNick Piggin 	}
533e286781dSNick Piggin 
53449d2e9ccSChristoph Lameter 	return 1;
53549d2e9ccSChristoph Lameter 
53649d2e9ccSChristoph Lameter cannot_free:
53719fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
53849d2e9ccSChristoph Lameter 	return 0;
53949d2e9ccSChristoph Lameter }
54049d2e9ccSChristoph Lameter 
5411da177e4SLinus Torvalds /*
542e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
543e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
544e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
545e286781dSNick Piggin  * this page.
546e286781dSNick Piggin  */
547e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
548e286781dSNick Piggin {
549e286781dSNick Piggin 	if (__remove_mapping(mapping, page)) {
550e286781dSNick Piggin 		/*
551e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
552e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
553e286781dSNick Piggin 		 * atomic operation.
554e286781dSNick Piggin 		 */
555e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
556e286781dSNick Piggin 		return 1;
557e286781dSNick Piggin 	}
558e286781dSNick Piggin 	return 0;
559e286781dSNick Piggin }
560e286781dSNick Piggin 
561894bc310SLee Schermerhorn /**
562894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
563894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
564894bc310SLee Schermerhorn  *
565894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
566894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
567894bc310SLee Schermerhorn  *
568894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
569894bc310SLee Schermerhorn  */
570894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
571894bc310SLee Schermerhorn {
572894bc310SLee Schermerhorn 	int lru;
573894bc310SLee Schermerhorn 	int active = !!TestClearPageActive(page);
574bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
575894bc310SLee Schermerhorn 
576894bc310SLee Schermerhorn 	VM_BUG_ON(PageLRU(page));
577894bc310SLee Schermerhorn 
578894bc310SLee Schermerhorn redo:
579894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
580894bc310SLee Schermerhorn 
581894bc310SLee Schermerhorn 	if (page_evictable(page, NULL)) {
582894bc310SLee Schermerhorn 		/*
583894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
584894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
585894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
586894bc310SLee Schermerhorn 		 * We know how to handle that.
587894bc310SLee Schermerhorn 		 */
588401a8e1cSJohannes Weiner 		lru = active + page_lru_base_type(page);
589894bc310SLee Schermerhorn 		lru_cache_add_lru(page, lru);
590894bc310SLee Schermerhorn 	} else {
591894bc310SLee Schermerhorn 		/*
592894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
593894bc310SLee Schermerhorn 		 * list.
594894bc310SLee Schermerhorn 		 */
595894bc310SLee Schermerhorn 		lru = LRU_UNEVICTABLE;
596894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
5976a7b9548SJohannes Weiner 		/*
59821ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
59921ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
60021ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
60124513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
60221ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
6036a7b9548SJohannes Weiner 		 * the page back to the evictable list.
6046a7b9548SJohannes Weiner 		 *
60521ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
6066a7b9548SJohannes Weiner 		 */
6076a7b9548SJohannes Weiner 		smp_mb();
608894bc310SLee Schermerhorn 	}
609894bc310SLee Schermerhorn 
610894bc310SLee Schermerhorn 	/*
611894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
612894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
613894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
614894bc310SLee Schermerhorn 	 */
615894bc310SLee Schermerhorn 	if (lru == LRU_UNEVICTABLE && page_evictable(page, NULL)) {
616894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
617894bc310SLee Schermerhorn 			put_page(page);
618894bc310SLee Schermerhorn 			goto redo;
619894bc310SLee Schermerhorn 		}
620894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
621894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
622894bc310SLee Schermerhorn 		 * nothing to do here.
623894bc310SLee Schermerhorn 		 */
624894bc310SLee Schermerhorn 	}
625894bc310SLee Schermerhorn 
626bbfd28eeSLee Schermerhorn 	if (was_unevictable && lru != LRU_UNEVICTABLE)
627bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
628bbfd28eeSLee Schermerhorn 	else if (!was_unevictable && lru == LRU_UNEVICTABLE)
629bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
630bbfd28eeSLee Schermerhorn 
631894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
632894bc310SLee Schermerhorn }
633894bc310SLee Schermerhorn 
634dfc8d636SJohannes Weiner enum page_references {
635dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
636dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
63764574746SJohannes Weiner 	PAGEREF_KEEP,
638dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
639dfc8d636SJohannes Weiner };
640dfc8d636SJohannes Weiner 
641dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
642f16015fbSJohannes Weiner 						  struct mem_cgroup_zone *mz,
643dfc8d636SJohannes Weiner 						  struct scan_control *sc)
644dfc8d636SJohannes Weiner {
64564574746SJohannes Weiner 	int referenced_ptes, referenced_page;
646dfc8d636SJohannes Weiner 	unsigned long vm_flags;
647dfc8d636SJohannes Weiner 
648c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
649c3ac9a8aSJohannes Weiner 					  &vm_flags);
65064574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
651dfc8d636SJohannes Weiner 
652dfc8d636SJohannes Weiner 	/*
653dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
654dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
655dfc8d636SJohannes Weiner 	 */
656dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
657dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
658dfc8d636SJohannes Weiner 
65964574746SJohannes Weiner 	if (referenced_ptes) {
660*e4898273SMichal Hocko 		if (PageSwapBacked(page))
66164574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
66264574746SJohannes Weiner 		/*
66364574746SJohannes Weiner 		 * All mapped pages start out with page table
66464574746SJohannes Weiner 		 * references from the instantiating fault, so we need
66564574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
66664574746SJohannes Weiner 		 * than once.
66764574746SJohannes Weiner 		 *
66864574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
66964574746SJohannes Weiner 		 * inactive list.  Another page table reference will
67064574746SJohannes Weiner 		 * lead to its activation.
67164574746SJohannes Weiner 		 *
67264574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
67364574746SJohannes Weiner 		 * so that recently deactivated but used pages are
67464574746SJohannes Weiner 		 * quickly recovered.
67564574746SJohannes Weiner 		 */
67664574746SJohannes Weiner 		SetPageReferenced(page);
67764574746SJohannes Weiner 
67834dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
679dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
680dfc8d636SJohannes Weiner 
681c909e993SKonstantin Khlebnikov 		/*
682c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
683c909e993SKonstantin Khlebnikov 		 */
684c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
685c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
686c909e993SKonstantin Khlebnikov 
68764574746SJohannes Weiner 		return PAGEREF_KEEP;
68864574746SJohannes Weiner 	}
68964574746SJohannes Weiner 
690dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
6912e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
692dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
69364574746SJohannes Weiner 
69464574746SJohannes Weiner 	return PAGEREF_RECLAIM;
695dfc8d636SJohannes Weiner }
696dfc8d636SJohannes Weiner 
697e286781dSNick Piggin /*
6981742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
6991da177e4SLinus Torvalds  */
7001742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
701f16015fbSJohannes Weiner 				      struct mem_cgroup_zone *mz,
702f84f6e2bSMel Gorman 				      struct scan_control *sc,
70392df3a72SMel Gorman 				      int priority,
70492df3a72SMel Gorman 				      unsigned long *ret_nr_dirty,
70592df3a72SMel Gorman 				      unsigned long *ret_nr_writeback)
7061da177e4SLinus Torvalds {
7071da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
708abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
7091da177e4SLinus Torvalds 	int pgactivate = 0;
7100e093d99SMel Gorman 	unsigned long nr_dirty = 0;
7110e093d99SMel Gorman 	unsigned long nr_congested = 0;
71205ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
71392df3a72SMel Gorman 	unsigned long nr_writeback = 0;
7141da177e4SLinus Torvalds 
7151da177e4SLinus Torvalds 	cond_resched();
7161da177e4SLinus Torvalds 
7171da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
718dfc8d636SJohannes Weiner 		enum page_references references;
7191da177e4SLinus Torvalds 		struct address_space *mapping;
7201da177e4SLinus Torvalds 		struct page *page;
7211da177e4SLinus Torvalds 		int may_enter_fs;
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));
732f16015fbSJohannes Weiner 		VM_BUG_ON(page_zone(page) != mz->zone);
7331da177e4SLinus Torvalds 
7341da177e4SLinus Torvalds 		sc->nr_scanned++;
73580e43426SChristoph Lameter 
736b291f000SNick Piggin 		if (unlikely(!page_evictable(page, NULL)))
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 
749c661b078SAndy Whitcroft 		if (PageWriteback(page)) {
75092df3a72SMel Gorman 			nr_writeback++;
7517d3579e8SKOSAKI Motohiro 			unlock_page(page);
75241ac1999SMel Gorman 			goto keep;
753c661b078SAndy Whitcroft 		}
7541da177e4SLinus Torvalds 
755f16015fbSJohannes Weiner 		references = page_check_references(page, mz, sc);
756dfc8d636SJohannes Weiner 		switch (references) {
757dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
7581da177e4SLinus Torvalds 			goto activate_locked;
75964574746SJohannes Weiner 		case PAGEREF_KEEP:
76064574746SJohannes Weiner 			goto keep_locked;
761dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
762dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
763dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
764dfc8d636SJohannes Weiner 		}
7651da177e4SLinus Torvalds 
7661da177e4SLinus Torvalds 		/*
7671da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
7681da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
7691da177e4SLinus Torvalds 		 */
770b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
77163eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
77263eb6b93SHugh Dickins 				goto keep_locked;
773ac47b003SHugh Dickins 			if (!add_to_swap(page))
7741da177e4SLinus Torvalds 				goto activate_locked;
77563eb6b93SHugh Dickins 			may_enter_fs = 1;
776b291f000SNick Piggin 		}
7771da177e4SLinus Torvalds 
7781da177e4SLinus Torvalds 		mapping = page_mapping(page);
7791da177e4SLinus Torvalds 
7801da177e4SLinus Torvalds 		/*
7811da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
7821da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
7831da177e4SLinus Torvalds 		 */
7841da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
78514fa31b8SAndi Kleen 			switch (try_to_unmap(page, TTU_UNMAP)) {
7861da177e4SLinus Torvalds 			case SWAP_FAIL:
7871da177e4SLinus Torvalds 				goto activate_locked;
7881da177e4SLinus Torvalds 			case SWAP_AGAIN:
7891da177e4SLinus Torvalds 				goto keep_locked;
790b291f000SNick Piggin 			case SWAP_MLOCK:
791b291f000SNick Piggin 				goto cull_mlocked;
7921da177e4SLinus Torvalds 			case SWAP_SUCCESS:
7931da177e4SLinus Torvalds 				; /* try to free the page below */
7941da177e4SLinus Torvalds 			}
7951da177e4SLinus Torvalds 		}
7961da177e4SLinus Torvalds 
7971da177e4SLinus Torvalds 		if (PageDirty(page)) {
7980e093d99SMel Gorman 			nr_dirty++;
7990e093d99SMel Gorman 
800ee72886dSMel Gorman 			/*
801ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
802f84f6e2bSMel Gorman 			 * avoid risk of stack overflow but do not writeback
803f84f6e2bSMel Gorman 			 * unless under significant pressure.
804ee72886dSMel Gorman 			 */
805f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
806f84f6e2bSMel Gorman 					(!current_is_kswapd() || priority >= DEF_PRIORITY - 2)) {
80749ea7eb6SMel Gorman 				/*
80849ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
80949ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
81049ea7eb6SMel Gorman 				 * except we already have the page isolated
81149ea7eb6SMel Gorman 				 * and know it's dirty
81249ea7eb6SMel Gorman 				 */
81349ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
81449ea7eb6SMel Gorman 				SetPageReclaim(page);
81549ea7eb6SMel Gorman 
816ee72886dSMel Gorman 				goto keep_locked;
817ee72886dSMel Gorman 			}
818ee72886dSMel Gorman 
819dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
8201da177e4SLinus Torvalds 				goto keep_locked;
8214dd4b920SAndrew Morton 			if (!may_enter_fs)
8221da177e4SLinus Torvalds 				goto keep_locked;
82352a8363eSChristoph Lameter 			if (!sc->may_writepage)
8241da177e4SLinus Torvalds 				goto keep_locked;
8251da177e4SLinus Torvalds 
8261da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
8277d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
8281da177e4SLinus Torvalds 			case PAGE_KEEP:
8290e093d99SMel Gorman 				nr_congested++;
8301da177e4SLinus Torvalds 				goto keep_locked;
8311da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
8321da177e4SLinus Torvalds 				goto activate_locked;
8331da177e4SLinus Torvalds 			case PAGE_SUCCESS:
8347d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
83541ac1999SMel Gorman 					goto keep;
8367d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
8371da177e4SLinus Torvalds 					goto keep;
8387d3579e8SKOSAKI Motohiro 
8391da177e4SLinus Torvalds 				/*
8401da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
8411da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
8421da177e4SLinus Torvalds 				 */
843529ae9aaSNick Piggin 				if (!trylock_page(page))
8441da177e4SLinus Torvalds 					goto keep;
8451da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
8461da177e4SLinus Torvalds 					goto keep_locked;
8471da177e4SLinus Torvalds 				mapping = page_mapping(page);
8481da177e4SLinus Torvalds 			case PAGE_CLEAN:
8491da177e4SLinus Torvalds 				; /* try to free the page below */
8501da177e4SLinus Torvalds 			}
8511da177e4SLinus Torvalds 		}
8521da177e4SLinus Torvalds 
8531da177e4SLinus Torvalds 		/*
8541da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
8551da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
8561da177e4SLinus Torvalds 		 * the page as well.
8571da177e4SLinus Torvalds 		 *
8581da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
8591da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
8601da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
8611da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
8621da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
8631da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
8641da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
8651da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
8661da177e4SLinus Torvalds 		 *
8671da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
8681da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
8691da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
8701da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
8711da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
8721da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
8731da177e4SLinus Torvalds 		 */
874266cf658SDavid Howells 		if (page_has_private(page)) {
8751da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
8761da177e4SLinus Torvalds 				goto activate_locked;
877e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
878e286781dSNick Piggin 				unlock_page(page);
879e286781dSNick Piggin 				if (put_page_testzero(page))
8801da177e4SLinus Torvalds 					goto free_it;
881e286781dSNick Piggin 				else {
882e286781dSNick Piggin 					/*
883e286781dSNick Piggin 					 * rare race with speculative reference.
884e286781dSNick Piggin 					 * the speculative reference will free
885e286781dSNick Piggin 					 * this page shortly, so we may
886e286781dSNick Piggin 					 * increment nr_reclaimed here (and
887e286781dSNick Piggin 					 * leave it off the LRU).
888e286781dSNick Piggin 					 */
889e286781dSNick Piggin 					nr_reclaimed++;
890e286781dSNick Piggin 					continue;
891e286781dSNick Piggin 				}
892e286781dSNick Piggin 			}
8931da177e4SLinus Torvalds 		}
8941da177e4SLinus Torvalds 
895e286781dSNick Piggin 		if (!mapping || !__remove_mapping(mapping, page))
89649d2e9ccSChristoph Lameter 			goto keep_locked;
8971da177e4SLinus Torvalds 
898a978d6f5SNick Piggin 		/*
899a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
900a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
901a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
902a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
903a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
904a978d6f5SNick Piggin 		 */
905a978d6f5SNick Piggin 		__clear_page_locked(page);
906e286781dSNick Piggin free_it:
90705ff5137SAndrew Morton 		nr_reclaimed++;
908abe4c3b5SMel Gorman 
909abe4c3b5SMel Gorman 		/*
910abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
911abe4c3b5SMel Gorman 		 * appear not as the counts should be low
912abe4c3b5SMel Gorman 		 */
913abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
9141da177e4SLinus Torvalds 		continue;
9151da177e4SLinus Torvalds 
916b291f000SNick Piggin cull_mlocked:
91763d6c5adSHugh Dickins 		if (PageSwapCache(page))
91863d6c5adSHugh Dickins 			try_to_free_swap(page);
919b291f000SNick Piggin 		unlock_page(page);
920b291f000SNick Piggin 		putback_lru_page(page);
921b291f000SNick Piggin 		continue;
922b291f000SNick Piggin 
9231da177e4SLinus Torvalds activate_locked:
92468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
92568a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
926a2c43eedSHugh Dickins 			try_to_free_swap(page);
927894bc310SLee Schermerhorn 		VM_BUG_ON(PageActive(page));
9281da177e4SLinus Torvalds 		SetPageActive(page);
9291da177e4SLinus Torvalds 		pgactivate++;
9301da177e4SLinus Torvalds keep_locked:
9311da177e4SLinus Torvalds 		unlock_page(page);
9321da177e4SLinus Torvalds keep:
9331da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
934b291f000SNick Piggin 		VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
9351da177e4SLinus Torvalds 	}
936abe4c3b5SMel Gorman 
9370e093d99SMel Gorman 	/*
9380e093d99SMel Gorman 	 * Tag a zone as congested if all the dirty pages encountered were
9390e093d99SMel Gorman 	 * backed by a congested BDI. In this case, reclaimers should just
9400e093d99SMel Gorman 	 * back off and wait for congestion to clear because further reclaim
9410e093d99SMel Gorman 	 * will encounter the same problem
9420e093d99SMel Gorman 	 */
94389b5fae5SJohannes Weiner 	if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
944f16015fbSJohannes Weiner 		zone_set_flag(mz->zone, ZONE_CONGESTED);
9450e093d99SMel Gorman 
946cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
947abe4c3b5SMel Gorman 
9481da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
949f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
95092df3a72SMel Gorman 	*ret_nr_dirty += nr_dirty;
95192df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
95205ff5137SAndrew Morton 	return nr_reclaimed;
9531da177e4SLinus Torvalds }
9541da177e4SLinus Torvalds 
9555ad333ebSAndy Whitcroft /*
9565ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
9575ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
9585ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
9595ad333ebSAndy Whitcroft  *
9605ad333ebSAndy Whitcroft  * page:	page to consider
9615ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
9625ad333ebSAndy Whitcroft  *
9635ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
9645ad333ebSAndy Whitcroft  */
9654356f21dSMinchan Kim int __isolate_lru_page(struct page *page, isolate_mode_t mode, int file)
9665ad333ebSAndy Whitcroft {
9674356f21dSMinchan Kim 	bool all_lru_mode;
9685ad333ebSAndy Whitcroft 	int ret = -EINVAL;
9695ad333ebSAndy Whitcroft 
9705ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
9715ad333ebSAndy Whitcroft 	if (!PageLRU(page))
9725ad333ebSAndy Whitcroft 		return ret;
9735ad333ebSAndy Whitcroft 
9744356f21dSMinchan Kim 	all_lru_mode = (mode & (ISOLATE_ACTIVE|ISOLATE_INACTIVE)) ==
9754356f21dSMinchan Kim 		(ISOLATE_ACTIVE|ISOLATE_INACTIVE);
9764356f21dSMinchan Kim 
9775ad333ebSAndy Whitcroft 	/*
9785ad333ebSAndy Whitcroft 	 * When checking the active state, we need to be sure we are
9795ad333ebSAndy Whitcroft 	 * dealing with comparible boolean values.  Take the logical not
9805ad333ebSAndy Whitcroft 	 * of each.
9815ad333ebSAndy Whitcroft 	 */
9824356f21dSMinchan Kim 	if (!all_lru_mode && !PageActive(page) != !(mode & ISOLATE_ACTIVE))
9835ad333ebSAndy Whitcroft 		return ret;
9845ad333ebSAndy Whitcroft 
9854356f21dSMinchan Kim 	if (!all_lru_mode && !!page_is_file_cache(page) != file)
9864f98a2feSRik van Riel 		return ret;
9874f98a2feSRik van Riel 
988c53919adSMel Gorman 	/* Do not give back unevictable pages for compaction */
989894bc310SLee Schermerhorn 	if (PageUnevictable(page))
990894bc310SLee Schermerhorn 		return ret;
991894bc310SLee Schermerhorn 
9925ad333ebSAndy Whitcroft 	ret = -EBUSY;
99308e552c6SKAMEZAWA Hiroyuki 
994c8244935SMel Gorman 	/*
995c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
996c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
997c8244935SMel Gorman 	 * blocking - clean pages for the most part.
998c8244935SMel Gorman 	 *
999c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1000c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1001c8244935SMel Gorman 	 *
1002c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1003c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1004c8244935SMel Gorman 	 */
1005c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1006c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1007c8244935SMel Gorman 		if (PageWriteback(page))
100839deaf85SMinchan Kim 			return ret;
100939deaf85SMinchan Kim 
1010c8244935SMel Gorman 		if (PageDirty(page)) {
1011c8244935SMel Gorman 			struct address_space *mapping;
1012c8244935SMel Gorman 
1013c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1014c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1015c8244935SMel Gorman 				return ret;
1016c8244935SMel Gorman 
1017c8244935SMel Gorman 			/*
1018c8244935SMel Gorman 			 * Only pages without mappings or that have a
1019c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1020c8244935SMel Gorman 			 * without blocking
1021c8244935SMel Gorman 			 */
1022c8244935SMel Gorman 			mapping = page_mapping(page);
1023c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1024c8244935SMel Gorman 				return ret;
1025c8244935SMel Gorman 		}
1026c8244935SMel Gorman 	}
1027c8244935SMel Gorman 
1028f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1029f80c0673SMinchan Kim 		return ret;
1030f80c0673SMinchan Kim 
10315ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
10325ad333ebSAndy Whitcroft 		/*
10335ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
10345ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
10355ad333ebSAndy Whitcroft 		 * page release code relies on it.
10365ad333ebSAndy Whitcroft 		 */
10375ad333ebSAndy Whitcroft 		ClearPageLRU(page);
10385ad333ebSAndy Whitcroft 		ret = 0;
10395ad333ebSAndy Whitcroft 	}
10405ad333ebSAndy Whitcroft 
10415ad333ebSAndy Whitcroft 	return ret;
10425ad333ebSAndy Whitcroft }
10435ad333ebSAndy Whitcroft 
104449d2e9ccSChristoph Lameter /*
10451da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
10461da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
10471da177e4SLinus Torvalds  * and working on them outside the LRU lock.
10481da177e4SLinus Torvalds  *
10491da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
10501da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
10511da177e4SLinus Torvalds  *
10521da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
10531da177e4SLinus Torvalds  *
10541da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
1055f626012dSHugh Dickins  * @mz:		The mem_cgroup_zone to pull pages from.
10561da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1057f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1058fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
10595ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
1060f626012dSHugh Dickins  * @active:	True [1] if isolating active pages
10614f98a2feSRik van Riel  * @file:	True [1] if isolating file [!anon] pages
10621da177e4SLinus Torvalds  *
10631da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
10641da177e4SLinus Torvalds  */
106569e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1066f626012dSHugh Dickins 		struct mem_cgroup_zone *mz, struct list_head *dst,
1067fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1068fe2c2a10SRik van Riel 		isolate_mode_t mode, int active, int file)
10691da177e4SLinus Torvalds {
1070f626012dSHugh Dickins 	struct lruvec *lruvec;
1071f626012dSHugh Dickins 	struct list_head *src;
107269e05944SAndrew Morton 	unsigned long nr_taken = 0;
1073c9b02d97SWu Fengguang 	unsigned long scan;
1074f626012dSHugh Dickins 	int lru = LRU_BASE;
1075f626012dSHugh Dickins 
1076f626012dSHugh Dickins 	lruvec = mem_cgroup_zone_lruvec(mz->zone, mz->mem_cgroup);
1077f626012dSHugh Dickins 	if (active)
1078f626012dSHugh Dickins 		lru += LRU_ACTIVE;
1079f626012dSHugh Dickins 	if (file)
1080f626012dSHugh Dickins 		lru += LRU_FILE;
1081f626012dSHugh Dickins 	src = &lruvec->lists[lru];
10821da177e4SLinus Torvalds 
1083c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
10845ad333ebSAndy Whitcroft 		struct page *page;
10855ad333ebSAndy Whitcroft 
10861da177e4SLinus Torvalds 		page = lru_to_page(src);
10871da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
10881da177e4SLinus Torvalds 
1089725d704eSNick Piggin 		VM_BUG_ON(!PageLRU(page));
10908d438f96SNick Piggin 
10914f98a2feSRik van Riel 		switch (__isolate_lru_page(page, mode, file)) {
10925ad333ebSAndy Whitcroft 		case 0:
1093925b7673SJohannes Weiner 			mem_cgroup_lru_del(page);
10945ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
10952c888cfbSRik van Riel 			nr_taken += hpage_nr_pages(page);
10965ad333ebSAndy Whitcroft 			break;
10977c8ee9a8SNick Piggin 
10985ad333ebSAndy Whitcroft 		case -EBUSY:
10995ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
11005ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
11015ad333ebSAndy Whitcroft 			continue;
11025ad333ebSAndy Whitcroft 
11035ad333ebSAndy Whitcroft 		default:
11045ad333ebSAndy Whitcroft 			BUG();
11055ad333ebSAndy Whitcroft 		}
11065ad333ebSAndy Whitcroft 	}
11071da177e4SLinus Torvalds 
1108f626012dSHugh Dickins 	*nr_scanned = scan;
1109a8a94d15SMel Gorman 
1110fe2c2a10SRik van Riel 	trace_mm_vmscan_lru_isolate(sc->order,
1111a8a94d15SMel Gorman 			nr_to_scan, scan,
1112a8a94d15SMel Gorman 			nr_taken,
1113ea4d349fSTao Ma 			mode, file);
11141da177e4SLinus Torvalds 	return nr_taken;
11151da177e4SLinus Torvalds }
11161da177e4SLinus Torvalds 
111762695a84SNick Piggin /**
111862695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
111962695a84SNick Piggin  * @page: page to isolate from its LRU list
112062695a84SNick Piggin  *
112162695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
112262695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
112362695a84SNick Piggin  *
112462695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
112562695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
112662695a84SNick Piggin  *
112762695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1128894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1129894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1130894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
113162695a84SNick Piggin  *
113262695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
113362695a84SNick Piggin  * found will be decremented.
113462695a84SNick Piggin  *
113562695a84SNick Piggin  * Restrictions:
113662695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
113762695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
113862695a84SNick Piggin  *     without a stable reference).
113962695a84SNick Piggin  * (2) the lru_lock must not be held.
114062695a84SNick Piggin  * (3) interrupts must be enabled.
114162695a84SNick Piggin  */
114262695a84SNick Piggin int isolate_lru_page(struct page *page)
114362695a84SNick Piggin {
114462695a84SNick Piggin 	int ret = -EBUSY;
114562695a84SNick Piggin 
11460c917313SKonstantin Khlebnikov 	VM_BUG_ON(!page_count(page));
11470c917313SKonstantin Khlebnikov 
114862695a84SNick Piggin 	if (PageLRU(page)) {
114962695a84SNick Piggin 		struct zone *zone = page_zone(page);
115062695a84SNick Piggin 
115162695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
11520c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1153894bc310SLee Schermerhorn 			int lru = page_lru(page);
115462695a84SNick Piggin 			ret = 0;
11550c917313SKonstantin Khlebnikov 			get_page(page);
115662695a84SNick Piggin 			ClearPageLRU(page);
11574f98a2feSRik van Riel 
11584f98a2feSRik van Riel 			del_page_from_lru_list(zone, page, lru);
115962695a84SNick Piggin 		}
116062695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
116162695a84SNick Piggin 	}
116262695a84SNick Piggin 	return ret;
116362695a84SNick Piggin }
116462695a84SNick Piggin 
11655ad333ebSAndy Whitcroft /*
116635cd7815SRik van Riel  * Are there way too many processes in the direct reclaim path already?
116735cd7815SRik van Riel  */
116835cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
116935cd7815SRik van Riel 		struct scan_control *sc)
117035cd7815SRik van Riel {
117135cd7815SRik van Riel 	unsigned long inactive, isolated;
117235cd7815SRik van Riel 
117335cd7815SRik van Riel 	if (current_is_kswapd())
117435cd7815SRik van Riel 		return 0;
117535cd7815SRik van Riel 
117689b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
117735cd7815SRik van Riel 		return 0;
117835cd7815SRik van Riel 
117935cd7815SRik van Riel 	if (file) {
118035cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
118135cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
118235cd7815SRik van Riel 	} else {
118335cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
118435cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
118535cd7815SRik van Riel 	}
118635cd7815SRik van Riel 
118735cd7815SRik van Riel 	return isolated > inactive;
118835cd7815SRik van Riel }
118935cd7815SRik van Riel 
119066635629SMel Gorman static noinline_for_stack void
11913f79768fSHugh Dickins putback_inactive_pages(struct mem_cgroup_zone *mz,
119266635629SMel Gorman 		       struct list_head *page_list)
119366635629SMel Gorman {
1194f16015fbSJohannes Weiner 	struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(mz);
11953f79768fSHugh Dickins 	struct zone *zone = mz->zone;
11963f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
119766635629SMel Gorman 
119866635629SMel Gorman 	/*
119966635629SMel Gorman 	 * Put back any unfreeable pages.
120066635629SMel Gorman 	 */
120166635629SMel Gorman 	while (!list_empty(page_list)) {
12023f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
120366635629SMel Gorman 		int lru;
12043f79768fSHugh Dickins 
120566635629SMel Gorman 		VM_BUG_ON(PageLRU(page));
120666635629SMel Gorman 		list_del(&page->lru);
120766635629SMel Gorman 		if (unlikely(!page_evictable(page, NULL))) {
120866635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
120966635629SMel Gorman 			putback_lru_page(page);
121066635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
121166635629SMel Gorman 			continue;
121266635629SMel Gorman 		}
12137a608572SLinus Torvalds 		SetPageLRU(page);
121466635629SMel Gorman 		lru = page_lru(page);
12157a608572SLinus Torvalds 		add_page_to_lru_list(zone, page, lru);
121666635629SMel Gorman 		if (is_active_lru(lru)) {
121766635629SMel Gorman 			int file = is_file_lru(lru);
12189992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
12199992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
122066635629SMel Gorman 		}
12212bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
12222bcf8879SHugh Dickins 			__ClearPageLRU(page);
12232bcf8879SHugh Dickins 			__ClearPageActive(page);
12242bcf8879SHugh Dickins 			del_page_from_lru_list(zone, page, lru);
12252bcf8879SHugh Dickins 
12262bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
122766635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
12282bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
122966635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
12302bcf8879SHugh Dickins 			} else
12312bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
123266635629SMel Gorman 		}
123366635629SMel Gorman 	}
123466635629SMel Gorman 
12353f79768fSHugh Dickins 	/*
12363f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
12373f79768fSHugh Dickins 	 */
12383f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
123966635629SMel Gorman }
124066635629SMel Gorman 
1241f16015fbSJohannes Weiner static noinline_for_stack void
1242f16015fbSJohannes Weiner update_isolated_counts(struct mem_cgroup_zone *mz,
12433f79768fSHugh Dickins 		       struct list_head *page_list,
12441489fa14SMel Gorman 		       unsigned long *nr_anon,
12453f79768fSHugh Dickins 		       unsigned long *nr_file)
12461489fa14SMel Gorman {
1247f16015fbSJohannes Weiner 	struct zone *zone = mz->zone;
12481489fa14SMel Gorman 	unsigned int count[NR_LRU_LISTS] = { 0, };
12493f79768fSHugh Dickins 	unsigned long nr_active = 0;
12503f79768fSHugh Dickins 	struct page *page;
12513f79768fSHugh Dickins 	int lru;
12521489fa14SMel Gorman 
12533f79768fSHugh Dickins 	/*
12543f79768fSHugh Dickins 	 * Count pages and clear active flags
12553f79768fSHugh Dickins 	 */
12563f79768fSHugh Dickins 	list_for_each_entry(page, page_list, lru) {
12573f79768fSHugh Dickins 		int numpages = hpage_nr_pages(page);
12583f79768fSHugh Dickins 		lru = page_lru_base_type(page);
12593f79768fSHugh Dickins 		if (PageActive(page)) {
12603f79768fSHugh Dickins 			lru += LRU_ACTIVE;
12613f79768fSHugh Dickins 			ClearPageActive(page);
12623f79768fSHugh Dickins 			nr_active += numpages;
12633f79768fSHugh Dickins 		}
12643f79768fSHugh Dickins 		count[lru] += numpages;
12653f79768fSHugh Dickins 	}
12663f79768fSHugh Dickins 
1267d563c050SHillf Danton 	preempt_disable();
12681489fa14SMel Gorman 	__count_vm_events(PGDEACTIVATE, nr_active);
12691489fa14SMel Gorman 
12701489fa14SMel Gorman 	__mod_zone_page_state(zone, NR_ACTIVE_FILE,
12711489fa14SMel Gorman 			      -count[LRU_ACTIVE_FILE]);
12721489fa14SMel Gorman 	__mod_zone_page_state(zone, NR_INACTIVE_FILE,
12731489fa14SMel Gorman 			      -count[LRU_INACTIVE_FILE]);
12741489fa14SMel Gorman 	__mod_zone_page_state(zone, NR_ACTIVE_ANON,
12751489fa14SMel Gorman 			      -count[LRU_ACTIVE_ANON]);
12761489fa14SMel Gorman 	__mod_zone_page_state(zone, NR_INACTIVE_ANON,
12771489fa14SMel Gorman 			      -count[LRU_INACTIVE_ANON]);
12781489fa14SMel Gorman 
12791489fa14SMel Gorman 	*nr_anon = count[LRU_ACTIVE_ANON] + count[LRU_INACTIVE_ANON];
12801489fa14SMel Gorman 	*nr_file = count[LRU_ACTIVE_FILE] + count[LRU_INACTIVE_FILE];
12811489fa14SMel Gorman 
1282d563c050SHillf Danton 	__mod_zone_page_state(zone, NR_ISOLATED_ANON, *nr_anon);
1283d563c050SHillf Danton 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, *nr_file);
1284d563c050SHillf Danton 	preempt_enable();
12851489fa14SMel Gorman }
12861489fa14SMel Gorman 
128766635629SMel Gorman /*
12881742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
12891742f19fSAndrew Morton  * of reclaimed pages
12901da177e4SLinus Torvalds  */
129166635629SMel Gorman static noinline_for_stack unsigned long
1292f16015fbSJohannes Weiner shrink_inactive_list(unsigned long nr_to_scan, struct mem_cgroup_zone *mz,
129366635629SMel Gorman 		     struct scan_control *sc, int priority, int file)
12941da177e4SLinus Torvalds {
12951da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1296e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
129705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1298e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1299e247dbceSKOSAKI Motohiro 	unsigned long nr_anon;
1300e247dbceSKOSAKI Motohiro 	unsigned long nr_file;
130192df3a72SMel Gorman 	unsigned long nr_dirty = 0;
130292df3a72SMel Gorman 	unsigned long nr_writeback = 0;
130361317289SHillf Danton 	isolate_mode_t isolate_mode = ISOLATE_INACTIVE;
1304f16015fbSJohannes Weiner 	struct zone *zone = mz->zone;
1305d563c050SHillf Danton 	struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(mz);
130678dc583dSKOSAKI Motohiro 
130735cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
130858355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
130935cd7815SRik van Riel 
131035cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
131135cd7815SRik van Riel 		if (fatal_signal_pending(current))
131235cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
131335cd7815SRik van Riel 	}
131435cd7815SRik van Riel 
13151da177e4SLinus Torvalds 	lru_add_drain();
1316f80c0673SMinchan Kim 
1317f80c0673SMinchan Kim 	if (!sc->may_unmap)
131861317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1319f80c0673SMinchan Kim 	if (!sc->may_writepage)
132061317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1321f80c0673SMinchan Kim 
13221da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
13231da177e4SLinus Torvalds 
1324fe2c2a10SRik van Riel 	nr_taken = isolate_lru_pages(nr_to_scan, mz, &page_list, &nr_scanned,
1325fe2c2a10SRik van Riel 				     sc, isolate_mode, 0, file);
132689b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1327e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1328b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1329b35ea17bSKOSAKI Motohiro 			__count_zone_vm_events(PGSCAN_KSWAPD, zone,
1330e247dbceSKOSAKI Motohiro 					       nr_scanned);
1331b35ea17bSKOSAKI Motohiro 		else
1332b35ea17bSKOSAKI Motohiro 			__count_zone_vm_events(PGSCAN_DIRECT, zone,
1333e247dbceSKOSAKI Motohiro 					       nr_scanned);
1334b35ea17bSKOSAKI Motohiro 	}
133566635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1336d563c050SHillf Danton 
1337d563c050SHillf Danton 	if (nr_taken == 0)
133866635629SMel Gorman 		return 0;
1339b35ea17bSKOSAKI Motohiro 
13403f79768fSHugh Dickins 	update_isolated_counts(mz, &page_list, &nr_anon, &nr_file);
13413f79768fSHugh Dickins 
1342f16015fbSJohannes Weiner 	nr_reclaimed = shrink_page_list(&page_list, mz, sc, priority,
134392df3a72SMel Gorman 						&nr_dirty, &nr_writeback);
1344c661b078SAndy Whitcroft 
13453f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
13463f79768fSHugh Dickins 
1347d563c050SHillf Danton 	reclaim_stat->recent_scanned[0] += nr_anon;
1348d563c050SHillf Danton 	reclaim_stat->recent_scanned[1] += nr_file;
1349d563c050SHillf Danton 
1350904249aaSYing Han 	if (global_reclaim(sc)) {
1351b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1352904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1353904249aaSYing Han 					       nr_reclaimed);
1354904249aaSYing Han 		else
1355904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1356904249aaSYing Han 					       nr_reclaimed);
1357904249aaSYing Han 	}
1358a74609faSNick Piggin 
13593f79768fSHugh Dickins 	putback_inactive_pages(mz, &page_list);
13603f79768fSHugh Dickins 
13613f79768fSHugh Dickins 	__mod_zone_page_state(zone, NR_ISOLATED_ANON, -nr_anon);
13623f79768fSHugh Dickins 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -nr_file);
13633f79768fSHugh Dickins 
13643f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
13653f79768fSHugh Dickins 
13663f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1367e11da5b4SMel Gorman 
136892df3a72SMel Gorman 	/*
136992df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
137092df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
137192df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
137292df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
137392df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
137492df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
137592df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
137692df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
137792df3a72SMel Gorman 	 *
137892df3a72SMel Gorman 	 * This scales the number of dirty pages that must be under writeback
137992df3a72SMel Gorman 	 * before throttling depending on priority. It is a simple backoff
138092df3a72SMel Gorman 	 * function that has the most effect in the range DEF_PRIORITY to
138192df3a72SMel Gorman 	 * DEF_PRIORITY-2 which is the priority reclaim is considered to be
138292df3a72SMel Gorman 	 * in trouble and reclaim is considered to be in trouble.
138392df3a72SMel Gorman 	 *
138492df3a72SMel Gorman 	 * DEF_PRIORITY   100% isolated pages must be PageWriteback to throttle
138592df3a72SMel Gorman 	 * DEF_PRIORITY-1  50% must be PageWriteback
138692df3a72SMel Gorman 	 * DEF_PRIORITY-2  25% must be PageWriteback, kswapd in trouble
138792df3a72SMel Gorman 	 * ...
138892df3a72SMel Gorman 	 * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
138992df3a72SMel Gorman 	 *                     isolated page is PageWriteback
139092df3a72SMel Gorman 	 */
139192df3a72SMel Gorman 	if (nr_writeback && nr_writeback >= (nr_taken >> (DEF_PRIORITY-priority)))
139292df3a72SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
139392df3a72SMel Gorman 
1394e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1395e11da5b4SMel Gorman 		zone_idx(zone),
1396e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
1397e11da5b4SMel Gorman 		priority,
139823b9da55SMel Gorman 		trace_shrink_flags(file));
139905ff5137SAndrew Morton 	return nr_reclaimed;
14001da177e4SLinus Torvalds }
14011da177e4SLinus Torvalds 
14023bb1a852SMartin Bligh /*
14031cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
14041cfb419bSKAMEZAWA Hiroyuki  *
14051cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
14061cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
14071cfb419bSKAMEZAWA Hiroyuki  *
14081cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
14091cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
14101cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
14111cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
14121cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
14131cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
14141cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
14151cfb419bSKAMEZAWA Hiroyuki  *
14161cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
14171cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
14181cfb419bSKAMEZAWA Hiroyuki  */
14191cfb419bSKAMEZAWA Hiroyuki 
14203eb4140fSWu Fengguang static void move_active_pages_to_lru(struct zone *zone,
14213eb4140fSWu Fengguang 				     struct list_head *list,
14222bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
14233eb4140fSWu Fengguang 				     enum lru_list lru)
14243eb4140fSWu Fengguang {
14253eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
14263eb4140fSWu Fengguang 	struct page *page;
14273eb4140fSWu Fengguang 
14283eb4140fSWu Fengguang 	while (!list_empty(list)) {
1429925b7673SJohannes Weiner 		struct lruvec *lruvec;
1430925b7673SJohannes Weiner 
14313eb4140fSWu Fengguang 		page = lru_to_page(list);
14323eb4140fSWu Fengguang 
14333eb4140fSWu Fengguang 		VM_BUG_ON(PageLRU(page));
14343eb4140fSWu Fengguang 		SetPageLRU(page);
14353eb4140fSWu Fengguang 
1436925b7673SJohannes Weiner 		lruvec = mem_cgroup_lru_add_list(zone, page, lru);
1437925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
14382c888cfbSRik van Riel 		pgmoved += hpage_nr_pages(page);
14393eb4140fSWu Fengguang 
14402bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
14412bcf8879SHugh Dickins 			__ClearPageLRU(page);
14422bcf8879SHugh Dickins 			__ClearPageActive(page);
14432bcf8879SHugh Dickins 			del_page_from_lru_list(zone, page, lru);
14442bcf8879SHugh Dickins 
14452bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
14463eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
14472bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
14483eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
14492bcf8879SHugh Dickins 			} else
14502bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
14513eb4140fSWu Fengguang 		}
14523eb4140fSWu Fengguang 	}
14533eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
14543eb4140fSWu Fengguang 	if (!is_active_lru(lru))
14553eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
14563eb4140fSWu Fengguang }
14571cfb419bSKAMEZAWA Hiroyuki 
1458f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
1459f16015fbSJohannes Weiner 			       struct mem_cgroup_zone *mz,
1460f16015fbSJohannes Weiner 			       struct scan_control *sc,
1461f16015fbSJohannes Weiner 			       int priority, int file)
14621cfb419bSKAMEZAWA Hiroyuki {
146344c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1464f626012dSHugh Dickins 	unsigned long nr_scanned;
14656fe6b7e3SWu Fengguang 	unsigned long vm_flags;
14661cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
14678cab4754SWu Fengguang 	LIST_HEAD(l_active);
1468b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
14691cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
1470f16015fbSJohannes Weiner 	struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(mz);
147144c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
147261317289SHillf Danton 	isolate_mode_t isolate_mode = ISOLATE_ACTIVE;
1473f16015fbSJohannes Weiner 	struct zone *zone = mz->zone;
14741cfb419bSKAMEZAWA Hiroyuki 
14751da177e4SLinus Torvalds 	lru_add_drain();
1476f80c0673SMinchan Kim 
1477f80c0673SMinchan Kim 	if (!sc->may_unmap)
147861317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1479f80c0673SMinchan Kim 	if (!sc->may_writepage)
148061317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1481f80c0673SMinchan Kim 
14821da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1483925b7673SJohannes Weiner 
1484fe2c2a10SRik van Riel 	nr_taken = isolate_lru_pages(nr_to_scan, mz, &l_hold, &nr_scanned, sc,
148561317289SHillf Danton 				     isolate_mode, 1, file);
148689b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1487f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
148889b5fae5SJohannes Weiner 
1489b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
14901cfb419bSKAMEZAWA Hiroyuki 
1491f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
14924f98a2feSRik van Riel 	if (file)
149344c241f1SKOSAKI Motohiro 		__mod_zone_page_state(zone, NR_ACTIVE_FILE, -nr_taken);
14944f98a2feSRik van Riel 	else
149544c241f1SKOSAKI Motohiro 		__mod_zone_page_state(zone, NR_ACTIVE_ANON, -nr_taken);
1496a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
14971da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
14981da177e4SLinus Torvalds 
14991da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
15001da177e4SLinus Torvalds 		cond_resched();
15011da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
15021da177e4SLinus Torvalds 		list_del(&page->lru);
15037e9cd484SRik van Riel 
1504894bc310SLee Schermerhorn 		if (unlikely(!page_evictable(page, NULL))) {
1505894bc310SLee Schermerhorn 			putback_lru_page(page);
1506894bc310SLee Schermerhorn 			continue;
1507894bc310SLee Schermerhorn 		}
1508894bc310SLee Schermerhorn 
1509cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1510cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1511cc715d99SMel Gorman 				if (page_has_private(page))
1512cc715d99SMel Gorman 					try_to_release_page(page, 0);
1513cc715d99SMel Gorman 				unlock_page(page);
1514cc715d99SMel Gorman 			}
1515cc715d99SMel Gorman 		}
1516cc715d99SMel Gorman 
1517c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1518c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
15199992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
15208cab4754SWu Fengguang 			/*
15218cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
15228cab4754SWu Fengguang 			 * give them one more trip around the active list. So
15238cab4754SWu Fengguang 			 * that executable code get better chances to stay in
15248cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
15258cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
15268cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
15278cab4754SWu Fengguang 			 * so we ignore them here.
15288cab4754SWu Fengguang 			 */
152941e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
15308cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
15318cab4754SWu Fengguang 				continue;
15328cab4754SWu Fengguang 			}
15338cab4754SWu Fengguang 		}
15347e9cd484SRik van Riel 
15355205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
15361da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
15371da177e4SLinus Torvalds 	}
15381da177e4SLinus Torvalds 
1539b555749aSAndrew Morton 	/*
15408cab4754SWu Fengguang 	 * Move pages back to the lru list.
1541b555749aSAndrew Morton 	 */
15422a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
15434f98a2feSRik van Riel 	/*
15448cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
15458cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
15468cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
15478cab4754SWu Fengguang 	 * get_scan_ratio.
1548556adecbSRik van Riel 	 */
1549b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1550556adecbSRik van Riel 
15512bcf8879SHugh Dickins 	move_active_pages_to_lru(zone, &l_active, &l_hold,
15523eb4140fSWu Fengguang 						LRU_ACTIVE + file * LRU_FILE);
15532bcf8879SHugh Dickins 	move_active_pages_to_lru(zone, &l_inactive, &l_hold,
15543eb4140fSWu Fengguang 						LRU_BASE   + file * LRU_FILE);
1555a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1556f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
15572bcf8879SHugh Dickins 
15582bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
15591da177e4SLinus Torvalds }
15601da177e4SLinus Torvalds 
156174e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
156214797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1563f89eb90eSKOSAKI Motohiro {
1564f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1565f89eb90eSKOSAKI Motohiro 
1566f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1567f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1568f89eb90eSKOSAKI Motohiro 
1569f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1570f89eb90eSKOSAKI Motohiro 		return 1;
1571f89eb90eSKOSAKI Motohiro 
1572f89eb90eSKOSAKI Motohiro 	return 0;
1573f89eb90eSKOSAKI Motohiro }
1574f89eb90eSKOSAKI Motohiro 
157514797e23SKOSAKI Motohiro /**
157614797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
157714797e23SKOSAKI Motohiro  * @zone: zone to check
157814797e23SKOSAKI Motohiro  * @sc:   scan control of this context
157914797e23SKOSAKI Motohiro  *
158014797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
158114797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
158214797e23SKOSAKI Motohiro  */
1583f16015fbSJohannes Weiner static int inactive_anon_is_low(struct mem_cgroup_zone *mz)
158414797e23SKOSAKI Motohiro {
158574e3f3c3SMinchan Kim 	/*
158674e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
158774e3f3c3SMinchan Kim 	 * is pointless.
158874e3f3c3SMinchan Kim 	 */
158974e3f3c3SMinchan Kim 	if (!total_swap_pages)
159074e3f3c3SMinchan Kim 		return 0;
159174e3f3c3SMinchan Kim 
1592f16015fbSJohannes Weiner 	if (!scanning_global_lru(mz))
1593f16015fbSJohannes Weiner 		return mem_cgroup_inactive_anon_is_low(mz->mem_cgroup,
1594f16015fbSJohannes Weiner 						       mz->zone);
1595f16015fbSJohannes Weiner 
1596f16015fbSJohannes Weiner 	return inactive_anon_is_low_global(mz->zone);
159714797e23SKOSAKI Motohiro }
159874e3f3c3SMinchan Kim #else
1599f16015fbSJohannes Weiner static inline int inactive_anon_is_low(struct mem_cgroup_zone *mz)
160074e3f3c3SMinchan Kim {
160174e3f3c3SMinchan Kim 	return 0;
160274e3f3c3SMinchan Kim }
160374e3f3c3SMinchan Kim #endif
160414797e23SKOSAKI Motohiro 
160556e49d21SRik van Riel static int inactive_file_is_low_global(struct zone *zone)
160656e49d21SRik van Riel {
160756e49d21SRik van Riel 	unsigned long active, inactive;
160856e49d21SRik van Riel 
160956e49d21SRik van Riel 	active = zone_page_state(zone, NR_ACTIVE_FILE);
161056e49d21SRik van Riel 	inactive = zone_page_state(zone, NR_INACTIVE_FILE);
161156e49d21SRik van Riel 
161256e49d21SRik van Riel 	return (active > inactive);
161356e49d21SRik van Riel }
161456e49d21SRik van Riel 
161556e49d21SRik van Riel /**
161656e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1617f16015fbSJohannes Weiner  * @mz: memory cgroup and zone to check
161856e49d21SRik van Riel  *
161956e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
162056e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
162156e49d21SRik van Riel  * than half of the file pages are on the inactive list.
162256e49d21SRik van Riel  *
162356e49d21SRik van Riel  * Once we get to that situation, protect the system's working
162456e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
162556e49d21SRik van Riel  *
162656e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
162756e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
162856e49d21SRik van Riel  */
1629f16015fbSJohannes Weiner static int inactive_file_is_low(struct mem_cgroup_zone *mz)
163056e49d21SRik van Riel {
1631f16015fbSJohannes Weiner 	if (!scanning_global_lru(mz))
1632f16015fbSJohannes Weiner 		return mem_cgroup_inactive_file_is_low(mz->mem_cgroup,
1633f16015fbSJohannes Weiner 						       mz->zone);
163456e49d21SRik van Riel 
1635f16015fbSJohannes Weiner 	return inactive_file_is_low_global(mz->zone);
163656e49d21SRik van Riel }
163756e49d21SRik van Riel 
1638f16015fbSJohannes Weiner static int inactive_list_is_low(struct mem_cgroup_zone *mz, int file)
1639b39415b2SRik van Riel {
1640b39415b2SRik van Riel 	if (file)
1641f16015fbSJohannes Weiner 		return inactive_file_is_low(mz);
1642b39415b2SRik van Riel 	else
1643f16015fbSJohannes Weiner 		return inactive_anon_is_low(mz);
1644b39415b2SRik van Riel }
1645b39415b2SRik van Riel 
16464f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1647f16015fbSJohannes Weiner 				 struct mem_cgroup_zone *mz,
1648f16015fbSJohannes Weiner 				 struct scan_control *sc, int priority)
1649b69408e8SChristoph Lameter {
16504f98a2feSRik van Riel 	int file = is_file_lru(lru);
16514f98a2feSRik van Riel 
1652b39415b2SRik van Riel 	if (is_active_lru(lru)) {
1653f16015fbSJohannes Weiner 		if (inactive_list_is_low(mz, file))
1654f16015fbSJohannes Weiner 			shrink_active_list(nr_to_scan, mz, sc, priority, file);
1655556adecbSRik van Riel 		return 0;
1656556adecbSRik van Riel 	}
1657556adecbSRik van Riel 
1658f16015fbSJohannes Weiner 	return shrink_inactive_list(nr_to_scan, mz, sc, priority, file);
1659b69408e8SChristoph Lameter }
1660b69408e8SChristoph Lameter 
1661f16015fbSJohannes Weiner static int vmscan_swappiness(struct mem_cgroup_zone *mz,
1662f16015fbSJohannes Weiner 			     struct scan_control *sc)
16631f4c025bSKAMEZAWA Hiroyuki {
166489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
16651f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
1666f16015fbSJohannes Weiner 	return mem_cgroup_swappiness(mz->mem_cgroup);
16671f4c025bSKAMEZAWA Hiroyuki }
16681f4c025bSKAMEZAWA Hiroyuki 
16691da177e4SLinus Torvalds /*
16704f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
16714f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
16724f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
16734f98a2feSRik van Riel  * onto the active list instead of evict.
16744f98a2feSRik van Riel  *
167576a33fc3SShaohua Li  * nr[0] = anon pages to scan; nr[1] = file pages to scan
16764f98a2feSRik van Riel  */
1677f16015fbSJohannes Weiner static void get_scan_count(struct mem_cgroup_zone *mz, struct scan_control *sc,
167876a33fc3SShaohua Li 			   unsigned long *nr, int priority)
16794f98a2feSRik van Riel {
16804f98a2feSRik van Riel 	unsigned long anon, file, free;
16814f98a2feSRik van Riel 	unsigned long anon_prio, file_prio;
16824f98a2feSRik van Riel 	unsigned long ap, fp;
1683f16015fbSJohannes Weiner 	struct zone_reclaim_stat *reclaim_stat = get_reclaim_stat(mz);
168476a33fc3SShaohua Li 	u64 fraction[2], denominator;
16854111304dSHugh Dickins 	enum lru_list lru;
168676a33fc3SShaohua Li 	int noswap = 0;
1687a4d3e9e7SJohannes Weiner 	bool force_scan = false;
1688246e87a9SKAMEZAWA Hiroyuki 
1689f11c0ca5SJohannes Weiner 	/*
1690f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1691f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1692f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1693f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1694f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1695f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1696f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1697f11c0ca5SJohannes Weiner 	 * well.
1698f11c0ca5SJohannes Weiner 	 */
1699b95a2f2dSJohannes Weiner 	if (current_is_kswapd() && mz->zone->all_unreclaimable)
1700a4d3e9e7SJohannes Weiner 		force_scan = true;
170189b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1702a4d3e9e7SJohannes Weiner 		force_scan = true;
170376a33fc3SShaohua Li 
170476a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
170576a33fc3SShaohua Li 	if (!sc->may_swap || (nr_swap_pages <= 0)) {
170676a33fc3SShaohua Li 		noswap = 1;
170776a33fc3SShaohua Li 		fraction[0] = 0;
170876a33fc3SShaohua Li 		fraction[1] = 1;
170976a33fc3SShaohua Li 		denominator = 1;
171076a33fc3SShaohua Li 		goto out;
171176a33fc3SShaohua Li 	}
17124f98a2feSRik van Riel 
1713f16015fbSJohannes Weiner 	anon  = zone_nr_lru_pages(mz, LRU_ACTIVE_ANON) +
1714f16015fbSJohannes Weiner 		zone_nr_lru_pages(mz, LRU_INACTIVE_ANON);
1715f16015fbSJohannes Weiner 	file  = zone_nr_lru_pages(mz, LRU_ACTIVE_FILE) +
1716f16015fbSJohannes Weiner 		zone_nr_lru_pages(mz, LRU_INACTIVE_FILE);
1717a4d3e9e7SJohannes Weiner 
171889b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1719f16015fbSJohannes Weiner 		free  = zone_page_state(mz->zone, NR_FREE_PAGES);
1720eeee9a8cSKOSAKI Motohiro 		/* If we have very few page cache pages,
1721eeee9a8cSKOSAKI Motohiro 		   force-scan anon pages. */
1722f16015fbSJohannes Weiner 		if (unlikely(file + free <= high_wmark_pages(mz->zone))) {
172376a33fc3SShaohua Li 			fraction[0] = 1;
172476a33fc3SShaohua Li 			fraction[1] = 0;
172576a33fc3SShaohua Li 			denominator = 1;
172676a33fc3SShaohua Li 			goto out;
17274f98a2feSRik van Riel 		}
1728eeee9a8cSKOSAKI Motohiro 	}
17294f98a2feSRik van Riel 
17304f98a2feSRik van Riel 	/*
173158c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
173258c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
173358c37f6eSKOSAKI Motohiro 	 */
1734f16015fbSJohannes Weiner 	anon_prio = vmscan_swappiness(mz, sc);
1735f16015fbSJohannes Weiner 	file_prio = 200 - vmscan_swappiness(mz, sc);
173658c37f6eSKOSAKI Motohiro 
173758c37f6eSKOSAKI Motohiro 	/*
17384f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
17394f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
17404f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
17414f98a2feSRik van Riel 	 *
17424f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
17434f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
17444f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
17454f98a2feSRik van Riel 	 *
17464f98a2feSRik van Riel 	 * anon in [0], file in [1]
17474f98a2feSRik van Riel 	 */
1748f16015fbSJohannes Weiner 	spin_lock_irq(&mz->zone->lru_lock);
174958c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
17506e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
17516e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
17524f98a2feSRik van Riel 	}
17534f98a2feSRik van Riel 
17546e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
17556e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
17566e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
17574f98a2feSRik van Riel 	}
17584f98a2feSRik van Riel 
17594f98a2feSRik van Riel 	/*
176000d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
176100d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
176200d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
17634f98a2feSRik van Riel 	 */
17646e901571SKOSAKI Motohiro 	ap = (anon_prio + 1) * (reclaim_stat->recent_scanned[0] + 1);
17656e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
17664f98a2feSRik van Riel 
17676e901571SKOSAKI Motohiro 	fp = (file_prio + 1) * (reclaim_stat->recent_scanned[1] + 1);
17686e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
1769f16015fbSJohannes Weiner 	spin_unlock_irq(&mz->zone->lru_lock);
17704f98a2feSRik van Riel 
177176a33fc3SShaohua Li 	fraction[0] = ap;
177276a33fc3SShaohua Li 	fraction[1] = fp;
177376a33fc3SShaohua Li 	denominator = ap + fp + 1;
177476a33fc3SShaohua Li out:
17754111304dSHugh Dickins 	for_each_evictable_lru(lru) {
17764111304dSHugh Dickins 		int file = is_file_lru(lru);
177776a33fc3SShaohua Li 		unsigned long scan;
177876a33fc3SShaohua Li 
17794111304dSHugh Dickins 		scan = zone_nr_lru_pages(mz, lru);
178076a33fc3SShaohua Li 		if (priority || noswap) {
178176a33fc3SShaohua Li 			scan >>= priority;
1782f11c0ca5SJohannes Weiner 			if (!scan && force_scan)
1783f11c0ca5SJohannes Weiner 				scan = SWAP_CLUSTER_MAX;
178476a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
17854f98a2feSRik van Riel 		}
17864111304dSHugh Dickins 		nr[lru] = scan;
178776a33fc3SShaohua Li 	}
17886e08a369SWu Fengguang }
17894f98a2feSRik van Riel 
179023b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
179123b9da55SMel Gorman static bool in_reclaim_compaction(int priority, struct scan_control *sc)
179223b9da55SMel Gorman {
179323b9da55SMel Gorman 	if (COMPACTION_BUILD && sc->order &&
179423b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
179523b9da55SMel Gorman 			 priority < DEF_PRIORITY - 2))
179623b9da55SMel Gorman 		return true;
179723b9da55SMel Gorman 
179823b9da55SMel Gorman 	return false;
179923b9da55SMel Gorman }
180023b9da55SMel Gorman 
18014f98a2feSRik van Riel /*
180223b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
180323b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
180423b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
180523b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
180623b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
18073e7d3449SMel Gorman  */
1808f16015fbSJohannes Weiner static inline bool should_continue_reclaim(struct mem_cgroup_zone *mz,
18093e7d3449SMel Gorman 					unsigned long nr_reclaimed,
18103e7d3449SMel Gorman 					unsigned long nr_scanned,
181123b9da55SMel Gorman 					int priority,
18123e7d3449SMel Gorman 					struct scan_control *sc)
18133e7d3449SMel Gorman {
18143e7d3449SMel Gorman 	unsigned long pages_for_compaction;
18153e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
18163e7d3449SMel Gorman 
18173e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
181823b9da55SMel Gorman 	if (!in_reclaim_compaction(priority, sc))
18193e7d3449SMel Gorman 		return false;
18203e7d3449SMel Gorman 
18212876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
18222876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
18233e7d3449SMel Gorman 		/*
18242876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
18252876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
18262876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
18272876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
18283e7d3449SMel Gorman 		 */
18293e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
18303e7d3449SMel Gorman 			return false;
18312876592fSMel Gorman 	} else {
18322876592fSMel Gorman 		/*
18332876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
18342876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
18352876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
18362876592fSMel Gorman 		 * pages that were scanned. This will return to the
18372876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
18382876592fSMel Gorman 		 * the resulting allocation attempt fails
18392876592fSMel Gorman 		 */
18402876592fSMel Gorman 		if (!nr_reclaimed)
18412876592fSMel Gorman 			return false;
18422876592fSMel Gorman 	}
18433e7d3449SMel Gorman 
18443e7d3449SMel Gorman 	/*
18453e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
18463e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
18473e7d3449SMel Gorman 	 */
18483e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
1849f16015fbSJohannes Weiner 	inactive_lru_pages = zone_nr_lru_pages(mz, LRU_INACTIVE_FILE);
185086cfd3a4SMinchan Kim 	if (nr_swap_pages > 0)
1851f16015fbSJohannes Weiner 		inactive_lru_pages += zone_nr_lru_pages(mz, LRU_INACTIVE_ANON);
18523e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
18533e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
18543e7d3449SMel Gorman 		return true;
18553e7d3449SMel Gorman 
18563e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
1857f16015fbSJohannes Weiner 	switch (compaction_suitable(mz->zone, sc->order)) {
18583e7d3449SMel Gorman 	case COMPACT_PARTIAL:
18593e7d3449SMel Gorman 	case COMPACT_CONTINUE:
18603e7d3449SMel Gorman 		return false;
18613e7d3449SMel Gorman 	default:
18623e7d3449SMel Gorman 		return true;
18633e7d3449SMel Gorman 	}
18643e7d3449SMel Gorman }
18653e7d3449SMel Gorman 
18663e7d3449SMel Gorman /*
18671da177e4SLinus Torvalds  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
18681da177e4SLinus Torvalds  */
1869f16015fbSJohannes Weiner static void shrink_mem_cgroup_zone(int priority, struct mem_cgroup_zone *mz,
187069e05944SAndrew Morton 				   struct scan_control *sc)
18711da177e4SLinus Torvalds {
1872b69408e8SChristoph Lameter 	unsigned long nr[NR_LRU_LISTS];
18738695949aSChristoph Lameter 	unsigned long nr_to_scan;
18744111304dSHugh Dickins 	enum lru_list lru;
1875f0fdc5e8SJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
187622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
18773da367c3SShaohua Li 	struct blk_plug plug;
18781da177e4SLinus Torvalds 
18793e7d3449SMel Gorman restart:
18803e7d3449SMel Gorman 	nr_reclaimed = 0;
1881f0fdc5e8SJohannes Weiner 	nr_scanned = sc->nr_scanned;
1882f16015fbSJohannes Weiner 	get_scan_count(mz, sc, nr, priority);
18831cfb419bSKAMEZAWA Hiroyuki 
18843da367c3SShaohua Li 	blk_start_plug(&plug);
1885556adecbSRik van Riel 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1886556adecbSRik van Riel 					nr[LRU_INACTIVE_FILE]) {
18874111304dSHugh Dickins 		for_each_evictable_lru(lru) {
18884111304dSHugh Dickins 			if (nr[lru]) {
1889ece74b2eSKOSAKI Motohiro 				nr_to_scan = min_t(unsigned long,
18904111304dSHugh Dickins 						   nr[lru], SWAP_CLUSTER_MAX);
18914111304dSHugh Dickins 				nr[lru] -= nr_to_scan;
1892b69408e8SChristoph Lameter 
18934111304dSHugh Dickins 				nr_reclaimed += shrink_list(lru, nr_to_scan,
1894f16015fbSJohannes Weiner 							    mz, sc, priority);
18951da177e4SLinus Torvalds 			}
18961da177e4SLinus Torvalds 		}
1897a79311c1SRik van Riel 		/*
1898a79311c1SRik van Riel 		 * On large memory systems, scan >> priority can become
1899a79311c1SRik van Riel 		 * really large. This is fine for the starting priority;
1900a79311c1SRik van Riel 		 * we want to put equal scanning pressure on each zone.
1901a79311c1SRik van Riel 		 * However, if the VM has a harder time of freeing pages,
1902a79311c1SRik van Riel 		 * with multiple processes reclaiming pages, the total
1903a79311c1SRik van Riel 		 * freeing target can get unreasonably large.
1904a79311c1SRik van Riel 		 */
190541c93088SYing Han 		if (nr_reclaimed >= nr_to_reclaim && priority < DEF_PRIORITY)
1906a79311c1SRik van Riel 			break;
19071da177e4SLinus Torvalds 	}
19083da367c3SShaohua Li 	blk_finish_plug(&plug);
19093e7d3449SMel Gorman 	sc->nr_reclaimed += nr_reclaimed;
191001dbe5c9SKOSAKI Motohiro 
1911556adecbSRik van Riel 	/*
1912556adecbSRik van Riel 	 * Even if we did not try to evict anon pages at all, we want to
1913556adecbSRik van Riel 	 * rebalance the anon lru active/inactive ratio.
1914556adecbSRik van Riel 	 */
1915f16015fbSJohannes Weiner 	if (inactive_anon_is_low(mz))
1916f16015fbSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, mz, sc, priority, 0);
1917556adecbSRik van Riel 
19183e7d3449SMel Gorman 	/* reclaim/compaction might need reclaim to continue */
1919f16015fbSJohannes Weiner 	if (should_continue_reclaim(mz, nr_reclaimed,
192023b9da55SMel Gorman 					sc->nr_scanned - nr_scanned,
192123b9da55SMel Gorman 					priority, sc))
19223e7d3449SMel Gorman 		goto restart;
19233e7d3449SMel Gorman 
1924232ea4d6SAndrew Morton 	throttle_vm_writeout(sc->gfp_mask);
19251da177e4SLinus Torvalds }
19261da177e4SLinus Torvalds 
1927f16015fbSJohannes Weiner static void shrink_zone(int priority, struct zone *zone,
1928f16015fbSJohannes Weiner 			struct scan_control *sc)
1929f16015fbSJohannes Weiner {
19305660048cSJohannes Weiner 	struct mem_cgroup *root = sc->target_mem_cgroup;
19315660048cSJohannes Weiner 	struct mem_cgroup_reclaim_cookie reclaim = {
19325660048cSJohannes Weiner 		.zone = zone,
19335660048cSJohannes Weiner 		.priority = priority,
19345660048cSJohannes Weiner 	};
19355660048cSJohannes Weiner 	struct mem_cgroup *memcg;
19365660048cSJohannes Weiner 
19375660048cSJohannes Weiner 	memcg = mem_cgroup_iter(root, NULL, &reclaim);
19385660048cSJohannes Weiner 	do {
19395660048cSJohannes Weiner 		struct mem_cgroup_zone mz = {
19405660048cSJohannes Weiner 			.mem_cgroup = memcg,
19415660048cSJohannes Weiner 			.zone = zone,
19425660048cSJohannes Weiner 		};
19435660048cSJohannes Weiner 
19445660048cSJohannes Weiner 		shrink_mem_cgroup_zone(priority, &mz, sc);
19455660048cSJohannes Weiner 		/*
19465660048cSJohannes Weiner 		 * Limit reclaim has historically picked one memcg and
19475660048cSJohannes Weiner 		 * scanned it with decreasing priority levels until
19485660048cSJohannes Weiner 		 * nr_to_reclaim had been reclaimed.  This priority
19495660048cSJohannes Weiner 		 * cycle is thus over after a single memcg.
1950b95a2f2dSJohannes Weiner 		 *
1951b95a2f2dSJohannes Weiner 		 * Direct reclaim and kswapd, on the other hand, have
1952b95a2f2dSJohannes Weiner 		 * to scan all memory cgroups to fulfill the overall
1953b95a2f2dSJohannes Weiner 		 * scan target for the zone.
19545660048cSJohannes Weiner 		 */
19555660048cSJohannes Weiner 		if (!global_reclaim(sc)) {
19565660048cSJohannes Weiner 			mem_cgroup_iter_break(root, memcg);
19575660048cSJohannes Weiner 			break;
19585660048cSJohannes Weiner 		}
19595660048cSJohannes Weiner 		memcg = mem_cgroup_iter(root, memcg, &reclaim);
19605660048cSJohannes Weiner 	} while (memcg);
1961f16015fbSJohannes Weiner }
1962f16015fbSJohannes Weiner 
1963fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
1964fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
1965fe4b1b24SMel Gorman {
1966fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
1967fe4b1b24SMel Gorman 	bool watermark_ok;
1968fe4b1b24SMel Gorman 
1969fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
1970fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
1971fe4b1b24SMel Gorman 		return false;
1972fe4b1b24SMel Gorman 
1973fe4b1b24SMel Gorman 	/*
1974fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
1975fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
1976fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
1977fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
1978fe4b1b24SMel Gorman 	 */
1979fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
1980fe4b1b24SMel Gorman 		(zone->present_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
1981fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
1982fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
1983fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
1984fe4b1b24SMel Gorman 
1985fe4b1b24SMel Gorman 	/*
1986fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
1987fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
1988fe4b1b24SMel Gorman 	 */
1989aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
1990fe4b1b24SMel Gorman 		return watermark_ok;
1991fe4b1b24SMel Gorman 
1992fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
1993fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
1994fe4b1b24SMel Gorman 		return false;
1995fe4b1b24SMel Gorman 
1996fe4b1b24SMel Gorman 	return watermark_ok;
1997fe4b1b24SMel Gorman }
1998fe4b1b24SMel Gorman 
19991da177e4SLinus Torvalds /*
20001da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
20011da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
20021da177e4SLinus Torvalds  * request.
20031da177e4SLinus Torvalds  *
200441858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
200541858966SMel Gorman  * Because:
20061da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
20071da177e4SLinus Torvalds  *    allocation or
200841858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
200941858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
201041858966SMel Gorman  *    zone defense algorithm.
20111da177e4SLinus Torvalds  *
20121da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
20131da177e4SLinus Torvalds  * scan then give up on it.
2014e0c23279SMel Gorman  *
2015e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2016fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
20170cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
20180cee34fdSMel Gorman  * further reclaim.
20191da177e4SLinus Torvalds  */
2020e0c23279SMel Gorman static bool shrink_zones(int priority, struct zonelist *zonelist,
202169e05944SAndrew Morton 					struct scan_control *sc)
20221da177e4SLinus Torvalds {
2023dd1a239fSMel Gorman 	struct zoneref *z;
202454a6eb5cSMel Gorman 	struct zone *zone;
2025d149e3b2SYing Han 	unsigned long nr_soft_reclaimed;
2026d149e3b2SYing Han 	unsigned long nr_soft_scanned;
20270cee34fdSMel Gorman 	bool aborted_reclaim = false;
20281cfb419bSKAMEZAWA Hiroyuki 
2029cc715d99SMel Gorman 	/*
2030cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2031cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2032cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2033cc715d99SMel Gorman 	 */
2034cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2035cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2036cc715d99SMel Gorman 
2037d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2038d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2039f3fe6512SCon Kolivas 		if (!populated_zone(zone))
20401da177e4SLinus Torvalds 			continue;
20411cfb419bSKAMEZAWA Hiroyuki 		/*
20421cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
20431cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
20441cfb419bSKAMEZAWA Hiroyuki 		 */
204589b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
204602a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
20471da177e4SLinus Torvalds 				continue;
204893e4a89aSKOSAKI Motohiro 			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
20491da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2050e0887c19SRik van Riel 			if (COMPACTION_BUILD) {
2051e0887c19SRik van Riel 				/*
2052e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2053e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2054e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2055e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2056e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2057c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2058c7cfa37bSCopot Alexandru 				 * page allocations.
2059e0887c19SRik van Riel 				 */
2060fe4b1b24SMel Gorman 				if (compaction_ready(zone, sc)) {
20610cee34fdSMel Gorman 					aborted_reclaim = true;
2062e0887c19SRik van Riel 					continue;
2063e0887c19SRik van Riel 				}
2064e0c23279SMel Gorman 			}
2065ac34a1a3SKAMEZAWA Hiroyuki 			/*
2066ac34a1a3SKAMEZAWA Hiroyuki 			 * This steals pages from memory cgroups over softlimit
2067ac34a1a3SKAMEZAWA Hiroyuki 			 * and returns the number of reclaimed pages and
2068ac34a1a3SKAMEZAWA Hiroyuki 			 * scanned pages. This works for global memory pressure
2069ac34a1a3SKAMEZAWA Hiroyuki 			 * and balancing, not for a memcg's limit.
2070ac34a1a3SKAMEZAWA Hiroyuki 			 */
2071d149e3b2SYing Han 			nr_soft_scanned = 0;
2072d149e3b2SYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2073d149e3b2SYing Han 						sc->order, sc->gfp_mask,
2074d149e3b2SYing Han 						&nr_soft_scanned);
2075d149e3b2SYing Han 			sc->nr_reclaimed += nr_soft_reclaimed;
2076ac34a1a3SKAMEZAWA Hiroyuki 			sc->nr_scanned += nr_soft_scanned;
2077ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2078ac34a1a3SKAMEZAWA Hiroyuki 		}
2079d149e3b2SYing Han 
2080a79311c1SRik van Riel 		shrink_zone(priority, zone, sc);
20811da177e4SLinus Torvalds 	}
2082e0c23279SMel Gorman 
20830cee34fdSMel Gorman 	return aborted_reclaim;
2084d1908362SMinchan Kim }
2085d1908362SMinchan Kim 
2086d1908362SMinchan Kim static bool zone_reclaimable(struct zone *zone)
2087d1908362SMinchan Kim {
2088d1908362SMinchan Kim 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2089d1908362SMinchan Kim }
2090d1908362SMinchan Kim 
2091929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2092d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2093d1908362SMinchan Kim 		struct scan_control *sc)
2094d1908362SMinchan Kim {
2095d1908362SMinchan Kim 	struct zoneref *z;
2096d1908362SMinchan Kim 	struct zone *zone;
2097d1908362SMinchan Kim 
2098d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2099d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2100d1908362SMinchan Kim 		if (!populated_zone(zone))
2101d1908362SMinchan Kim 			continue;
2102d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2103d1908362SMinchan Kim 			continue;
2104929bea7cSKOSAKI Motohiro 		if (!zone->all_unreclaimable)
2105929bea7cSKOSAKI Motohiro 			return false;
2106d1908362SMinchan Kim 	}
2107d1908362SMinchan Kim 
2108929bea7cSKOSAKI Motohiro 	return true;
21091da177e4SLinus Torvalds }
21101da177e4SLinus Torvalds 
21111da177e4SLinus Torvalds /*
21121da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
21131da177e4SLinus Torvalds  *
21141da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
21151da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
21161da177e4SLinus Torvalds  *
21171da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
21181da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
21195b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
21205b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
21215b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
21225b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2123a41f24eaSNishanth Aravamudan  *
2124a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2125a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
21261da177e4SLinus Torvalds  */
2127dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2128a09ed5e0SYing Han 					struct scan_control *sc,
2129a09ed5e0SYing Han 					struct shrink_control *shrink)
21301da177e4SLinus Torvalds {
21311da177e4SLinus Torvalds 	int priority;
213269e05944SAndrew Morton 	unsigned long total_scanned = 0;
21331da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
2134dd1a239fSMel Gorman 	struct zoneref *z;
213554a6eb5cSMel Gorman 	struct zone *zone;
213622fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
21370cee34fdSMel Gorman 	bool aborted_reclaim;
21381da177e4SLinus Torvalds 
2139873b4771SKeika Kobayashi 	delayacct_freepages_start();
2140873b4771SKeika Kobayashi 
214189b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2142f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
21431da177e4SLinus Torvalds 
21441da177e4SLinus Torvalds 	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
214566e1707bSBalbir Singh 		sc->nr_scanned = 0;
21460cee34fdSMel Gorman 		aborted_reclaim = shrink_zones(priority, zonelist, sc);
2147e0c23279SMel Gorman 
214866e1707bSBalbir Singh 		/*
214966e1707bSBalbir Singh 		 * Don't shrink slabs when reclaiming memory from
215066e1707bSBalbir Singh 		 * over limit cgroups
215166e1707bSBalbir Singh 		 */
215289b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2153c6a8a8c5SKOSAKI Motohiro 			unsigned long lru_pages = 0;
2154d4debc66SMel Gorman 			for_each_zone_zonelist(zone, z, zonelist,
2155d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask)) {
2156c6a8a8c5SKOSAKI Motohiro 				if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2157c6a8a8c5SKOSAKI Motohiro 					continue;
2158c6a8a8c5SKOSAKI Motohiro 
2159c6a8a8c5SKOSAKI Motohiro 				lru_pages += zone_reclaimable_pages(zone);
2160c6a8a8c5SKOSAKI Motohiro 			}
2161c6a8a8c5SKOSAKI Motohiro 
21621495f230SYing Han 			shrink_slab(shrink, sc->nr_scanned, lru_pages);
21631da177e4SLinus Torvalds 			if (reclaim_state) {
2164a79311c1SRik van Riel 				sc->nr_reclaimed += reclaim_state->reclaimed_slab;
21651da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
21661da177e4SLinus Torvalds 			}
216791a45470SKAMEZAWA Hiroyuki 		}
216866e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2169bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
21701da177e4SLinus Torvalds 			goto out;
21711da177e4SLinus Torvalds 
21721da177e4SLinus Torvalds 		/*
21731da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
21741da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
21751da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
21761da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
21771da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
21781da177e4SLinus Torvalds 		 */
217922fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
218022fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
21810e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
21820e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
218366e1707bSBalbir Singh 			sc->may_writepage = 1;
21841da177e4SLinus Torvalds 		}
21851da177e4SLinus Torvalds 
21861da177e4SLinus Torvalds 		/* Take a nap, wait for some writeback to complete */
21877b51755cSKOSAKI Motohiro 		if (!sc->hibernation_mode && sc->nr_scanned &&
21880e093d99SMel Gorman 		    priority < DEF_PRIORITY - 2) {
21890e093d99SMel Gorman 			struct zone *preferred_zone;
21900e093d99SMel Gorman 
21910e093d99SMel Gorman 			first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2192f33261d7SDavid Rientjes 						&cpuset_current_mems_allowed,
2193f33261d7SDavid Rientjes 						&preferred_zone);
21940e093d99SMel Gorman 			wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
21950e093d99SMel Gorman 		}
21961da177e4SLinus Torvalds 	}
2197bb21c7ceSKOSAKI Motohiro 
21981da177e4SLinus Torvalds out:
2199873b4771SKeika Kobayashi 	delayacct_freepages_end();
2200873b4771SKeika Kobayashi 
2201bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2202bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2203bb21c7ceSKOSAKI Motohiro 
2204929bea7cSKOSAKI Motohiro 	/*
2205929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2206929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2207929bea7cSKOSAKI Motohiro 	 * check.
2208929bea7cSKOSAKI Motohiro 	 */
2209929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2210929bea7cSKOSAKI Motohiro 		return 0;
2211929bea7cSKOSAKI Motohiro 
22120cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
22130cee34fdSMel Gorman 	if (aborted_reclaim)
22147335084dSMel Gorman 		return 1;
22157335084dSMel Gorman 
2216bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
221789b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2218bb21c7ceSKOSAKI Motohiro 		return 1;
2219bb21c7ceSKOSAKI Motohiro 
2220bb21c7ceSKOSAKI Motohiro 	return 0;
22211da177e4SLinus Torvalds }
22221da177e4SLinus Torvalds 
2223dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2224327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
222566e1707bSBalbir Singh {
222633906bc5SMel Gorman 	unsigned long nr_reclaimed;
222766e1707bSBalbir Singh 	struct scan_control sc = {
222866e1707bSBalbir Singh 		.gfp_mask = gfp_mask,
222966e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
223022fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2231a6dc60f8SJohannes Weiner 		.may_unmap = 1,
22322e2e4259SKOSAKI Motohiro 		.may_swap = 1,
223366e1707bSBalbir Singh 		.order = order,
2234f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2235327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
223666e1707bSBalbir Singh 	};
2237a09ed5e0SYing Han 	struct shrink_control shrink = {
2238a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2239a09ed5e0SYing Han 	};
224066e1707bSBalbir Singh 
224133906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
224233906bc5SMel Gorman 				sc.may_writepage,
224333906bc5SMel Gorman 				gfp_mask);
224433906bc5SMel Gorman 
2245a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
224633906bc5SMel Gorman 
224733906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
224833906bc5SMel Gorman 
224933906bc5SMel Gorman 	return nr_reclaimed;
225066e1707bSBalbir Singh }
225166e1707bSBalbir Singh 
225200f0b825SBalbir Singh #ifdef CONFIG_CGROUP_MEM_RES_CTLR
225366e1707bSBalbir Singh 
225472835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
22554e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
22560ae5e89cSYing Han 						struct zone *zone,
22570ae5e89cSYing Han 						unsigned long *nr_scanned)
22584e416953SBalbir Singh {
22594e416953SBalbir Singh 	struct scan_control sc = {
22600ae5e89cSYing Han 		.nr_scanned = 0,
2261b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
22624e416953SBalbir Singh 		.may_writepage = !laptop_mode,
22634e416953SBalbir Singh 		.may_unmap = 1,
22644e416953SBalbir Singh 		.may_swap = !noswap,
22654e416953SBalbir Singh 		.order = 0,
226672835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
22674e416953SBalbir Singh 	};
22685660048cSJohannes Weiner 	struct mem_cgroup_zone mz = {
226972835c86SJohannes Weiner 		.mem_cgroup = memcg,
22705660048cSJohannes Weiner 		.zone = zone,
22715660048cSJohannes Weiner 	};
22720ae5e89cSYing Han 
22734e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
22744e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2275bdce6d9eSKOSAKI Motohiro 
2276bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(0,
2277bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2278bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2279bdce6d9eSKOSAKI Motohiro 
22804e416953SBalbir Singh 	/*
22814e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
22824e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
22834e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
22844e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
22854e416953SBalbir Singh 	 * the priority and make it zero.
22864e416953SBalbir Singh 	 */
22875660048cSJohannes Weiner 	shrink_mem_cgroup_zone(0, &mz, &sc);
2288bdce6d9eSKOSAKI Motohiro 
2289bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2290bdce6d9eSKOSAKI Motohiro 
22910ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
22924e416953SBalbir Singh 	return sc.nr_reclaimed;
22934e416953SBalbir Singh }
22944e416953SBalbir Singh 
229572835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
22968c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2297185efc0fSJohannes Weiner 					   bool noswap)
229866e1707bSBalbir Singh {
22994e416953SBalbir Singh 	struct zonelist *zonelist;
2300bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2301889976dbSYing Han 	int nid;
230266e1707bSBalbir Singh 	struct scan_control sc = {
230366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2304a6dc60f8SJohannes Weiner 		.may_unmap = 1,
23052e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
230622fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
230766e1707bSBalbir Singh 		.order = 0,
230872835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2309327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2310a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2311a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2312a09ed5e0SYing Han 	};
2313a09ed5e0SYing Han 	struct shrink_control shrink = {
2314a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
231566e1707bSBalbir Singh 	};
231666e1707bSBalbir Singh 
2317889976dbSYing Han 	/*
2318889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2319889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2320889976dbSYing Han 	 * scan does not need to be the current node.
2321889976dbSYing Han 	 */
232272835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2323889976dbSYing Han 
2324889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2325bdce6d9eSKOSAKI Motohiro 
2326bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2327bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2328bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2329bdce6d9eSKOSAKI Motohiro 
2330a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2331bdce6d9eSKOSAKI Motohiro 
2332bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2333bdce6d9eSKOSAKI Motohiro 
2334bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
233566e1707bSBalbir Singh }
233666e1707bSBalbir Singh #endif
233766e1707bSBalbir Singh 
2338f16015fbSJohannes Weiner static void age_active_anon(struct zone *zone, struct scan_control *sc,
2339f16015fbSJohannes Weiner 			    int priority)
2340f16015fbSJohannes Weiner {
2341b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2342b95a2f2dSJohannes Weiner 
2343b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2344b95a2f2dSJohannes Weiner 		return;
2345b95a2f2dSJohannes Weiner 
2346b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2347b95a2f2dSJohannes Weiner 	do {
2348f16015fbSJohannes Weiner 		struct mem_cgroup_zone mz = {
2349b95a2f2dSJohannes Weiner 			.mem_cgroup = memcg,
2350f16015fbSJohannes Weiner 			.zone = zone,
2351f16015fbSJohannes Weiner 		};
2352f16015fbSJohannes Weiner 
2353f16015fbSJohannes Weiner 		if (inactive_anon_is_low(&mz))
2354b95a2f2dSJohannes Weiner 			shrink_active_list(SWAP_CLUSTER_MAX, &mz,
2355b95a2f2dSJohannes Weiner 					   sc, priority, 0);
2356b95a2f2dSJohannes Weiner 
2357b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2358b95a2f2dSJohannes Weiner 	} while (memcg);
2359f16015fbSJohannes Weiner }
2360f16015fbSJohannes Weiner 
23611741c877SMel Gorman /*
23621741c877SMel Gorman  * pgdat_balanced is used when checking if a node is balanced for high-order
23631741c877SMel Gorman  * allocations. Only zones that meet watermarks and are in a zone allowed
23641741c877SMel Gorman  * by the callers classzone_idx are added to balanced_pages. The total of
23651741c877SMel Gorman  * balanced pages must be at least 25% of the zones allowed by classzone_idx
23661741c877SMel Gorman  * for the node to be considered balanced. Forcing all zones to be balanced
23671741c877SMel Gorman  * for high orders can cause excessive reclaim when there are imbalanced zones.
23681741c877SMel Gorman  * The choice of 25% is due to
23691741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
23701741c877SMel Gorman  *     reasonable sized machine
23711741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
237225985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
23731741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
23741741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
23751741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
23761741c877SMel Gorman  */
23771741c877SMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, unsigned long balanced_pages,
23781741c877SMel Gorman 						int classzone_idx)
23791741c877SMel Gorman {
23801741c877SMel Gorman 	unsigned long present_pages = 0;
23811741c877SMel Gorman 	int i;
23821741c877SMel Gorman 
23831741c877SMel Gorman 	for (i = 0; i <= classzone_idx; i++)
23841741c877SMel Gorman 		present_pages += pgdat->node_zones[i].present_pages;
23851741c877SMel Gorman 
23864746efdeSShaohua Li 	/* A special case here: if zone has no page, we think it's balanced */
23874746efdeSShaohua Li 	return balanced_pages >= (present_pages >> 2);
23881741c877SMel Gorman }
23891741c877SMel Gorman 
2390f50de2d3SMel Gorman /* is kswapd sleeping prematurely? */
2391dc83edd9SMel Gorman static bool sleeping_prematurely(pg_data_t *pgdat, int order, long remaining,
2392dc83edd9SMel Gorman 					int classzone_idx)
2393f50de2d3SMel Gorman {
2394bb3ab596SKOSAKI Motohiro 	int i;
23951741c877SMel Gorman 	unsigned long balanced = 0;
23961741c877SMel Gorman 	bool all_zones_ok = true;
2397f50de2d3SMel Gorman 
2398f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2399f50de2d3SMel Gorman 	if (remaining)
2400dc83edd9SMel Gorman 		return true;
2401f50de2d3SMel Gorman 
24020abdee2bSMel Gorman 	/* Check the watermark levels */
240308951e54SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
2404bb3ab596SKOSAKI Motohiro 		struct zone *zone = pgdat->node_zones + i;
2405bb3ab596SKOSAKI Motohiro 
2406bb3ab596SKOSAKI Motohiro 		if (!populated_zone(zone))
2407bb3ab596SKOSAKI Motohiro 			continue;
2408bb3ab596SKOSAKI Motohiro 
2409355b09c4SMel Gorman 		/*
2410355b09c4SMel Gorman 		 * balance_pgdat() skips over all_unreclaimable after
2411355b09c4SMel Gorman 		 * DEF_PRIORITY. Effectively, it considers them balanced so
2412355b09c4SMel Gorman 		 * they must be considered balanced here as well if kswapd
2413355b09c4SMel Gorman 		 * is to sleep
2414355b09c4SMel Gorman 		 */
2415355b09c4SMel Gorman 		if (zone->all_unreclaimable) {
2416355b09c4SMel Gorman 			balanced += zone->present_pages;
2417de3fab39SKOSAKI Motohiro 			continue;
2418355b09c4SMel Gorman 		}
2419de3fab39SKOSAKI Motohiro 
242088f5acf8SMel Gorman 		if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone),
2421da175d06SMel Gorman 							i, 0))
24221741c877SMel Gorman 			all_zones_ok = false;
24231741c877SMel Gorman 		else
24241741c877SMel Gorman 			balanced += zone->present_pages;
2425bb3ab596SKOSAKI Motohiro 	}
2426f50de2d3SMel Gorman 
24271741c877SMel Gorman 	/*
24281741c877SMel Gorman 	 * For high-order requests, the balanced zones must contain at least
24291741c877SMel Gorman 	 * 25% of the nodes pages for kswapd to sleep. For order-0, all zones
24301741c877SMel Gorman 	 * must be balanced
24311741c877SMel Gorman 	 */
24321741c877SMel Gorman 	if (order)
2433afc7e326SJohannes Weiner 		return !pgdat_balanced(pgdat, balanced, classzone_idx);
24341741c877SMel Gorman 	else
24351741c877SMel Gorman 		return !all_zones_ok;
2436f50de2d3SMel Gorman }
2437f50de2d3SMel Gorman 
24381da177e4SLinus Torvalds /*
24391da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
244041858966SMel Gorman  * they are all at high_wmark_pages(zone).
24411da177e4SLinus Torvalds  *
24420abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
24431da177e4SLinus Torvalds  *
24441da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
24451da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
24461da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
24471da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
24481da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
24491da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
24501da177e4SLinus Torvalds  * the zone for when the problem goes away.
24511da177e4SLinus Torvalds  *
24521da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
245341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
245441858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
245541858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
245641858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
245741858966SMel Gorman  * of pages is balanced across the zones.
24581da177e4SLinus Torvalds  */
245999504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2460dc83edd9SMel Gorman 							int *classzone_idx)
24611da177e4SLinus Torvalds {
24621da177e4SLinus Torvalds 	int all_zones_ok;
24631741c877SMel Gorman 	unsigned long balanced;
24641da177e4SLinus Torvalds 	int priority;
24651da177e4SLinus Torvalds 	int i;
246699504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
246769e05944SAndrew Morton 	unsigned long total_scanned;
24681da177e4SLinus Torvalds 	struct reclaim_state *reclaim_state = current->reclaim_state;
24690ae5e89cSYing Han 	unsigned long nr_soft_reclaimed;
24700ae5e89cSYing Han 	unsigned long nr_soft_scanned;
2471179e9639SAndrew Morton 	struct scan_control sc = {
2472179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2473a6dc60f8SJohannes Weiner 		.may_unmap = 1,
24742e2e4259SKOSAKI Motohiro 		.may_swap = 1,
247522fba335SKOSAKI Motohiro 		/*
247622fba335SKOSAKI Motohiro 		 * kswapd doesn't want to be bailed out while reclaim. because
247722fba335SKOSAKI Motohiro 		 * we want to put equal scanning pressure on each zone.
247822fba335SKOSAKI Motohiro 		 */
247922fba335SKOSAKI Motohiro 		.nr_to_reclaim = ULONG_MAX,
24805ad333ebSAndy Whitcroft 		.order = order,
2481f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2482179e9639SAndrew Morton 	};
2483a09ed5e0SYing Han 	struct shrink_control shrink = {
2484a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
2485a09ed5e0SYing Han 	};
24861da177e4SLinus Torvalds loop_again:
24871da177e4SLinus Torvalds 	total_scanned = 0;
2488a79311c1SRik van Riel 	sc.nr_reclaimed = 0;
2489c0bbbc73SChristoph Lameter 	sc.may_writepage = !laptop_mode;
2490f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
24911da177e4SLinus Torvalds 
24921da177e4SLinus Torvalds 	for (priority = DEF_PRIORITY; priority >= 0; priority--) {
24931da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
2494bb3ab596SKOSAKI Motohiro 		int has_under_min_watermark_zone = 0;
24951da177e4SLinus Torvalds 
24961da177e4SLinus Torvalds 		all_zones_ok = 1;
24971741c877SMel Gorman 		balanced = 0;
24981da177e4SLinus Torvalds 
24991da177e4SLinus Torvalds 		/*
25001da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
25011da177e4SLinus Torvalds 		 * zone which needs scanning
25021da177e4SLinus Torvalds 		 */
25031da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
25041da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
25051da177e4SLinus Torvalds 
2506f3fe6512SCon Kolivas 			if (!populated_zone(zone))
25071da177e4SLinus Torvalds 				continue;
25081da177e4SLinus Torvalds 
250993e4a89aSKOSAKI Motohiro 			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
25101da177e4SLinus Torvalds 				continue;
25111da177e4SLinus Torvalds 
2512556adecbSRik van Riel 			/*
2513556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2514556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2515556adecbSRik van Riel 			 */
2516f16015fbSJohannes Weiner 			age_active_anon(zone, &sc, priority);
2517556adecbSRik van Riel 
2518cc715d99SMel Gorman 			/*
2519cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2520cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2521cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2522cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2523cc715d99SMel Gorman 			 */
2524cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2525cc715d99SMel Gorman 				end_zone = i;
2526cc715d99SMel Gorman 				break;
2527cc715d99SMel Gorman 			}
2528cc715d99SMel Gorman 
252988f5acf8SMel Gorman 			if (!zone_watermark_ok_safe(zone, order,
253041858966SMel Gorman 					high_wmark_pages(zone), 0, 0)) {
25311da177e4SLinus Torvalds 				end_zone = i;
2532e1dbeda6SAndrew Morton 				break;
2533439423f6SShaohua Li 			} else {
2534439423f6SShaohua Li 				/* If balanced, clear the congested flag */
2535439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
25361da177e4SLinus Torvalds 			}
25371da177e4SLinus Torvalds 		}
2538e1dbeda6SAndrew Morton 		if (i < 0)
25391da177e4SLinus Torvalds 			goto out;
2540e1dbeda6SAndrew Morton 
25411da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
25421da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
25431da177e4SLinus Torvalds 
2544adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
25451da177e4SLinus Torvalds 		}
25461da177e4SLinus Torvalds 
25471da177e4SLinus Torvalds 		/*
25481da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
25491da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
25501da177e4SLinus Torvalds 		 *
25511da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
25521da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
25531da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
25541da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
25551da177e4SLinus Torvalds 		 */
25561da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
25571da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
2558fe2c2a10SRik van Riel 			int nr_slab, testorder;
25598afdceceSMel Gorman 			unsigned long balance_gap;
25601da177e4SLinus Torvalds 
2561f3fe6512SCon Kolivas 			if (!populated_zone(zone))
25621da177e4SLinus Torvalds 				continue;
25631da177e4SLinus Torvalds 
256493e4a89aSKOSAKI Motohiro 			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
25651da177e4SLinus Torvalds 				continue;
25661da177e4SLinus Torvalds 
25671da177e4SLinus Torvalds 			sc.nr_scanned = 0;
25684e416953SBalbir Singh 
25690ae5e89cSYing Han 			nr_soft_scanned = 0;
25704e416953SBalbir Singh 			/*
25714e416953SBalbir Singh 			 * Call soft limit reclaim before calling shrink_zone.
25724e416953SBalbir Singh 			 */
25730ae5e89cSYing Han 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
25740ae5e89cSYing Han 							order, sc.gfp_mask,
25750ae5e89cSYing Han 							&nr_soft_scanned);
25760ae5e89cSYing Han 			sc.nr_reclaimed += nr_soft_reclaimed;
25770ae5e89cSYing Han 			total_scanned += nr_soft_scanned;
257800918b6aSKOSAKI Motohiro 
257932a4330dSRik van Riel 			/*
25808afdceceSMel Gorman 			 * We put equal pressure on every zone, unless
25818afdceceSMel Gorman 			 * one zone has way too many pages free
25828afdceceSMel Gorman 			 * already. The "too many pages" is defined
25838afdceceSMel Gorman 			 * as the high wmark plus a "gap" where the
25848afdceceSMel Gorman 			 * gap is either the low watermark or 1%
25858afdceceSMel Gorman 			 * of the zone, whichever is smaller.
258632a4330dSRik van Riel 			 */
25878afdceceSMel Gorman 			balance_gap = min(low_wmark_pages(zone),
25888afdceceSMel Gorman 				(zone->present_pages +
25898afdceceSMel Gorman 					KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
25908afdceceSMel Gorman 				KSWAPD_ZONE_BALANCE_GAP_RATIO);
2591fe2c2a10SRik van Riel 			/*
2592fe2c2a10SRik van Riel 			 * Kswapd reclaims only single pages with compaction
2593fe2c2a10SRik van Riel 			 * enabled. Trying too hard to reclaim until contiguous
2594fe2c2a10SRik van Riel 			 * free pages have become available can hurt performance
2595fe2c2a10SRik van Riel 			 * by evicting too much useful data from memory.
2596fe2c2a10SRik van Riel 			 * Do not reclaim more than needed for compaction.
2597fe2c2a10SRik van Riel 			 */
2598fe2c2a10SRik van Riel 			testorder = order;
2599fe2c2a10SRik van Riel 			if (COMPACTION_BUILD && order &&
2600fe2c2a10SRik van Riel 					compaction_suitable(zone, order) !=
2601fe2c2a10SRik van Riel 						COMPACT_SKIPPED)
2602fe2c2a10SRik van Riel 				testorder = 0;
2603fe2c2a10SRik van Riel 
2604cc715d99SMel Gorman 			if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
2605643ac9fcSHugh Dickins 				    !zone_watermark_ok_safe(zone, testorder,
26068afdceceSMel Gorman 					high_wmark_pages(zone) + balance_gap,
2607d7868daeSMel Gorman 					end_zone, 0)) {
2608a79311c1SRik van Riel 				shrink_zone(priority, zone, &sc);
2609d7868daeSMel Gorman 
26101da177e4SLinus Torvalds 				reclaim_state->reclaimed_slab = 0;
26111495f230SYing Han 				nr_slab = shrink_slab(&shrink, sc.nr_scanned, lru_pages);
2612a79311c1SRik van Riel 				sc.nr_reclaimed += reclaim_state->reclaimed_slab;
26131da177e4SLinus Torvalds 				total_scanned += sc.nr_scanned;
26145a03b051SAndrea Arcangeli 
2615d7868daeSMel Gorman 				if (nr_slab == 0 && !zone_reclaimable(zone))
261693e4a89aSKOSAKI Motohiro 					zone->all_unreclaimable = 1;
2617d7868daeSMel Gorman 			}
2618d7868daeSMel Gorman 
26191da177e4SLinus Torvalds 			/*
26201da177e4SLinus Torvalds 			 * If we've done a decent amount of scanning and
26211da177e4SLinus Torvalds 			 * the reclaim ratio is low, start doing writepage
26221da177e4SLinus Torvalds 			 * even in laptop mode
26231da177e4SLinus Torvalds 			 */
26241da177e4SLinus Torvalds 			if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
2625a79311c1SRik van Riel 			    total_scanned > sc.nr_reclaimed + sc.nr_reclaimed / 2)
26261da177e4SLinus Torvalds 				sc.may_writepage = 1;
2627bb3ab596SKOSAKI Motohiro 
2628215ddd66SMel Gorman 			if (zone->all_unreclaimable) {
2629215ddd66SMel Gorman 				if (end_zone && end_zone == i)
2630215ddd66SMel Gorman 					end_zone--;
2631d7868daeSMel Gorman 				continue;
2632215ddd66SMel Gorman 			}
2633d7868daeSMel Gorman 
2634fe2c2a10SRik van Riel 			if (!zone_watermark_ok_safe(zone, testorder,
263545973d74SMinchan Kim 					high_wmark_pages(zone), end_zone, 0)) {
263645973d74SMinchan Kim 				all_zones_ok = 0;
2637bb3ab596SKOSAKI Motohiro 				/*
263845973d74SMinchan Kim 				 * We are still under min water mark.  This
263945973d74SMinchan Kim 				 * means that we have a GFP_ATOMIC allocation
264045973d74SMinchan Kim 				 * failure risk. Hurry up!
2641bb3ab596SKOSAKI Motohiro 				 */
264288f5acf8SMel Gorman 				if (!zone_watermark_ok_safe(zone, order,
264345973d74SMinchan Kim 					    min_wmark_pages(zone), end_zone, 0))
2644bb3ab596SKOSAKI Motohiro 					has_under_min_watermark_zone = 1;
26450e093d99SMel Gorman 			} else {
26460e093d99SMel Gorman 				/*
26470e093d99SMel Gorman 				 * If a zone reaches its high watermark,
26480e093d99SMel Gorman 				 * consider it to be no longer congested. It's
26490e093d99SMel Gorman 				 * possible there are dirty pages backed by
26500e093d99SMel Gorman 				 * congested BDIs but as pressure is relieved,
26510e093d99SMel Gorman 				 * spectulatively avoid congestion waits
26520e093d99SMel Gorman 				 */
26530e093d99SMel Gorman 				zone_clear_flag(zone, ZONE_CONGESTED);
2654dc83edd9SMel Gorman 				if (i <= *classzone_idx)
26551741c877SMel Gorman 					balanced += zone->present_pages;
265645973d74SMinchan Kim 			}
2657bb3ab596SKOSAKI Motohiro 
26581da177e4SLinus Torvalds 		}
2659dc83edd9SMel Gorman 		if (all_zones_ok || (order && pgdat_balanced(pgdat, balanced, *classzone_idx)))
26601da177e4SLinus Torvalds 			break;		/* kswapd: all done */
26611da177e4SLinus Torvalds 		/*
26621da177e4SLinus Torvalds 		 * OK, kswapd is getting into trouble.  Take a nap, then take
26631da177e4SLinus Torvalds 		 * another pass across the zones.
26641da177e4SLinus Torvalds 		 */
2665bb3ab596SKOSAKI Motohiro 		if (total_scanned && (priority < DEF_PRIORITY - 2)) {
2666bb3ab596SKOSAKI Motohiro 			if (has_under_min_watermark_zone)
2667bb3ab596SKOSAKI Motohiro 				count_vm_event(KSWAPD_SKIP_CONGESTION_WAIT);
2668bb3ab596SKOSAKI Motohiro 			else
26698aa7e847SJens Axboe 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2670bb3ab596SKOSAKI Motohiro 		}
26711da177e4SLinus Torvalds 
26721da177e4SLinus Torvalds 		/*
26731da177e4SLinus Torvalds 		 * We do this so kswapd doesn't build up large priorities for
26741da177e4SLinus Torvalds 		 * example when it is freeing in parallel with allocators. It
26751da177e4SLinus Torvalds 		 * matches the direct reclaim path behaviour in terms of impact
26761da177e4SLinus Torvalds 		 * on zone->*_priority.
26771da177e4SLinus Torvalds 		 */
2678a79311c1SRik van Riel 		if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
26791da177e4SLinus Torvalds 			break;
26801da177e4SLinus Torvalds 	}
26811da177e4SLinus Torvalds out:
268299504748SMel Gorman 
268399504748SMel Gorman 	/*
268499504748SMel Gorman 	 * order-0: All zones must meet high watermark for a balanced node
26851741c877SMel Gorman 	 * high-order: Balanced zones must make up at least 25% of the node
26861741c877SMel Gorman 	 *             for the node to be balanced
268799504748SMel Gorman 	 */
2688dc83edd9SMel Gorman 	if (!(all_zones_ok || (order && pgdat_balanced(pgdat, balanced, *classzone_idx)))) {
26891da177e4SLinus Torvalds 		cond_resched();
26908357376dSRafael J. Wysocki 
26918357376dSRafael J. Wysocki 		try_to_freeze();
26928357376dSRafael J. Wysocki 
269373ce02e9SKOSAKI Motohiro 		/*
269473ce02e9SKOSAKI Motohiro 		 * Fragmentation may mean that the system cannot be
269573ce02e9SKOSAKI Motohiro 		 * rebalanced for high-order allocations in all zones.
269673ce02e9SKOSAKI Motohiro 		 * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
269773ce02e9SKOSAKI Motohiro 		 * it means the zones have been fully scanned and are still
269873ce02e9SKOSAKI Motohiro 		 * not balanced. For high-order allocations, there is
269973ce02e9SKOSAKI Motohiro 		 * little point trying all over again as kswapd may
270073ce02e9SKOSAKI Motohiro 		 * infinite loop.
270173ce02e9SKOSAKI Motohiro 		 *
270273ce02e9SKOSAKI Motohiro 		 * Instead, recheck all watermarks at order-0 as they
270373ce02e9SKOSAKI Motohiro 		 * are the most important. If watermarks are ok, kswapd will go
270473ce02e9SKOSAKI Motohiro 		 * back to sleep. High-order users can still perform direct
270573ce02e9SKOSAKI Motohiro 		 * reclaim if they wish.
270673ce02e9SKOSAKI Motohiro 		 */
270773ce02e9SKOSAKI Motohiro 		if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
270873ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
270973ce02e9SKOSAKI Motohiro 
27101da177e4SLinus Torvalds 		goto loop_again;
27111da177e4SLinus Torvalds 	}
27121da177e4SLinus Torvalds 
271399504748SMel Gorman 	/*
271499504748SMel Gorman 	 * If kswapd was reclaiming at a higher order, it has the option of
271599504748SMel Gorman 	 * sleeping without all zones being balanced. Before it does, it must
271699504748SMel Gorman 	 * ensure that the watermarks for order-0 on *all* zones are met and
271799504748SMel Gorman 	 * that the congestion flags are cleared. The congestion flag must
271899504748SMel Gorman 	 * be cleared as kswapd is the only mechanism that clears the flag
271999504748SMel Gorman 	 * and it is potentially going to sleep here.
272099504748SMel Gorman 	 */
272199504748SMel Gorman 	if (order) {
27227be62de9SRik van Riel 		int zones_need_compaction = 1;
27237be62de9SRik van Riel 
272499504748SMel Gorman 		for (i = 0; i <= end_zone; i++) {
272599504748SMel Gorman 			struct zone *zone = pgdat->node_zones + i;
272699504748SMel Gorman 
272799504748SMel Gorman 			if (!populated_zone(zone))
272899504748SMel Gorman 				continue;
272999504748SMel Gorman 
273099504748SMel Gorman 			if (zone->all_unreclaimable && priority != DEF_PRIORITY)
273199504748SMel Gorman 				continue;
273299504748SMel Gorman 
2733fe2c2a10SRik van Riel 			/* Would compaction fail due to lack of free memory? */
2734496b919bSRik van Riel 			if (COMPACTION_BUILD &&
2735496b919bSRik van Riel 			    compaction_suitable(zone, order) == COMPACT_SKIPPED)
2736fe2c2a10SRik van Riel 				goto loop_again;
2737fe2c2a10SRik van Riel 
273899504748SMel Gorman 			/* Confirm the zone is balanced for order-0 */
273999504748SMel Gorman 			if (!zone_watermark_ok(zone, 0,
274099504748SMel Gorman 					high_wmark_pages(zone), 0, 0)) {
274199504748SMel Gorman 				order = sc.order = 0;
274299504748SMel Gorman 				goto loop_again;
274399504748SMel Gorman 			}
274499504748SMel Gorman 
27457be62de9SRik van Riel 			/* Check if the memory needs to be defragmented. */
27467be62de9SRik van Riel 			if (zone_watermark_ok(zone, order,
27477be62de9SRik van Riel 				    low_wmark_pages(zone), *classzone_idx, 0))
27487be62de9SRik van Riel 				zones_need_compaction = 0;
27497be62de9SRik van Riel 
275099504748SMel Gorman 			/* If balanced, clear the congested flag */
275199504748SMel Gorman 			zone_clear_flag(zone, ZONE_CONGESTED);
275299504748SMel Gorman 		}
27537be62de9SRik van Riel 
27547be62de9SRik van Riel 		if (zones_need_compaction)
27557be62de9SRik van Riel 			compact_pgdat(pgdat, order);
275699504748SMel Gorman 	}
275799504748SMel Gorman 
27580abdee2bSMel Gorman 	/*
27590abdee2bSMel Gorman 	 * Return the order we were reclaiming at so sleeping_prematurely()
27600abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
27610abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
27620abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
27630abdee2bSMel Gorman 	 */
2764dc83edd9SMel Gorman 	*classzone_idx = end_zone;
27650abdee2bSMel Gorman 	return order;
27661da177e4SLinus Torvalds }
27671da177e4SLinus Torvalds 
2768dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
2769f0bc0a60SKOSAKI Motohiro {
2770f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
2771f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
2772f0bc0a60SKOSAKI Motohiro 
2773f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
2774f0bc0a60SKOSAKI Motohiro 		return;
2775f0bc0a60SKOSAKI Motohiro 
2776f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2777f0bc0a60SKOSAKI Motohiro 
2778f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
2779dc83edd9SMel Gorman 	if (!sleeping_prematurely(pgdat, order, remaining, classzone_idx)) {
2780f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
2781f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
2782f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2783f0bc0a60SKOSAKI Motohiro 	}
2784f0bc0a60SKOSAKI Motohiro 
2785f0bc0a60SKOSAKI Motohiro 	/*
2786f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
2787f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
2788f0bc0a60SKOSAKI Motohiro 	 */
2789dc83edd9SMel Gorman 	if (!sleeping_prematurely(pgdat, order, remaining, classzone_idx)) {
2790f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
2791f0bc0a60SKOSAKI Motohiro 
2792f0bc0a60SKOSAKI Motohiro 		/*
2793f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
2794f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
2795f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
2796f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
2797f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
2798f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
2799f0bc0a60SKOSAKI Motohiro 		 */
2800f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
2801f0bc0a60SKOSAKI Motohiro 		schedule();
2802f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
2803f0bc0a60SKOSAKI Motohiro 	} else {
2804f0bc0a60SKOSAKI Motohiro 		if (remaining)
2805f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2806f0bc0a60SKOSAKI Motohiro 		else
2807f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2808f0bc0a60SKOSAKI Motohiro 	}
2809f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
2810f0bc0a60SKOSAKI Motohiro }
2811f0bc0a60SKOSAKI Motohiro 
28121da177e4SLinus Torvalds /*
28131da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
28141da177e4SLinus Torvalds  * from the init process.
28151da177e4SLinus Torvalds  *
28161da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
28171da177e4SLinus Torvalds  * free memory available even if there is no other activity
28181da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
28191da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
28201da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
28211da177e4SLinus Torvalds  *
28221da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
28231da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
28241da177e4SLinus Torvalds  */
28251da177e4SLinus Torvalds static int kswapd(void *p)
28261da177e4SLinus Torvalds {
2827215ddd66SMel Gorman 	unsigned long order, new_order;
2828d2ebd0f6SAlex,Shi 	unsigned balanced_order;
2829215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
2830d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
28311da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
28321da177e4SLinus Torvalds 	struct task_struct *tsk = current;
2833f0bc0a60SKOSAKI Motohiro 
28341da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
28351da177e4SLinus Torvalds 		.reclaimed_slab = 0,
28361da177e4SLinus Torvalds 	};
2837a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
28381da177e4SLinus Torvalds 
2839cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
2840cf40bd16SNick Piggin 
2841174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
2842c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
28431da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
28441da177e4SLinus Torvalds 
28451da177e4SLinus Torvalds 	/*
28461da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
28471da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
28481da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
28491da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
28501da177e4SLinus Torvalds 	 *
28511da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
28521da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
28531da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
28541da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
28551da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
28561da177e4SLinus Torvalds 	 */
2857930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
285883144186SRafael J. Wysocki 	set_freezable();
28591da177e4SLinus Torvalds 
2860215ddd66SMel Gorman 	order = new_order = 0;
2861d2ebd0f6SAlex,Shi 	balanced_order = 0;
2862215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
2863d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
28641da177e4SLinus Torvalds 	for ( ; ; ) {
28658fe23e05SDavid Rientjes 		int ret;
28663e1d1d28SChristoph Lameter 
2867215ddd66SMel Gorman 		/*
2868215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
2869215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
2870215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
2871215ddd66SMel Gorman 		 */
2872d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
2873d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
28741da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
287599504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
28761da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
2877215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
2878215ddd66SMel Gorman 		}
2879215ddd66SMel Gorman 
288099504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
28811da177e4SLinus Torvalds 			/*
28821da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
288399504748SMel Gorman 			 * allocation or has tigher zone constraints
28841da177e4SLinus Torvalds 			 */
28851da177e4SLinus Torvalds 			order = new_order;
288699504748SMel Gorman 			classzone_idx = new_classzone_idx;
28871da177e4SLinus Torvalds 		} else {
2888d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
2889d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
28901da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
289199504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
2892f0dfcde0SAlex,Shi 			new_order = order;
2893f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
28944d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
2895215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
28961da177e4SLinus Torvalds 		}
28971da177e4SLinus Torvalds 
28988fe23e05SDavid Rientjes 		ret = try_to_freeze();
28998fe23e05SDavid Rientjes 		if (kthread_should_stop())
29008fe23e05SDavid Rientjes 			break;
29018fe23e05SDavid Rientjes 
29028fe23e05SDavid Rientjes 		/*
29038fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
29048fe23e05SDavid Rientjes 		 * after returning from the refrigerator
2905b1296cc4SRafael J. Wysocki 		 */
290633906bc5SMel Gorman 		if (!ret) {
290733906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
2908d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
2909d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
2910d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
29111da177e4SLinus Torvalds 		}
291233906bc5SMel Gorman 	}
29131da177e4SLinus Torvalds 	return 0;
29141da177e4SLinus Torvalds }
29151da177e4SLinus Torvalds 
29161da177e4SLinus Torvalds /*
29171da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
29181da177e4SLinus Torvalds  */
291999504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
29201da177e4SLinus Torvalds {
29211da177e4SLinus Torvalds 	pg_data_t *pgdat;
29221da177e4SLinus Torvalds 
2923f3fe6512SCon Kolivas 	if (!populated_zone(zone))
29241da177e4SLinus Torvalds 		return;
29251da177e4SLinus Torvalds 
292602a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
29271da177e4SLinus Torvalds 		return;
292888f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
292999504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
293088f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
293199504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
293299504748SMel Gorman 	}
29338d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
29341da177e4SLinus Torvalds 		return;
293588f5acf8SMel Gorman 	if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
293688f5acf8SMel Gorman 		return;
293788f5acf8SMel Gorman 
293888f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
29398d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
29401da177e4SLinus Torvalds }
29411da177e4SLinus Torvalds 
2942adea02a1SWu Fengguang /*
2943adea02a1SWu Fengguang  * The reclaimable count would be mostly accurate.
2944adea02a1SWu Fengguang  * The less reclaimable pages may be
2945adea02a1SWu Fengguang  * - mlocked pages, which will be moved to unevictable list when encountered
2946adea02a1SWu Fengguang  * - mapped pages, which may require several travels to be reclaimed
2947adea02a1SWu Fengguang  * - dirty pages, which is not "instantly" reclaimable
2948adea02a1SWu Fengguang  */
2949adea02a1SWu Fengguang unsigned long global_reclaimable_pages(void)
29504f98a2feSRik van Riel {
2951adea02a1SWu Fengguang 	int nr;
2952adea02a1SWu Fengguang 
2953adea02a1SWu Fengguang 	nr = global_page_state(NR_ACTIVE_FILE) +
2954adea02a1SWu Fengguang 	     global_page_state(NR_INACTIVE_FILE);
2955adea02a1SWu Fengguang 
2956adea02a1SWu Fengguang 	if (nr_swap_pages > 0)
2957adea02a1SWu Fengguang 		nr += global_page_state(NR_ACTIVE_ANON) +
2958adea02a1SWu Fengguang 		      global_page_state(NR_INACTIVE_ANON);
2959adea02a1SWu Fengguang 
2960adea02a1SWu Fengguang 	return nr;
2961adea02a1SWu Fengguang }
2962adea02a1SWu Fengguang 
2963adea02a1SWu Fengguang unsigned long zone_reclaimable_pages(struct zone *zone)
2964adea02a1SWu Fengguang {
2965adea02a1SWu Fengguang 	int nr;
2966adea02a1SWu Fengguang 
2967adea02a1SWu Fengguang 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
2968adea02a1SWu Fengguang 	     zone_page_state(zone, NR_INACTIVE_FILE);
2969adea02a1SWu Fengguang 
2970adea02a1SWu Fengguang 	if (nr_swap_pages > 0)
2971adea02a1SWu Fengguang 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
2972adea02a1SWu Fengguang 		      zone_page_state(zone, NR_INACTIVE_ANON);
2973adea02a1SWu Fengguang 
2974adea02a1SWu Fengguang 	return nr;
29754f98a2feSRik van Riel }
29764f98a2feSRik van Riel 
2977c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
29781da177e4SLinus Torvalds /*
29797b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
2980d6277db4SRafael J. Wysocki  * freed pages.
2981d6277db4SRafael J. Wysocki  *
2982d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
2983d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
2984d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
29851da177e4SLinus Torvalds  */
29867b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
29871da177e4SLinus Torvalds {
2988d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
2989d6277db4SRafael J. Wysocki 	struct scan_control sc = {
29907b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
29917b51755cSKOSAKI Motohiro 		.may_swap = 1,
29927b51755cSKOSAKI Motohiro 		.may_unmap = 1,
2993d6277db4SRafael J. Wysocki 		.may_writepage = 1,
29947b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
29957b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
29967b51755cSKOSAKI Motohiro 		.order = 0,
29971da177e4SLinus Torvalds 	};
2998a09ed5e0SYing Han 	struct shrink_control shrink = {
2999a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3000a09ed5e0SYing Han 	};
30017b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
30027b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
30037b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
30041da177e4SLinus Torvalds 
30057b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
30067b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3007d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
30087b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3009d6277db4SRafael J. Wysocki 
3010a09ed5e0SYing Han 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3011d6277db4SRafael J. Wysocki 
30127b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
30137b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
30147b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3015d6277db4SRafael J. Wysocki 
30167b51755cSKOSAKI Motohiro 	return nr_reclaimed;
30171da177e4SLinus Torvalds }
3018c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
30191da177e4SLinus Torvalds 
30201da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
30211da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
30221da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
30231da177e4SLinus Torvalds    restore their cpu bindings. */
30249c7b216dSChandra Seetharaman static int __devinit cpu_callback(struct notifier_block *nfb,
302569e05944SAndrew Morton 				  unsigned long action, void *hcpu)
30261da177e4SLinus Torvalds {
302758c0a4a7SYasunori Goto 	int nid;
30281da177e4SLinus Torvalds 
30298bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
303058c0a4a7SYasunori Goto 		for_each_node_state(nid, N_HIGH_MEMORY) {
3031c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3032a70f7302SRusty Russell 			const struct cpumask *mask;
3033a70f7302SRusty Russell 
3034a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3035c5f59f08SMike Travis 
30363e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
30371da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3038c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
30391da177e4SLinus Torvalds 		}
30401da177e4SLinus Torvalds 	}
30411da177e4SLinus Torvalds 	return NOTIFY_OK;
30421da177e4SLinus Torvalds }
30431da177e4SLinus Torvalds 
30443218ae14SYasunori Goto /*
30453218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
30463218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
30473218ae14SYasunori Goto  */
30483218ae14SYasunori Goto int kswapd_run(int nid)
30493218ae14SYasunori Goto {
30503218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
30513218ae14SYasunori Goto 	int ret = 0;
30523218ae14SYasunori Goto 
30533218ae14SYasunori Goto 	if (pgdat->kswapd)
30543218ae14SYasunori Goto 		return 0;
30553218ae14SYasunori Goto 
30563218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
30573218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
30583218ae14SYasunori Goto 		/* failure at boot is fatal */
30593218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
30603218ae14SYasunori Goto 		printk("Failed to start kswapd on node %d\n",nid);
30613218ae14SYasunori Goto 		ret = -1;
30623218ae14SYasunori Goto 	}
30633218ae14SYasunori Goto 	return ret;
30643218ae14SYasunori Goto }
30653218ae14SYasunori Goto 
30668fe23e05SDavid Rientjes /*
30678fe23e05SDavid Rientjes  * Called by memory hotplug when all memory in a node is offlined.
30688fe23e05SDavid Rientjes  */
30698fe23e05SDavid Rientjes void kswapd_stop(int nid)
30708fe23e05SDavid Rientjes {
30718fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
30728fe23e05SDavid Rientjes 
30738fe23e05SDavid Rientjes 	if (kswapd)
30748fe23e05SDavid Rientjes 		kthread_stop(kswapd);
30758fe23e05SDavid Rientjes }
30768fe23e05SDavid Rientjes 
30771da177e4SLinus Torvalds static int __init kswapd_init(void)
30781da177e4SLinus Torvalds {
30793218ae14SYasunori Goto 	int nid;
308069e05944SAndrew Morton 
30811da177e4SLinus Torvalds 	swap_setup();
30829422ffbaSChristoph Lameter 	for_each_node_state(nid, N_HIGH_MEMORY)
30833218ae14SYasunori Goto  		kswapd_run(nid);
30841da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
30851da177e4SLinus Torvalds 	return 0;
30861da177e4SLinus Torvalds }
30871da177e4SLinus Torvalds 
30881da177e4SLinus Torvalds module_init(kswapd_init)
30899eeff239SChristoph Lameter 
30909eeff239SChristoph Lameter #ifdef CONFIG_NUMA
30919eeff239SChristoph Lameter /*
30929eeff239SChristoph Lameter  * Zone reclaim mode
30939eeff239SChristoph Lameter  *
30949eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
30959eeff239SChristoph Lameter  * the watermarks.
30969eeff239SChristoph Lameter  */
30979eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
30989eeff239SChristoph Lameter 
30991b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
31007d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
31011b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
31021b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
31031b2ffb78SChristoph Lameter 
31049eeff239SChristoph Lameter /*
3105a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3106a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3107a92f7126SChristoph Lameter  * a zone.
3108a92f7126SChristoph Lameter  */
3109a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3110a92f7126SChristoph Lameter 
31119eeff239SChristoph Lameter /*
31129614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
31139614634fSChristoph Lameter  * occur.
31149614634fSChristoph Lameter  */
31159614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
31169614634fSChristoph Lameter 
31179614634fSChristoph Lameter /*
31180ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
31190ff38490SChristoph Lameter  * slab reclaim needs to occur.
31200ff38490SChristoph Lameter  */
31210ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
31220ff38490SChristoph Lameter 
312390afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
312490afa5deSMel Gorman {
312590afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
312690afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
312790afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
312890afa5deSMel Gorman 
312990afa5deSMel Gorman 	/*
313090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
313190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
313290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
313390afa5deSMel Gorman 	 */
313490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
313590afa5deSMel Gorman }
313690afa5deSMel Gorman 
313790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
313890afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
313990afa5deSMel Gorman {
314090afa5deSMel Gorman 	long nr_pagecache_reclaimable;
314190afa5deSMel Gorman 	long delta = 0;
314290afa5deSMel Gorman 
314390afa5deSMel Gorman 	/*
314490afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
314590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
314690afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
314790afa5deSMel Gorman 	 * a better estimate
314890afa5deSMel Gorman 	 */
314990afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
315090afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
315190afa5deSMel Gorman 	else
315290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
315390afa5deSMel Gorman 
315490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
315590afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
315690afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
315790afa5deSMel Gorman 
315890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
315990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
316090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
316190afa5deSMel Gorman 
316290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
316390afa5deSMel Gorman }
316490afa5deSMel Gorman 
31650ff38490SChristoph Lameter /*
31669eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
31679eeff239SChristoph Lameter  */
3168179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
31699eeff239SChristoph Lameter {
31707fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
317169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
31729eeff239SChristoph Lameter 	struct task_struct *p = current;
31739eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
31748695949aSChristoph Lameter 	int priority;
3175179e9639SAndrew Morton 	struct scan_control sc = {
3176179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3177a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
31782e2e4259SKOSAKI Motohiro 		.may_swap = 1,
317922fba335SKOSAKI Motohiro 		.nr_to_reclaim = max_t(unsigned long, nr_pages,
318022fba335SKOSAKI Motohiro 				       SWAP_CLUSTER_MAX),
3181179e9639SAndrew Morton 		.gfp_mask = gfp_mask,
3182bd2f6199SJohannes Weiner 		.order = order,
3183179e9639SAndrew Morton 	};
3184a09ed5e0SYing Han 	struct shrink_control shrink = {
3185a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3186a09ed5e0SYing Han 	};
318715748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
31889eeff239SChristoph Lameter 
31899eeff239SChristoph Lameter 	cond_resched();
3190d4f7796eSChristoph Lameter 	/*
3191d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3192d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3193d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3194d4f7796eSChristoph Lameter 	 */
3195d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
319676ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
31979eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
31989eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3199c84db23cSChristoph Lameter 
320090afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3201a92f7126SChristoph Lameter 		/*
32020ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
32030ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3204a92f7126SChristoph Lameter 		 */
32058695949aSChristoph Lameter 		priority = ZONE_RECLAIM_PRIORITY;
3206a92f7126SChristoph Lameter 		do {
3207a79311c1SRik van Riel 			shrink_zone(priority, zone, &sc);
32088695949aSChristoph Lameter 			priority--;
3209a79311c1SRik van Riel 		} while (priority >= 0 && sc.nr_reclaimed < nr_pages);
32100ff38490SChristoph Lameter 	}
3211a92f7126SChristoph Lameter 
321215748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
321315748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
32142a16e3f4SChristoph Lameter 		/*
32157fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
32160ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
32170ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
32180ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
32190ff38490SChristoph Lameter 		 * pages.
32202a16e3f4SChristoph Lameter 		 *
32210ff38490SChristoph Lameter 		 * Note that shrink_slab will free memory on all zones and may
32220ff38490SChristoph Lameter 		 * take a long time.
32232a16e3f4SChristoph Lameter 		 */
32244dc4b3d9SKOSAKI Motohiro 		for (;;) {
32254dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
32264dc4b3d9SKOSAKI Motohiro 
32274dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
32281495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
32294dc4b3d9SKOSAKI Motohiro 				break;
32304dc4b3d9SKOSAKI Motohiro 
32314dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
32324dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
32334dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
32344dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
32354dc4b3d9SKOSAKI Motohiro 				break;
32364dc4b3d9SKOSAKI Motohiro 		}
323783e33a47SChristoph Lameter 
323883e33a47SChristoph Lameter 		/*
323983e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
324083e33a47SChristoph Lameter 		 * reclaimed from this zone.
324183e33a47SChristoph Lameter 		 */
324215748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
324315748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
324415748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
32452a16e3f4SChristoph Lameter 	}
32462a16e3f4SChristoph Lameter 
32479eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3248d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
324976ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3250a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
32519eeff239SChristoph Lameter }
3252179e9639SAndrew Morton 
3253179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3254179e9639SAndrew Morton {
3255179e9639SAndrew Morton 	int node_id;
3256d773ed6bSDavid Rientjes 	int ret;
3257179e9639SAndrew Morton 
3258179e9639SAndrew Morton 	/*
32590ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
32600ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
326134aa1330SChristoph Lameter 	 *
32629614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
32639614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
32649614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
32659614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
32669614634fSChristoph Lameter 	 * unmapped file backed pages.
3267179e9639SAndrew Morton 	 */
326890afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
326990afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3270fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3271179e9639SAndrew Morton 
327293e4a89aSKOSAKI Motohiro 	if (zone->all_unreclaimable)
3273fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3274d773ed6bSDavid Rientjes 
3275179e9639SAndrew Morton 	/*
3276d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3277179e9639SAndrew Morton 	 */
3278d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3279fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3280179e9639SAndrew Morton 
3281179e9639SAndrew Morton 	/*
3282179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3283179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3284179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3285179e9639SAndrew Morton 	 * as wide as possible.
3286179e9639SAndrew Morton 	 */
328789fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
328837c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3289fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3290d773ed6bSDavid Rientjes 
3291d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3292fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3293fa5e084eSMel Gorman 
3294d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3295d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3296d773ed6bSDavid Rientjes 
329724cf7251SMel Gorman 	if (!ret)
329824cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
329924cf7251SMel Gorman 
3300d773ed6bSDavid Rientjes 	return ret;
3301179e9639SAndrew Morton }
33029eeff239SChristoph Lameter #endif
3303894bc310SLee Schermerhorn 
3304894bc310SLee Schermerhorn /*
3305894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3306894bc310SLee Schermerhorn  * @page: the page to test
3307894bc310SLee Schermerhorn  * @vma: the VMA in which the page is or will be mapped, may be NULL
3308894bc310SLee Schermerhorn  *
3309894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
3310b291f000SNick Piggin  * lists vs unevictable list.  The vma argument is !NULL when called from the
3311b291f000SNick Piggin  * fault path to determine how to instantate a new page.
3312894bc310SLee Schermerhorn  *
3313894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3314ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3315b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3316ba9ddf49SLee Schermerhorn  *
3317894bc310SLee Schermerhorn  */
3318894bc310SLee Schermerhorn int page_evictable(struct page *page, struct vm_area_struct *vma)
3319894bc310SLee Schermerhorn {
3320894bc310SLee Schermerhorn 
3321ba9ddf49SLee Schermerhorn 	if (mapping_unevictable(page_mapping(page)))
3322ba9ddf49SLee Schermerhorn 		return 0;
3323ba9ddf49SLee Schermerhorn 
3324096a7cf4SYing Han 	if (PageMlocked(page) || (vma && mlocked_vma_newpage(vma, page)))
3325b291f000SNick Piggin 		return 0;
3326894bc310SLee Schermerhorn 
3327894bc310SLee Schermerhorn 	return 1;
3328894bc310SLee Schermerhorn }
332989e004eaSLee Schermerhorn 
333085046579SHugh Dickins #ifdef CONFIG_SHMEM
333189e004eaSLee Schermerhorn /**
333224513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
333324513264SHugh Dickins  * @pages:	array of pages to check
333424513264SHugh Dickins  * @nr_pages:	number of pages to check
333589e004eaSLee Schermerhorn  *
333624513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
333785046579SHugh Dickins  *
333885046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
333989e004eaSLee Schermerhorn  */
334024513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
334189e004eaSLee Schermerhorn {
3342925b7673SJohannes Weiner 	struct lruvec *lruvec;
334324513264SHugh Dickins 	struct zone *zone = NULL;
334424513264SHugh Dickins 	int pgscanned = 0;
334524513264SHugh Dickins 	int pgrescued = 0;
334689e004eaSLee Schermerhorn 	int i;
334789e004eaSLee Schermerhorn 
334824513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
334924513264SHugh Dickins 		struct page *page = pages[i];
335024513264SHugh Dickins 		struct zone *pagezone;
335189e004eaSLee Schermerhorn 
335224513264SHugh Dickins 		pgscanned++;
335324513264SHugh Dickins 		pagezone = page_zone(page);
335489e004eaSLee Schermerhorn 		if (pagezone != zone) {
335589e004eaSLee Schermerhorn 			if (zone)
335689e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
335789e004eaSLee Schermerhorn 			zone = pagezone;
335889e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
335989e004eaSLee Schermerhorn 		}
336089e004eaSLee Schermerhorn 
336124513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
336224513264SHugh Dickins 			continue;
336389e004eaSLee Schermerhorn 
336424513264SHugh Dickins 		if (page_evictable(page, NULL)) {
336524513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
336624513264SHugh Dickins 
336724513264SHugh Dickins 			VM_BUG_ON(PageActive(page));
336824513264SHugh Dickins 			ClearPageUnevictable(page);
336924513264SHugh Dickins 			__dec_zone_state(zone, NR_UNEVICTABLE);
337024513264SHugh Dickins 			lruvec = mem_cgroup_lru_move_lists(zone, page,
337124513264SHugh Dickins 						LRU_UNEVICTABLE, lru);
337224513264SHugh Dickins 			list_move(&page->lru, &lruvec->lists[lru]);
337324513264SHugh Dickins 			__inc_zone_state(zone, NR_INACTIVE_ANON + lru);
337424513264SHugh Dickins 			pgrescued++;
337589e004eaSLee Schermerhorn 		}
337689e004eaSLee Schermerhorn 	}
337724513264SHugh Dickins 
337824513264SHugh Dickins 	if (zone) {
337924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
338024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
338124513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
338224513264SHugh Dickins 	}
338385046579SHugh Dickins }
338485046579SHugh Dickins #endif /* CONFIG_SHMEM */
3385af936a16SLee Schermerhorn 
3386264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3387af936a16SLee Schermerhorn {
3388264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
338925bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3390264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
339125bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
339225bd91bdSKOSAKI Motohiro 		    current->comm);
3393af936a16SLee Schermerhorn }
3394af936a16SLee Schermerhorn 
3395af936a16SLee Schermerhorn /*
3396af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3397af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3398af936a16SLee Schermerhorn  */
3399af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3400af936a16SLee Schermerhorn 
3401af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
34028d65af78SAlexey Dobriyan 			   void __user *buffer,
3403af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3404af936a16SLee Schermerhorn {
3405264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
34068d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3407af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3408af936a16SLee Schermerhorn 	return 0;
3409af936a16SLee Schermerhorn }
3410af936a16SLee Schermerhorn 
3411e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3412af936a16SLee Schermerhorn /*
3413af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3414af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3415af936a16SLee Schermerhorn  */
3416af936a16SLee Schermerhorn 
341710fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
341810fbcf4cSKay Sievers 					  struct device_attribute *attr,
3419af936a16SLee Schermerhorn 					  char *buf)
3420af936a16SLee Schermerhorn {
3421264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3422af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3423af936a16SLee Schermerhorn }
3424af936a16SLee Schermerhorn 
342510fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
342610fbcf4cSKay Sievers 					   struct device_attribute *attr,
3427af936a16SLee Schermerhorn 					const char *buf, size_t count)
3428af936a16SLee Schermerhorn {
3429264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3430af936a16SLee Schermerhorn 	return 1;
3431af936a16SLee Schermerhorn }
3432af936a16SLee Schermerhorn 
3433af936a16SLee Schermerhorn 
343410fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3435af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3436af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3437af936a16SLee Schermerhorn 
3438af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3439af936a16SLee Schermerhorn {
344010fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3441af936a16SLee Schermerhorn }
3442af936a16SLee Schermerhorn 
3443af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3444af936a16SLee Schermerhorn {
344510fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3446af936a16SLee Schermerhorn }
3447e4455abbSThadeu Lima de Souza Cascardo #endif
3448