xref: /openbmc/linux/mm/vmscan.c (revision 0bf1457f0cfca7bc026a82323ad34bcf58ad035d)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/mm/vmscan.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
71da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
81da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
91da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
101da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
111da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
121da177e4SLinus Torvalds  */
131da177e4SLinus Torvalds 
141da177e4SLinus Torvalds #include <linux/mm.h>
151da177e4SLinus Torvalds #include <linux/module.h>
165a0e3ad6STejun Heo #include <linux/gfp.h>
171da177e4SLinus Torvalds #include <linux/kernel_stat.h>
181da177e4SLinus Torvalds #include <linux/swap.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/init.h>
211da177e4SLinus Torvalds #include <linux/highmem.h>
2270ddf637SAnton Vorontsov #include <linux/vmpressure.h>
23e129b5c2SAndrew Morton #include <linux/vmstat.h>
241da177e4SLinus Torvalds #include <linux/file.h>
251da177e4SLinus Torvalds #include <linux/writeback.h>
261da177e4SLinus Torvalds #include <linux/blkdev.h>
271da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
281da177e4SLinus Torvalds 					buffer_heads_over_limit */
291da177e4SLinus Torvalds #include <linux/mm_inline.h>
301da177e4SLinus Torvalds #include <linux/backing-dev.h>
311da177e4SLinus Torvalds #include <linux/rmap.h>
321da177e4SLinus Torvalds #include <linux/topology.h>
331da177e4SLinus Torvalds #include <linux/cpu.h>
341da177e4SLinus Torvalds #include <linux/cpuset.h>
353e7d3449SMel Gorman #include <linux/compaction.h>
361da177e4SLinus Torvalds #include <linux/notifier.h>
371da177e4SLinus Torvalds #include <linux/rwsem.h>
38248a0301SRafael J. Wysocki #include <linux/delay.h>
393218ae14SYasunori Goto #include <linux/kthread.h>
407dfb7103SNigel Cunningham #include <linux/freezer.h>
4166e1707bSBalbir Singh #include <linux/memcontrol.h>
42873b4771SKeika Kobayashi #include <linux/delayacct.h>
43af936a16SLee Schermerhorn #include <linux/sysctl.h>
44929bea7cSKOSAKI Motohiro #include <linux/oom.h>
45268bb0ceSLinus Torvalds #include <linux/prefetch.h>
461da177e4SLinus Torvalds 
471da177e4SLinus Torvalds #include <asm/tlbflush.h>
481da177e4SLinus Torvalds #include <asm/div64.h>
491da177e4SLinus Torvalds 
501da177e4SLinus Torvalds #include <linux/swapops.h>
51117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
521da177e4SLinus Torvalds 
530f8053a5SNick Piggin #include "internal.h"
540f8053a5SNick Piggin 
5533906bc5SMel Gorman #define CREATE_TRACE_POINTS
5633906bc5SMel Gorman #include <trace/events/vmscan.h>
5733906bc5SMel Gorman 
581da177e4SLinus Torvalds struct scan_control {
591da177e4SLinus Torvalds 	/* Incremented by the number of inactive pages that were scanned */
601da177e4SLinus Torvalds 	unsigned long nr_scanned;
611da177e4SLinus Torvalds 
62a79311c1SRik van Riel 	/* Number of pages freed so far during a call to shrink_zones() */
63a79311c1SRik van Riel 	unsigned long nr_reclaimed;
64a79311c1SRik van Riel 
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
687b51755cSKOSAKI Motohiro 	unsigned long hibernation_mode;
697b51755cSKOSAKI Motohiro 
701da177e4SLinus Torvalds 	/* This context's GFP mask */
716daa0e28SAl Viro 	gfp_t gfp_mask;
721da177e4SLinus Torvalds 
731da177e4SLinus Torvalds 	int may_writepage;
741da177e4SLinus Torvalds 
75a6dc60f8SJohannes Weiner 	/* Can mapped pages be reclaimed? */
76a6dc60f8SJohannes Weiner 	int may_unmap;
77f1fd1067SChristoph Lameter 
782e2e4259SKOSAKI Motohiro 	/* Can pages be swapped as part of reclaim? */
792e2e4259SKOSAKI Motohiro 	int may_swap;
802e2e4259SKOSAKI Motohiro 
815ad333ebSAndy Whitcroft 	int order;
8266e1707bSBalbir Singh 
839e3b2f8cSKonstantin Khlebnikov 	/* Scan (total_size >> priority) pages at once */
849e3b2f8cSKonstantin Khlebnikov 	int priority;
859e3b2f8cSKonstantin Khlebnikov 
865f53e762SKOSAKI Motohiro 	/*
87f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
88f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
89f16015fbSJohannes Weiner 	 */
90f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
9166e1707bSBalbir Singh 
92327c0e96SKAMEZAWA Hiroyuki 	/*
93327c0e96SKAMEZAWA Hiroyuki 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
94327c0e96SKAMEZAWA Hiroyuki 	 * are scanned.
95327c0e96SKAMEZAWA Hiroyuki 	 */
96327c0e96SKAMEZAWA Hiroyuki 	nodemask_t	*nodemask;
971da177e4SLinus Torvalds };
981da177e4SLinus Torvalds 
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;
133b21e0b90SZhang Yanfei unsigned 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 
138c255a458SAndrew Morton #ifdef CONFIG_MEMCG
13989b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
14089b5fae5SJohannes Weiner {
141f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
14289b5fae5SJohannes Weiner }
14391a45470SKAMEZAWA Hiroyuki #else
14489b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
14589b5fae5SJohannes Weiner {
14689b5fae5SJohannes Weiner 	return true;
14789b5fae5SJohannes Weiner }
14891a45470SKAMEZAWA Hiroyuki #endif
14991a45470SKAMEZAWA Hiroyuki 
150a1c3bfb2SJohannes Weiner static unsigned long zone_reclaimable_pages(struct zone *zone)
1516e543d57SLisa Du {
1526e543d57SLisa Du 	int nr;
1536e543d57SLisa Du 
1546e543d57SLisa Du 	nr = zone_page_state(zone, NR_ACTIVE_FILE) +
1556e543d57SLisa Du 	     zone_page_state(zone, NR_INACTIVE_FILE);
1566e543d57SLisa Du 
1576e543d57SLisa Du 	if (get_nr_swap_pages() > 0)
1586e543d57SLisa Du 		nr += zone_page_state(zone, NR_ACTIVE_ANON) +
1596e543d57SLisa Du 		      zone_page_state(zone, NR_INACTIVE_ANON);
1606e543d57SLisa Du 
1616e543d57SLisa Du 	return nr;
1626e543d57SLisa Du }
1636e543d57SLisa Du 
1646e543d57SLisa Du bool zone_reclaimable(struct zone *zone)
1656e543d57SLisa Du {
1666e543d57SLisa Du 	return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
1676e543d57SLisa Du }
1686e543d57SLisa Du 
1694d7dcca2SHugh Dickins static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
170c9f299d9SKOSAKI Motohiro {
171c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1724d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
173a3d8e054SKOSAKI Motohiro 
174074291feSKonstantin Khlebnikov 	return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
175c9f299d9SKOSAKI Motohiro }
176c9f299d9SKOSAKI Motohiro 
1771da177e4SLinus Torvalds /*
1781d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
1791da177e4SLinus Torvalds  */
1801d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
1811da177e4SLinus Torvalds {
1821d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
1831d3d4437SGlauber Costa 
1841d3d4437SGlauber Costa 	/*
1851d3d4437SGlauber Costa 	 * If we only have one possible node in the system anyway, save
1861d3d4437SGlauber Costa 	 * ourselves the trouble and disable NUMA aware behavior. This way we
1871d3d4437SGlauber Costa 	 * will save memory and some small loop time later.
1881d3d4437SGlauber Costa 	 */
1891d3d4437SGlauber Costa 	if (nr_node_ids == 1)
1901d3d4437SGlauber Costa 		shrinker->flags &= ~SHRINKER_NUMA_AWARE;
1911d3d4437SGlauber Costa 
1921d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
1931d3d4437SGlauber Costa 		size *= nr_node_ids;
1941d3d4437SGlauber Costa 
1951d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
1961d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
1971d3d4437SGlauber Costa 		return -ENOMEM;
1981d3d4437SGlauber Costa 
1991da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2001da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2011da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2021d3d4437SGlauber Costa 	return 0;
2031da177e4SLinus Torvalds }
2048e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2051da177e4SLinus Torvalds 
2061da177e4SLinus Torvalds /*
2071da177e4SLinus Torvalds  * Remove one
2081da177e4SLinus Torvalds  */
2098e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2101da177e4SLinus Torvalds {
2111da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2121da177e4SLinus Torvalds 	list_del(&shrinker->list);
2131da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
214ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2151da177e4SLinus Torvalds }
2168e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2171da177e4SLinus Torvalds 
2181da177e4SLinus Torvalds #define SHRINK_BATCH 128
2191d3d4437SGlauber Costa 
2201d3d4437SGlauber Costa static unsigned long
2211d3d4437SGlauber Costa shrink_slab_node(struct shrink_control *shrinkctl, struct shrinker *shrinker,
2221d3d4437SGlauber Costa 		 unsigned long nr_pages_scanned, unsigned long lru_pages)
2231da177e4SLinus Torvalds {
22424f7c6b9SDave Chinner 	unsigned long freed = 0;
2251da177e4SLinus Torvalds 	unsigned long long delta;
226635697c6SKonstantin Khlebnikov 	long total_scan;
227d5bc5fd3SVladimir Davydov 	long freeable;
228acf92b48SDave Chinner 	long nr;
229acf92b48SDave Chinner 	long new_nr;
2301d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
231e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
232e9299f50SDave Chinner 					  : SHRINK_BATCH;
2331da177e4SLinus Torvalds 
234d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
235d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2361d3d4437SGlauber Costa 		return 0;
237635697c6SKonstantin Khlebnikov 
238acf92b48SDave Chinner 	/*
239acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
240acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
241acf92b48SDave Chinner 	 * don't also do this scanning work.
242acf92b48SDave Chinner 	 */
2431d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
244acf92b48SDave Chinner 
245acf92b48SDave Chinner 	total_scan = nr;
2461495f230SYing Han 	delta = (4 * nr_pages_scanned) / shrinker->seeks;
247d5bc5fd3SVladimir Davydov 	delta *= freeable;
2481da177e4SLinus Torvalds 	do_div(delta, lru_pages + 1);
249acf92b48SDave Chinner 	total_scan += delta;
250acf92b48SDave Chinner 	if (total_scan < 0) {
25124f7c6b9SDave Chinner 		printk(KERN_ERR
25224f7c6b9SDave Chinner 		"shrink_slab: %pF negative objects to delete nr=%ld\n",
253a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
254d5bc5fd3SVladimir Davydov 		total_scan = freeable;
255ea164d73SAndrea Arcangeli 	}
256ea164d73SAndrea Arcangeli 
257ea164d73SAndrea Arcangeli 	/*
2583567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
2593567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
2603567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
2613567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
2623567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
263d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
2643567b59aSDave Chinner 	 * memory.
2653567b59aSDave Chinner 	 *
2663567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
2673567b59aSDave Chinner 	 * a large delta change is calculated directly.
2683567b59aSDave Chinner 	 */
269d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
270d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
2713567b59aSDave Chinner 
2723567b59aSDave Chinner 	/*
273ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
274ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
275ea164d73SAndrea Arcangeli 	 * freeable entries.
276ea164d73SAndrea Arcangeli 	 */
277d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
278d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
2791da177e4SLinus Torvalds 
28024f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
28109576073SDave Chinner 				nr_pages_scanned, lru_pages,
282d5bc5fd3SVladimir Davydov 				freeable, delta, total_scan);
28309576073SDave Chinner 
2840b1fb40aSVladimir Davydov 	/*
2850b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
2860b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
2870b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
2880b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
2890b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
2900b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
2910b1fb40aSVladimir Davydov 	 * batch_size.
2920b1fb40aSVladimir Davydov 	 *
2930b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
2940b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
295d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
2960b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
2970b1fb40aSVladimir Davydov 	 * possible.
2980b1fb40aSVladimir Davydov 	 */
2990b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
300d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
30124f7c6b9SDave Chinner 		unsigned long ret;
3020b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3031da177e4SLinus Torvalds 
3040b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
30524f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
30624f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3071da177e4SLinus Torvalds 			break;
30824f7c6b9SDave Chinner 		freed += ret;
30924f7c6b9SDave Chinner 
3100b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3110b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3121da177e4SLinus Torvalds 
3131da177e4SLinus Torvalds 		cond_resched();
3141da177e4SLinus Torvalds 	}
3151da177e4SLinus Torvalds 
316acf92b48SDave Chinner 	/*
317acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
318acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
319acf92b48SDave Chinner 	 * scan, there is no need to do an update.
320acf92b48SDave Chinner 	 */
32183aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
32283aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3231d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
32483aeeadaSKonstantin Khlebnikov 	else
3251d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
326acf92b48SDave Chinner 
32724f7c6b9SDave Chinner 	trace_mm_shrink_slab_end(shrinker, freed, nr, new_nr);
3281d3d4437SGlauber Costa 	return freed;
3291d3d4437SGlauber Costa }
3301d3d4437SGlauber Costa 
3311d3d4437SGlauber Costa /*
3321d3d4437SGlauber Costa  * Call the shrink functions to age shrinkable caches
3331d3d4437SGlauber Costa  *
3341d3d4437SGlauber Costa  * Here we assume it costs one seek to replace a lru page and that it also
3351d3d4437SGlauber Costa  * takes a seek to recreate a cache object.  With this in mind we age equal
3361d3d4437SGlauber Costa  * percentages of the lru and ageable caches.  This should balance the seeks
3371d3d4437SGlauber Costa  * generated by these structures.
3381d3d4437SGlauber Costa  *
3391d3d4437SGlauber Costa  * If the vm encountered mapped pages on the LRU it increase the pressure on
3401d3d4437SGlauber Costa  * slab to avoid swapping.
3411d3d4437SGlauber Costa  *
3421d3d4437SGlauber Costa  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
3431d3d4437SGlauber Costa  *
3441d3d4437SGlauber Costa  * `lru_pages' represents the number of on-LRU pages in all the zones which
3451d3d4437SGlauber Costa  * are eligible for the caller's allocation attempt.  It is used for balancing
3461d3d4437SGlauber Costa  * slab reclaim versus page reclaim.
3471d3d4437SGlauber Costa  *
3481d3d4437SGlauber Costa  * Returns the number of slab objects which we shrunk.
3491d3d4437SGlauber Costa  */
3501d3d4437SGlauber Costa unsigned long shrink_slab(struct shrink_control *shrinkctl,
3511d3d4437SGlauber Costa 			  unsigned long nr_pages_scanned,
3521d3d4437SGlauber Costa 			  unsigned long lru_pages)
3531d3d4437SGlauber Costa {
3541d3d4437SGlauber Costa 	struct shrinker *shrinker;
3551d3d4437SGlauber Costa 	unsigned long freed = 0;
3561d3d4437SGlauber Costa 
3571d3d4437SGlauber Costa 	if (nr_pages_scanned == 0)
3581d3d4437SGlauber Costa 		nr_pages_scanned = SWAP_CLUSTER_MAX;
3591d3d4437SGlauber Costa 
3601d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
3611d3d4437SGlauber Costa 		/*
3621d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
3631d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
3641d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
3651d3d4437SGlauber Costa 		 * time.
3661d3d4437SGlauber Costa 		 */
3671d3d4437SGlauber Costa 		freed = 1;
3681d3d4437SGlauber Costa 		goto out;
3691d3d4437SGlauber Costa 	}
3701d3d4437SGlauber Costa 
3711d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
372ec97097bSVladimir Davydov 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE)) {
373ec97097bSVladimir Davydov 			shrinkctl->nid = 0;
374ec97097bSVladimir Davydov 			freed += shrink_slab_node(shrinkctl, shrinker,
375ec97097bSVladimir Davydov 					nr_pages_scanned, lru_pages);
3761d3d4437SGlauber Costa 			continue;
377ec97097bSVladimir Davydov 		}
3781d3d4437SGlauber Costa 
379ec97097bSVladimir Davydov 		for_each_node_mask(shrinkctl->nid, shrinkctl->nodes_to_scan) {
380ec97097bSVladimir Davydov 			if (node_online(shrinkctl->nid))
3811d3d4437SGlauber Costa 				freed += shrink_slab_node(shrinkctl, shrinker,
3821d3d4437SGlauber Costa 						nr_pages_scanned, lru_pages);
3831d3d4437SGlauber Costa 
3841d3d4437SGlauber Costa 		}
3851da177e4SLinus Torvalds 	}
3861da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
387f06590bdSMinchan Kim out:
388f06590bdSMinchan Kim 	cond_resched();
38924f7c6b9SDave Chinner 	return freed;
3901da177e4SLinus Torvalds }
3911da177e4SLinus Torvalds 
3921da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
3931da177e4SLinus Torvalds {
394ceddc3a5SJohannes Weiner 	/*
395ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
396ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
397ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
398ceddc3a5SJohannes Weiner 	 */
399edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
4001da177e4SLinus Torvalds }
4011da177e4SLinus Torvalds 
4027d3579e8SKOSAKI Motohiro static int may_write_to_queue(struct backing_dev_info *bdi,
4037d3579e8SKOSAKI Motohiro 			      struct scan_control *sc)
4041da177e4SLinus Torvalds {
405930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
4061da177e4SLinus Torvalds 		return 1;
4071da177e4SLinus Torvalds 	if (!bdi_write_congested(bdi))
4081da177e4SLinus Torvalds 		return 1;
4091da177e4SLinus Torvalds 	if (bdi == current->backing_dev_info)
4101da177e4SLinus Torvalds 		return 1;
4111da177e4SLinus Torvalds 	return 0;
4121da177e4SLinus Torvalds }
4131da177e4SLinus Torvalds 
4141da177e4SLinus Torvalds /*
4151da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
4161da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
4171da177e4SLinus Torvalds  * fsync(), msync() or close().
4181da177e4SLinus Torvalds  *
4191da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
4201da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
4211da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
4221da177e4SLinus Torvalds  *
4231da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
4241da177e4SLinus Torvalds  * __GFP_FS.
4251da177e4SLinus Torvalds  */
4261da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
4271da177e4SLinus Torvalds 				struct page *page, int error)
4281da177e4SLinus Torvalds {
4297eaceaccSJens Axboe 	lock_page(page);
4303e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
4313e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
4321da177e4SLinus Torvalds 	unlock_page(page);
4331da177e4SLinus Torvalds }
4341da177e4SLinus Torvalds 
43504e62a29SChristoph Lameter /* possible outcome of pageout() */
43604e62a29SChristoph Lameter typedef enum {
43704e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
43804e62a29SChristoph Lameter 	PAGE_KEEP,
43904e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
44004e62a29SChristoph Lameter 	PAGE_ACTIVATE,
44104e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
44204e62a29SChristoph Lameter 	PAGE_SUCCESS,
44304e62a29SChristoph Lameter 	/* page is clean and locked */
44404e62a29SChristoph Lameter 	PAGE_CLEAN,
44504e62a29SChristoph Lameter } pageout_t;
44604e62a29SChristoph Lameter 
4471da177e4SLinus Torvalds /*
4481742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
4491742f19fSAndrew Morton  * Calls ->writepage().
4501da177e4SLinus Torvalds  */
451c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
4527d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
4531da177e4SLinus Torvalds {
4541da177e4SLinus Torvalds 	/*
4551da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
4561da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
4571da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
4581da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
4591da177e4SLinus Torvalds 	 * PagePrivate for that.
4601da177e4SLinus Torvalds 	 *
4616aceb53bSVincent Li 	 * If this process is currently in __generic_file_aio_write() against
4621da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
4631da177e4SLinus Torvalds 	 * will block.
4641da177e4SLinus Torvalds 	 *
4651da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
4661da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
4671da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
4681da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
4691da177e4SLinus Torvalds 	 */
4701da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
4711da177e4SLinus Torvalds 		return PAGE_KEEP;
4721da177e4SLinus Torvalds 	if (!mapping) {
4731da177e4SLinus Torvalds 		/*
4741da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
4751da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
4761da177e4SLinus Torvalds 		 */
477266cf658SDavid Howells 		if (page_has_private(page)) {
4781da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
4791da177e4SLinus Torvalds 				ClearPageDirty(page);
480d40cee24SHarvey Harrison 				printk("%s: orphaned page\n", __func__);
4811da177e4SLinus Torvalds 				return PAGE_CLEAN;
4821da177e4SLinus Torvalds 			}
4831da177e4SLinus Torvalds 		}
4841da177e4SLinus Torvalds 		return PAGE_KEEP;
4851da177e4SLinus Torvalds 	}
4861da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
4871da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
4880e093d99SMel Gorman 	if (!may_write_to_queue(mapping->backing_dev_info, sc))
4891da177e4SLinus Torvalds 		return PAGE_KEEP;
4901da177e4SLinus Torvalds 
4911da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
4921da177e4SLinus Torvalds 		int res;
4931da177e4SLinus Torvalds 		struct writeback_control wbc = {
4941da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
4951da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
496111ebb6eSOGAWA Hirofumi 			.range_start = 0,
497111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
4981da177e4SLinus Torvalds 			.for_reclaim = 1,
4991da177e4SLinus Torvalds 		};
5001da177e4SLinus Torvalds 
5011da177e4SLinus Torvalds 		SetPageReclaim(page);
5021da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
5031da177e4SLinus Torvalds 		if (res < 0)
5041da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
505994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
5061da177e4SLinus Torvalds 			ClearPageReclaim(page);
5071da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
5081da177e4SLinus Torvalds 		}
509c661b078SAndy Whitcroft 
5101da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
5111da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
5121da177e4SLinus Torvalds 			ClearPageReclaim(page);
5131da177e4SLinus Torvalds 		}
51423b9da55SMel Gorman 		trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
515e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
5161da177e4SLinus Torvalds 		return PAGE_SUCCESS;
5171da177e4SLinus Torvalds 	}
5181da177e4SLinus Torvalds 
5191da177e4SLinus Torvalds 	return PAGE_CLEAN;
5201da177e4SLinus Torvalds }
5211da177e4SLinus Torvalds 
522a649fd92SAndrew Morton /*
523e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
524e286781dSNick Piggin  * gets returned with a refcount of 0.
525a649fd92SAndrew Morton  */
526a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
527a528910eSJohannes Weiner 			    bool reclaimed)
52849d2e9ccSChristoph Lameter {
52928e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
53028e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
53149d2e9ccSChristoph Lameter 
53219fd6231SNick Piggin 	spin_lock_irq(&mapping->tree_lock);
53349d2e9ccSChristoph Lameter 	/*
5340fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
5350fd0e6b0SNick Piggin 	 *
5360fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
5370fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
5380fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
5390fd0e6b0SNick Piggin 	 * here, then the following race may occur:
5400fd0e6b0SNick Piggin 	 *
5410fd0e6b0SNick Piggin 	 * get_user_pages(&page);
5420fd0e6b0SNick Piggin 	 * [user mapping goes away]
5430fd0e6b0SNick Piggin 	 * write_to(page);
5440fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
5450fd0e6b0SNick Piggin 	 * SetPageDirty(page);
5460fd0e6b0SNick Piggin 	 * put_page(page);
5470fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
5480fd0e6b0SNick Piggin 	 *
5490fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
5500fd0e6b0SNick Piggin 	 *
5510fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
5520fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
5530fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
5540fd0e6b0SNick Piggin 	 *
5550fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
5560fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
55749d2e9ccSChristoph Lameter 	 */
558e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
55949d2e9ccSChristoph Lameter 		goto cannot_free;
560e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
561e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
562e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
56349d2e9ccSChristoph Lameter 		goto cannot_free;
564e286781dSNick Piggin 	}
56549d2e9ccSChristoph Lameter 
56649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
56749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
56849d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
56919fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
570cb4b86baSKAMEZAWA Hiroyuki 		swapcache_free(swap, page);
571e286781dSNick Piggin 	} else {
5726072d13cSLinus Torvalds 		void (*freepage)(struct page *);
573a528910eSJohannes Weiner 		void *shadow = NULL;
5746072d13cSLinus Torvalds 
5756072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
576a528910eSJohannes Weiner 		/*
577a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
578a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
579a528910eSJohannes Weiner 		 *
580a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
581a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
582a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
583a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
584a528910eSJohannes Weiner 		 * back.
585a528910eSJohannes Weiner 		 */
586a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
587a528910eSJohannes Weiner 		    !mapping_exiting(mapping))
588a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
589a528910eSJohannes Weiner 		__delete_from_page_cache(page, shadow);
59019fd6231SNick Piggin 		spin_unlock_irq(&mapping->tree_lock);
591e767e056SDaisuke Nishimura 		mem_cgroup_uncharge_cache_page(page);
5926072d13cSLinus Torvalds 
5936072d13cSLinus Torvalds 		if (freepage != NULL)
5946072d13cSLinus Torvalds 			freepage(page);
595e286781dSNick Piggin 	}
596e286781dSNick Piggin 
59749d2e9ccSChristoph Lameter 	return 1;
59849d2e9ccSChristoph Lameter 
59949d2e9ccSChristoph Lameter cannot_free:
60019fd6231SNick Piggin 	spin_unlock_irq(&mapping->tree_lock);
60149d2e9ccSChristoph Lameter 	return 0;
60249d2e9ccSChristoph Lameter }
60349d2e9ccSChristoph Lameter 
6041da177e4SLinus Torvalds /*
605e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
606e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
607e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
608e286781dSNick Piggin  * this page.
609e286781dSNick Piggin  */
610e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
611e286781dSNick Piggin {
612a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
613e286781dSNick Piggin 		/*
614e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
615e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
616e286781dSNick Piggin 		 * atomic operation.
617e286781dSNick Piggin 		 */
618e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
619e286781dSNick Piggin 		return 1;
620e286781dSNick Piggin 	}
621e286781dSNick Piggin 	return 0;
622e286781dSNick Piggin }
623e286781dSNick Piggin 
624894bc310SLee Schermerhorn /**
625894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
626894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
627894bc310SLee Schermerhorn  *
628894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
629894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
630894bc310SLee Schermerhorn  *
631894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
632894bc310SLee Schermerhorn  */
633894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
634894bc310SLee Schermerhorn {
6350ec3b74cSVlastimil Babka 	bool is_unevictable;
636bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
637894bc310SLee Schermerhorn 
638309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
639894bc310SLee Schermerhorn 
640894bc310SLee Schermerhorn redo:
641894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
642894bc310SLee Schermerhorn 
64339b5f29aSHugh Dickins 	if (page_evictable(page)) {
644894bc310SLee Schermerhorn 		/*
645894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
646894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
647894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
648894bc310SLee Schermerhorn 		 * We know how to handle that.
649894bc310SLee Schermerhorn 		 */
6500ec3b74cSVlastimil Babka 		is_unevictable = false;
651c53954a0SMel Gorman 		lru_cache_add(page);
652894bc310SLee Schermerhorn 	} else {
653894bc310SLee Schermerhorn 		/*
654894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
655894bc310SLee Schermerhorn 		 * list.
656894bc310SLee Schermerhorn 		 */
6570ec3b74cSVlastimil Babka 		is_unevictable = true;
658894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
6596a7b9548SJohannes Weiner 		/*
66021ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
66121ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
66221ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
66324513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
66421ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
6656a7b9548SJohannes Weiner 		 * the page back to the evictable list.
6666a7b9548SJohannes Weiner 		 *
66721ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
6686a7b9548SJohannes Weiner 		 */
6696a7b9548SJohannes Weiner 		smp_mb();
670894bc310SLee Schermerhorn 	}
671894bc310SLee Schermerhorn 
672894bc310SLee Schermerhorn 	/*
673894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
674894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
675894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
676894bc310SLee Schermerhorn 	 */
6770ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
678894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
679894bc310SLee Schermerhorn 			put_page(page);
680894bc310SLee Schermerhorn 			goto redo;
681894bc310SLee Schermerhorn 		}
682894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
683894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
684894bc310SLee Schermerhorn 		 * nothing to do here.
685894bc310SLee Schermerhorn 		 */
686894bc310SLee Schermerhorn 	}
687894bc310SLee Schermerhorn 
6880ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
689bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
6900ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
691bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
692bbfd28eeSLee Schermerhorn 
693894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
694894bc310SLee Schermerhorn }
695894bc310SLee Schermerhorn 
696dfc8d636SJohannes Weiner enum page_references {
697dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
698dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
69964574746SJohannes Weiner 	PAGEREF_KEEP,
700dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
701dfc8d636SJohannes Weiner };
702dfc8d636SJohannes Weiner 
703dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
704dfc8d636SJohannes Weiner 						  struct scan_control *sc)
705dfc8d636SJohannes Weiner {
70664574746SJohannes Weiner 	int referenced_ptes, referenced_page;
707dfc8d636SJohannes Weiner 	unsigned long vm_flags;
708dfc8d636SJohannes Weiner 
709c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
710c3ac9a8aSJohannes Weiner 					  &vm_flags);
71164574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
712dfc8d636SJohannes Weiner 
713dfc8d636SJohannes Weiner 	/*
714dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
715dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
716dfc8d636SJohannes Weiner 	 */
717dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
718dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
719dfc8d636SJohannes Weiner 
72064574746SJohannes Weiner 	if (referenced_ptes) {
721e4898273SMichal Hocko 		if (PageSwapBacked(page))
72264574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
72364574746SJohannes Weiner 		/*
72464574746SJohannes Weiner 		 * All mapped pages start out with page table
72564574746SJohannes Weiner 		 * references from the instantiating fault, so we need
72664574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
72764574746SJohannes Weiner 		 * than once.
72864574746SJohannes Weiner 		 *
72964574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
73064574746SJohannes Weiner 		 * inactive list.  Another page table reference will
73164574746SJohannes Weiner 		 * lead to its activation.
73264574746SJohannes Weiner 		 *
73364574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
73464574746SJohannes Weiner 		 * so that recently deactivated but used pages are
73564574746SJohannes Weiner 		 * quickly recovered.
73664574746SJohannes Weiner 		 */
73764574746SJohannes Weiner 		SetPageReferenced(page);
73864574746SJohannes Weiner 
73934dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
740dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
741dfc8d636SJohannes Weiner 
742c909e993SKonstantin Khlebnikov 		/*
743c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
744c909e993SKonstantin Khlebnikov 		 */
745c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
746c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
747c909e993SKonstantin Khlebnikov 
74864574746SJohannes Weiner 		return PAGEREF_KEEP;
74964574746SJohannes Weiner 	}
75064574746SJohannes Weiner 
751dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
7522e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
753dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
75464574746SJohannes Weiner 
75564574746SJohannes Weiner 	return PAGEREF_RECLAIM;
756dfc8d636SJohannes Weiner }
757dfc8d636SJohannes Weiner 
758e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
759e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
760e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
761e2be15f6SMel Gorman {
762b4597226SMel Gorman 	struct address_space *mapping;
763b4597226SMel Gorman 
764e2be15f6SMel Gorman 	/*
765e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
766e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
767e2be15f6SMel Gorman 	 */
768e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
769e2be15f6SMel Gorman 		*dirty = false;
770e2be15f6SMel Gorman 		*writeback = false;
771e2be15f6SMel Gorman 		return;
772e2be15f6SMel Gorman 	}
773e2be15f6SMel Gorman 
774e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
775e2be15f6SMel Gorman 	*dirty = PageDirty(page);
776e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
777b4597226SMel Gorman 
778b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
779b4597226SMel Gorman 	if (!page_has_private(page))
780b4597226SMel Gorman 		return;
781b4597226SMel Gorman 
782b4597226SMel Gorman 	mapping = page_mapping(page);
783b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
784b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
785e2be15f6SMel Gorman }
786e2be15f6SMel Gorman 
787e286781dSNick Piggin /*
7881742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
7891da177e4SLinus Torvalds  */
7901742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
7916a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
792f84f6e2bSMel Gorman 				      struct scan_control *sc,
79302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
7948e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
795d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
7968e950282SMel Gorman 				      unsigned long *ret_nr_congested,
79702c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
798b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
79902c6de8dSMinchan Kim 				      bool force_reclaim)
8001da177e4SLinus Torvalds {
8011da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
802abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
8031da177e4SLinus Torvalds 	int pgactivate = 0;
804d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
8050e093d99SMel Gorman 	unsigned long nr_dirty = 0;
8060e093d99SMel Gorman 	unsigned long nr_congested = 0;
80705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
80892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
809b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
8101da177e4SLinus Torvalds 
8111da177e4SLinus Torvalds 	cond_resched();
8121da177e4SLinus Torvalds 
81369980e31STim Chen 	mem_cgroup_uncharge_start();
8141da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
8151da177e4SLinus Torvalds 		struct address_space *mapping;
8161da177e4SLinus Torvalds 		struct page *page;
8171da177e4SLinus Torvalds 		int may_enter_fs;
81802c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
819e2be15f6SMel Gorman 		bool dirty, writeback;
8201da177e4SLinus Torvalds 
8211da177e4SLinus Torvalds 		cond_resched();
8221da177e4SLinus Torvalds 
8231da177e4SLinus Torvalds 		page = lru_to_page(page_list);
8241da177e4SLinus Torvalds 		list_del(&page->lru);
8251da177e4SLinus Torvalds 
826529ae9aaSNick Piggin 		if (!trylock_page(page))
8271da177e4SLinus Torvalds 			goto keep;
8281da177e4SLinus Torvalds 
829309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
830309381feSSasha Levin 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
8311da177e4SLinus Torvalds 
8321da177e4SLinus Torvalds 		sc->nr_scanned++;
83380e43426SChristoph Lameter 
83439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
835b291f000SNick Piggin 			goto cull_mlocked;
836894bc310SLee Schermerhorn 
837a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
83880e43426SChristoph Lameter 			goto keep_locked;
83980e43426SChristoph Lameter 
8401da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
8411da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
8421da177e4SLinus Torvalds 			sc->nr_scanned++;
8431da177e4SLinus Torvalds 
844c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
845c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
846c661b078SAndy Whitcroft 
847e62e384eSMichal Hocko 		/*
848e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
849e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
850e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
851e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
852e2be15f6SMel Gorman 		 */
853e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
854e2be15f6SMel Gorman 		if (dirty || writeback)
855e2be15f6SMel Gorman 			nr_dirty++;
856e2be15f6SMel Gorman 
857e2be15f6SMel Gorman 		if (dirty && !writeback)
858e2be15f6SMel Gorman 			nr_unqueued_dirty++;
859e2be15f6SMel Gorman 
860d04e8acdSMel Gorman 		/*
861d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
862d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
863d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
864d04e8acdSMel Gorman 		 * end of the LRU a second time.
865d04e8acdSMel Gorman 		 */
866e2be15f6SMel Gorman 		mapping = page_mapping(page);
867d04e8acdSMel Gorman 		if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
868d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
869e2be15f6SMel Gorman 			nr_congested++;
870e2be15f6SMel Gorman 
871e2be15f6SMel Gorman 		/*
872283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
873283aba9fSMel Gorman 		 * are three cases to consider.
874e62e384eSMichal Hocko 		 *
875283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
876283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
877283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
878283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
879283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
880283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
881283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
882b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
883b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
884c3b94f44SHugh Dickins 		 *
885283aba9fSMel Gorman 		 * 2) Global reclaim encounters a page, memcg encounters a
886283aba9fSMel Gorman 		 *    page that is not marked for immediate reclaim or
887283aba9fSMel Gorman 		 *    the caller does not have __GFP_IO. In this case mark
888283aba9fSMel Gorman 		 *    the page for immediate reclaim and continue scanning.
889283aba9fSMel Gorman 		 *
890283aba9fSMel Gorman 		 *    __GFP_IO is checked  because a loop driver thread might
891283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
892283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
893283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
894283aba9fSMel Gorman 		 *    would probably show more reasons.
895283aba9fSMel Gorman 		 *
896283aba9fSMel Gorman 		 *    Don't require __GFP_FS, since we're not going into the
897283aba9fSMel Gorman 		 *    FS, just waiting on its writeback completion. Worryingly,
898283aba9fSMel Gorman 		 *    ext4 gfs2 and xfs allocate pages with
899283aba9fSMel Gorman 		 *    grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
900283aba9fSMel Gorman 		 *    may_enter_fs here is liable to OOM on them.
901283aba9fSMel Gorman 		 *
902283aba9fSMel Gorman 		 * 3) memcg encounters a page that is not already marked
903283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
904283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
905283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
906283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
907e62e384eSMichal Hocko 		 */
908283aba9fSMel Gorman 		if (PageWriteback(page)) {
909283aba9fSMel Gorman 			/* Case 1 above */
910283aba9fSMel Gorman 			if (current_is_kswapd() &&
911283aba9fSMel Gorman 			    PageReclaim(page) &&
912283aba9fSMel Gorman 			    zone_is_reclaim_writeback(zone)) {
913b1a6f21eSMel Gorman 				nr_immediate++;
914b1a6f21eSMel Gorman 				goto keep_locked;
915283aba9fSMel Gorman 
916283aba9fSMel Gorman 			/* Case 2 above */
917283aba9fSMel Gorman 			} else if (global_reclaim(sc) ||
918c3b94f44SHugh Dickins 			    !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
919c3b94f44SHugh Dickins 				/*
920c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
921c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
922c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
923c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
924c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
925c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
926c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
927c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
928c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
929c3b94f44SHugh Dickins 				 */
930c3b94f44SHugh Dickins 				SetPageReclaim(page);
93192df3a72SMel Gorman 				nr_writeback++;
932283aba9fSMel Gorman 
933c3b94f44SHugh Dickins 				goto keep_locked;
934283aba9fSMel Gorman 
935283aba9fSMel Gorman 			/* Case 3 above */
936283aba9fSMel Gorman 			} else {
937c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
938e62e384eSMichal Hocko 			}
939283aba9fSMel Gorman 		}
9401da177e4SLinus Torvalds 
94102c6de8dSMinchan Kim 		if (!force_reclaim)
9426a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
94302c6de8dSMinchan Kim 
944dfc8d636SJohannes Weiner 		switch (references) {
945dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
9461da177e4SLinus Torvalds 			goto activate_locked;
94764574746SJohannes Weiner 		case PAGEREF_KEEP:
94864574746SJohannes Weiner 			goto keep_locked;
949dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
950dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
951dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
952dfc8d636SJohannes Weiner 		}
9531da177e4SLinus Torvalds 
9541da177e4SLinus Torvalds 		/*
9551da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
9561da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
9571da177e4SLinus Torvalds 		 */
958b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
95963eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
96063eb6b93SHugh Dickins 				goto keep_locked;
9615bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
9621da177e4SLinus Torvalds 				goto activate_locked;
96363eb6b93SHugh Dickins 			may_enter_fs = 1;
9641da177e4SLinus Torvalds 
965e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
9661da177e4SLinus Torvalds 			mapping = page_mapping(page);
967e2be15f6SMel Gorman 		}
9681da177e4SLinus Torvalds 
9691da177e4SLinus Torvalds 		/*
9701da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
9711da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
9721da177e4SLinus Torvalds 		 */
9731da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
97402c6de8dSMinchan Kim 			switch (try_to_unmap(page, ttu_flags)) {
9751da177e4SLinus Torvalds 			case SWAP_FAIL:
9761da177e4SLinus Torvalds 				goto activate_locked;
9771da177e4SLinus Torvalds 			case SWAP_AGAIN:
9781da177e4SLinus Torvalds 				goto keep_locked;
979b291f000SNick Piggin 			case SWAP_MLOCK:
980b291f000SNick Piggin 				goto cull_mlocked;
9811da177e4SLinus Torvalds 			case SWAP_SUCCESS:
9821da177e4SLinus Torvalds 				; /* try to free the page below */
9831da177e4SLinus Torvalds 			}
9841da177e4SLinus Torvalds 		}
9851da177e4SLinus Torvalds 
9861da177e4SLinus Torvalds 		if (PageDirty(page)) {
987ee72886dSMel Gorman 			/*
988ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
989d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
990d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
991ee72886dSMel Gorman 			 */
992f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
9939e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
994d43006d5SMel Gorman 					 !zone_is_reclaim_dirty(zone))) {
99549ea7eb6SMel Gorman 				/*
99649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
99749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
99849ea7eb6SMel Gorman 				 * except we already have the page isolated
99949ea7eb6SMel Gorman 				 * and know it's dirty
100049ea7eb6SMel Gorman 				 */
100149ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
100249ea7eb6SMel Gorman 				SetPageReclaim(page);
100349ea7eb6SMel Gorman 
1004ee72886dSMel Gorman 				goto keep_locked;
1005ee72886dSMel Gorman 			}
1006ee72886dSMel Gorman 
1007dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
10081da177e4SLinus Torvalds 				goto keep_locked;
10094dd4b920SAndrew Morton 			if (!may_enter_fs)
10101da177e4SLinus Torvalds 				goto keep_locked;
101152a8363eSChristoph Lameter 			if (!sc->may_writepage)
10121da177e4SLinus Torvalds 				goto keep_locked;
10131da177e4SLinus Torvalds 
10141da177e4SLinus Torvalds 			/* Page is dirty, try to write it out here */
10157d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
10161da177e4SLinus Torvalds 			case PAGE_KEEP:
10171da177e4SLinus Torvalds 				goto keep_locked;
10181da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
10191da177e4SLinus Torvalds 				goto activate_locked;
10201da177e4SLinus Torvalds 			case PAGE_SUCCESS:
10217d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
102241ac1999SMel Gorman 					goto keep;
10237d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
10241da177e4SLinus Torvalds 					goto keep;
10257d3579e8SKOSAKI Motohiro 
10261da177e4SLinus Torvalds 				/*
10271da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
10281da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
10291da177e4SLinus Torvalds 				 */
1030529ae9aaSNick Piggin 				if (!trylock_page(page))
10311da177e4SLinus Torvalds 					goto keep;
10321da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
10331da177e4SLinus Torvalds 					goto keep_locked;
10341da177e4SLinus Torvalds 				mapping = page_mapping(page);
10351da177e4SLinus Torvalds 			case PAGE_CLEAN:
10361da177e4SLinus Torvalds 				; /* try to free the page below */
10371da177e4SLinus Torvalds 			}
10381da177e4SLinus Torvalds 		}
10391da177e4SLinus Torvalds 
10401da177e4SLinus Torvalds 		/*
10411da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
10421da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
10431da177e4SLinus Torvalds 		 * the page as well.
10441da177e4SLinus Torvalds 		 *
10451da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
10461da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
10471da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
10481da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
10491da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
10501da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
10511da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
10521da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
10531da177e4SLinus Torvalds 		 *
10541da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
10551da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
10561da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
10571da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
10581da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
10591da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
10601da177e4SLinus Torvalds 		 */
1061266cf658SDavid Howells 		if (page_has_private(page)) {
10621da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
10631da177e4SLinus Torvalds 				goto activate_locked;
1064e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1065e286781dSNick Piggin 				unlock_page(page);
1066e286781dSNick Piggin 				if (put_page_testzero(page))
10671da177e4SLinus Torvalds 					goto free_it;
1068e286781dSNick Piggin 				else {
1069e286781dSNick Piggin 					/*
1070e286781dSNick Piggin 					 * rare race with speculative reference.
1071e286781dSNick Piggin 					 * the speculative reference will free
1072e286781dSNick Piggin 					 * this page shortly, so we may
1073e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1074e286781dSNick Piggin 					 * leave it off the LRU).
1075e286781dSNick Piggin 					 */
1076e286781dSNick Piggin 					nr_reclaimed++;
1077e286781dSNick Piggin 					continue;
1078e286781dSNick Piggin 				}
1079e286781dSNick Piggin 			}
10801da177e4SLinus Torvalds 		}
10811da177e4SLinus Torvalds 
1082a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
108349d2e9ccSChristoph Lameter 			goto keep_locked;
10841da177e4SLinus Torvalds 
1085a978d6f5SNick Piggin 		/*
1086a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1087a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1088a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1089a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1090a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1091a978d6f5SNick Piggin 		 */
1092a978d6f5SNick Piggin 		__clear_page_locked(page);
1093e286781dSNick Piggin free_it:
109405ff5137SAndrew Morton 		nr_reclaimed++;
1095abe4c3b5SMel Gorman 
1096abe4c3b5SMel Gorman 		/*
1097abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1098abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1099abe4c3b5SMel Gorman 		 */
1100abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
11011da177e4SLinus Torvalds 		continue;
11021da177e4SLinus Torvalds 
1103b291f000SNick Piggin cull_mlocked:
110463d6c5adSHugh Dickins 		if (PageSwapCache(page))
110563d6c5adSHugh Dickins 			try_to_free_swap(page);
1106b291f000SNick Piggin 		unlock_page(page);
1107b291f000SNick Piggin 		putback_lru_page(page);
1108b291f000SNick Piggin 		continue;
1109b291f000SNick Piggin 
11101da177e4SLinus Torvalds activate_locked:
111168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
111268a22394SRik van Riel 		if (PageSwapCache(page) && vm_swap_full())
1113a2c43eedSHugh Dickins 			try_to_free_swap(page);
1114309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11151da177e4SLinus Torvalds 		SetPageActive(page);
11161da177e4SLinus Torvalds 		pgactivate++;
11171da177e4SLinus Torvalds keep_locked:
11181da177e4SLinus Torvalds 		unlock_page(page);
11191da177e4SLinus Torvalds keep:
11201da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1121309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
11221da177e4SLinus Torvalds 	}
1123abe4c3b5SMel Gorman 
1124cc59850eSKonstantin Khlebnikov 	free_hot_cold_page_list(&free_pages, 1);
1125abe4c3b5SMel Gorman 
11261da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1127f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
112869980e31STim Chen 	mem_cgroup_uncharge_end();
11298e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
11308e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1131d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
113292df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1133b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
113405ff5137SAndrew Morton 	return nr_reclaimed;
11351da177e4SLinus Torvalds }
11361da177e4SLinus Torvalds 
113702c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
113802c6de8dSMinchan Kim 					    struct list_head *page_list)
113902c6de8dSMinchan Kim {
114002c6de8dSMinchan Kim 	struct scan_control sc = {
114102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
114202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
114302c6de8dSMinchan Kim 		.may_unmap = 1,
114402c6de8dSMinchan Kim 	};
11458e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
114602c6de8dSMinchan Kim 	struct page *page, *next;
114702c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
114802c6de8dSMinchan Kim 
114902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1150117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1151117aad1eSRafael Aquini 		    !isolated_balloon_page(page)) {
115202c6de8dSMinchan Kim 			ClearPageActive(page);
115302c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
115402c6de8dSMinchan Kim 		}
115502c6de8dSMinchan Kim 	}
115602c6de8dSMinchan Kim 
115702c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
115802c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
11598e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
116002c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
116102c6de8dSMinchan Kim 	__mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
116202c6de8dSMinchan Kim 	return ret;
116302c6de8dSMinchan Kim }
116402c6de8dSMinchan Kim 
11655ad333ebSAndy Whitcroft /*
11665ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
11675ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
11685ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
11695ad333ebSAndy Whitcroft  *
11705ad333ebSAndy Whitcroft  * page:	page to consider
11715ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
11725ad333ebSAndy Whitcroft  *
11735ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
11745ad333ebSAndy Whitcroft  */
1175f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
11765ad333ebSAndy Whitcroft {
11775ad333ebSAndy Whitcroft 	int ret = -EINVAL;
11785ad333ebSAndy Whitcroft 
11795ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
11805ad333ebSAndy Whitcroft 	if (!PageLRU(page))
11815ad333ebSAndy Whitcroft 		return ret;
11825ad333ebSAndy Whitcroft 
1183e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1184e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1185894bc310SLee Schermerhorn 		return ret;
1186894bc310SLee Schermerhorn 
11875ad333ebSAndy Whitcroft 	ret = -EBUSY;
118808e552c6SKAMEZAWA Hiroyuki 
1189c8244935SMel Gorman 	/*
1190c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1191c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1192c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1193c8244935SMel Gorman 	 *
1194c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1195c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1196c8244935SMel Gorman 	 *
1197c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1198c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1199c8244935SMel Gorman 	 */
1200c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1201c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1202c8244935SMel Gorman 		if (PageWriteback(page))
120339deaf85SMinchan Kim 			return ret;
120439deaf85SMinchan Kim 
1205c8244935SMel Gorman 		if (PageDirty(page)) {
1206c8244935SMel Gorman 			struct address_space *mapping;
1207c8244935SMel Gorman 
1208c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1209c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1210c8244935SMel Gorman 				return ret;
1211c8244935SMel Gorman 
1212c8244935SMel Gorman 			/*
1213c8244935SMel Gorman 			 * Only pages without mappings or that have a
1214c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1215c8244935SMel Gorman 			 * without blocking
1216c8244935SMel Gorman 			 */
1217c8244935SMel Gorman 			mapping = page_mapping(page);
1218c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1219c8244935SMel Gorman 				return ret;
1220c8244935SMel Gorman 		}
1221c8244935SMel Gorman 	}
1222c8244935SMel Gorman 
1223f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1224f80c0673SMinchan Kim 		return ret;
1225f80c0673SMinchan Kim 
12265ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
12275ad333ebSAndy Whitcroft 		/*
12285ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
12295ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
12305ad333ebSAndy Whitcroft 		 * page release code relies on it.
12315ad333ebSAndy Whitcroft 		 */
12325ad333ebSAndy Whitcroft 		ClearPageLRU(page);
12335ad333ebSAndy Whitcroft 		ret = 0;
12345ad333ebSAndy Whitcroft 	}
12355ad333ebSAndy Whitcroft 
12365ad333ebSAndy Whitcroft 	return ret;
12375ad333ebSAndy Whitcroft }
12385ad333ebSAndy Whitcroft 
123949d2e9ccSChristoph Lameter /*
12401da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
12411da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
12421da177e4SLinus Torvalds  * and working on them outside the LRU lock.
12431da177e4SLinus Torvalds  *
12441da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
12451da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
12461da177e4SLinus Torvalds  *
12471da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
12481da177e4SLinus Torvalds  *
12491da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
12505dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
12511da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1252f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1253fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
12545ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
12553cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
12561da177e4SLinus Torvalds  *
12571da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
12581da177e4SLinus Torvalds  */
125969e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
12605dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1261fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
12623cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
12631da177e4SLinus Torvalds {
126475b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
126569e05944SAndrew Morton 	unsigned long nr_taken = 0;
1266c9b02d97SWu Fengguang 	unsigned long scan;
12671da177e4SLinus Torvalds 
1268c9b02d97SWu Fengguang 	for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
12695ad333ebSAndy Whitcroft 		struct page *page;
1270fa9add64SHugh Dickins 		int nr_pages;
12715ad333ebSAndy Whitcroft 
12721da177e4SLinus Torvalds 		page = lru_to_page(src);
12731da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
12741da177e4SLinus Torvalds 
1275309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
12768d438f96SNick Piggin 
1277f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
12785ad333ebSAndy Whitcroft 		case 0:
1279fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1280fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
12815ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1282fa9add64SHugh Dickins 			nr_taken += nr_pages;
12835ad333ebSAndy Whitcroft 			break;
12847c8ee9a8SNick Piggin 
12855ad333ebSAndy Whitcroft 		case -EBUSY:
12865ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
12875ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
12885ad333ebSAndy Whitcroft 			continue;
12895ad333ebSAndy Whitcroft 
12905ad333ebSAndy Whitcroft 		default:
12915ad333ebSAndy Whitcroft 			BUG();
12925ad333ebSAndy Whitcroft 		}
12935ad333ebSAndy Whitcroft 	}
12941da177e4SLinus Torvalds 
1295f626012dSHugh Dickins 	*nr_scanned = scan;
129675b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
129775b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
12981da177e4SLinus Torvalds 	return nr_taken;
12991da177e4SLinus Torvalds }
13001da177e4SLinus Torvalds 
130162695a84SNick Piggin /**
130262695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
130362695a84SNick Piggin  * @page: page to isolate from its LRU list
130462695a84SNick Piggin  *
130562695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
130662695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
130762695a84SNick Piggin  *
130862695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
130962695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
131062695a84SNick Piggin  *
131162695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1312894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1313894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1314894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
131562695a84SNick Piggin  *
131662695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
131762695a84SNick Piggin  * found will be decremented.
131862695a84SNick Piggin  *
131962695a84SNick Piggin  * Restrictions:
132062695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
132162695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
132262695a84SNick Piggin  *     without a stable reference).
132362695a84SNick Piggin  * (2) the lru_lock must not be held.
132462695a84SNick Piggin  * (3) interrupts must be enabled.
132562695a84SNick Piggin  */
132662695a84SNick Piggin int isolate_lru_page(struct page *page)
132762695a84SNick Piggin {
132862695a84SNick Piggin 	int ret = -EBUSY;
132962695a84SNick Piggin 
1330309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
13310c917313SKonstantin Khlebnikov 
133262695a84SNick Piggin 	if (PageLRU(page)) {
133362695a84SNick Piggin 		struct zone *zone = page_zone(page);
1334fa9add64SHugh Dickins 		struct lruvec *lruvec;
133562695a84SNick Piggin 
133662695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1337fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
13380c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1339894bc310SLee Schermerhorn 			int lru = page_lru(page);
13400c917313SKonstantin Khlebnikov 			get_page(page);
134162695a84SNick Piggin 			ClearPageLRU(page);
1342fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1343fa9add64SHugh Dickins 			ret = 0;
134462695a84SNick Piggin 		}
134562695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
134662695a84SNick Piggin 	}
134762695a84SNick Piggin 	return ret;
134862695a84SNick Piggin }
134962695a84SNick Piggin 
13505ad333ebSAndy Whitcroft /*
1351d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1352d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1353d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1354d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1355d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
135635cd7815SRik van Riel  */
135735cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
135835cd7815SRik van Riel 		struct scan_control *sc)
135935cd7815SRik van Riel {
136035cd7815SRik van Riel 	unsigned long inactive, isolated;
136135cd7815SRik van Riel 
136235cd7815SRik van Riel 	if (current_is_kswapd())
136335cd7815SRik van Riel 		return 0;
136435cd7815SRik van Riel 
136589b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
136635cd7815SRik van Riel 		return 0;
136735cd7815SRik van Riel 
136835cd7815SRik van Riel 	if (file) {
136935cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
137035cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
137135cd7815SRik van Riel 	} else {
137235cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
137335cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
137435cd7815SRik van Riel 	}
137535cd7815SRik van Riel 
13763cf23841SFengguang Wu 	/*
13773cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
13783cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
13793cf23841SFengguang Wu 	 * deadlock.
13803cf23841SFengguang Wu 	 */
13813cf23841SFengguang Wu 	if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
13823cf23841SFengguang Wu 		inactive >>= 3;
13833cf23841SFengguang Wu 
138435cd7815SRik van Riel 	return isolated > inactive;
138535cd7815SRik van Riel }
138635cd7815SRik van Riel 
138766635629SMel Gorman static noinline_for_stack void
138875b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
138966635629SMel Gorman {
139027ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
139127ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
13923f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
139366635629SMel Gorman 
139466635629SMel Gorman 	/*
139566635629SMel Gorman 	 * Put back any unfreeable pages.
139666635629SMel Gorman 	 */
139766635629SMel Gorman 	while (!list_empty(page_list)) {
13983f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
139966635629SMel Gorman 		int lru;
14003f79768fSHugh Dickins 
1401309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
140266635629SMel Gorman 		list_del(&page->lru);
140339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
140466635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
140566635629SMel Gorman 			putback_lru_page(page);
140666635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
140766635629SMel Gorman 			continue;
140866635629SMel Gorman 		}
1409fa9add64SHugh Dickins 
1410fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1411fa9add64SHugh Dickins 
14127a608572SLinus Torvalds 		SetPageLRU(page);
141366635629SMel Gorman 		lru = page_lru(page);
1414fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1415fa9add64SHugh Dickins 
141666635629SMel Gorman 		if (is_active_lru(lru)) {
141766635629SMel Gorman 			int file = is_file_lru(lru);
14189992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
14199992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
142066635629SMel Gorman 		}
14212bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
14222bcf8879SHugh Dickins 			__ClearPageLRU(page);
14232bcf8879SHugh Dickins 			__ClearPageActive(page);
1424fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
14252bcf8879SHugh Dickins 
14262bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
142766635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
14282bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
142966635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
14302bcf8879SHugh Dickins 			} else
14312bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
143266635629SMel Gorman 		}
143366635629SMel Gorman 	}
143466635629SMel Gorman 
14353f79768fSHugh Dickins 	/*
14363f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
14373f79768fSHugh Dickins 	 */
14383f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
143966635629SMel Gorman }
144066635629SMel Gorman 
144166635629SMel Gorman /*
14421742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
14431742f19fSAndrew Morton  * of reclaimed pages
14441da177e4SLinus Torvalds  */
144566635629SMel Gorman static noinline_for_stack unsigned long
14461a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
14479e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
14481da177e4SLinus Torvalds {
14491da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1450e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
145105ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1452e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
14538e950282SMel Gorman 	unsigned long nr_dirty = 0;
14548e950282SMel Gorman 	unsigned long nr_congested = 0;
1455e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
145692df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1457b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1458f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
14593cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
14601a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14611a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
146278dc583dSKOSAKI Motohiro 
146335cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
146458355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
146535cd7815SRik van Riel 
146635cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
146735cd7815SRik van Riel 		if (fatal_signal_pending(current))
146835cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
146935cd7815SRik van Riel 	}
147035cd7815SRik van Riel 
14711da177e4SLinus Torvalds 	lru_add_drain();
1472f80c0673SMinchan Kim 
1473f80c0673SMinchan Kim 	if (!sc->may_unmap)
147461317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1475f80c0673SMinchan Kim 	if (!sc->may_writepage)
147661317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1477f80c0673SMinchan Kim 
14781da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
14791da177e4SLinus Torvalds 
14805dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
14815dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
148295d918fcSKonstantin Khlebnikov 
148395d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
148495d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
148595d918fcSKonstantin Khlebnikov 
148689b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1487e247dbceSKOSAKI Motohiro 		zone->pages_scanned += nr_scanned;
1488b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
148975b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1490b35ea17bSKOSAKI Motohiro 		else
149175b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1492b35ea17bSKOSAKI Motohiro 	}
149366635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1494d563c050SHillf Danton 
1495d563c050SHillf Danton 	if (nr_taken == 0)
149666635629SMel Gorman 		return 0;
1497b35ea17bSKOSAKI Motohiro 
149802c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
14998e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
15008e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1501b1a6f21eSMel Gorman 				false);
1502c661b078SAndy Whitcroft 
15033f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
15043f79768fSHugh Dickins 
150595d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1506d563c050SHillf Danton 
1507904249aaSYing Han 	if (global_reclaim(sc)) {
1508b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1509904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1510904249aaSYing Han 					       nr_reclaimed);
1511904249aaSYing Han 		else
1512904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1513904249aaSYing Han 					       nr_reclaimed);
1514904249aaSYing Han 	}
1515a74609faSNick Piggin 
151627ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
15173f79768fSHugh Dickins 
151895d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
15193f79768fSHugh Dickins 
15203f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
15213f79768fSHugh Dickins 
15223f79768fSHugh Dickins 	free_hot_cold_page_list(&page_list, 1);
1523e11da5b4SMel Gorman 
152492df3a72SMel Gorman 	/*
152592df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
152692df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
152792df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
152892df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
152992df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
153092df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
153192df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
153292df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
153392df3a72SMel Gorman 	 *
15348e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
15358e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
15368e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
153792df3a72SMel Gorman 	 */
1538918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1539283aba9fSMel Gorman 		zone_set_flag(zone, ZONE_WRITEBACK);
154092df3a72SMel Gorman 
1541d43006d5SMel Gorman 	/*
1542b1a6f21eSMel Gorman 	 * memcg will stall in page writeback so only consider forcibly
1543b1a6f21eSMel Gorman 	 * stalling for global reclaim
1544d43006d5SMel Gorman 	 */
1545b1a6f21eSMel Gorman 	if (global_reclaim(sc)) {
1546b1a6f21eSMel Gorman 		/*
15478e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
15488e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
15498e950282SMel Gorman 		 */
15508e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
15518e950282SMel Gorman 			zone_set_flag(zone, ZONE_CONGESTED);
15528e950282SMel Gorman 
15538e950282SMel Gorman 		/*
1554b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1555b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1556b1a6f21eSMel Gorman 		 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1557b1a6f21eSMel Gorman 		 * pages from reclaim context. It will forcibly stall in the
1558b1a6f21eSMel Gorman 		 * next check.
1559b1a6f21eSMel Gorman 		 */
1560b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1561d43006d5SMel Gorman 			zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1562b1a6f21eSMel Gorman 
1563b1a6f21eSMel Gorman 		/*
1564b1a6f21eSMel Gorman 		 * In addition, if kswapd scans pages marked marked for
1565b1a6f21eSMel Gorman 		 * immediate reclaim and under writeback (nr_immediate), it
1566b1a6f21eSMel Gorman 		 * implies that pages are cycling through the LRU faster than
1567b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1568b1a6f21eSMel Gorman 		 */
1569b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken || nr_immediate)
1570b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1571e2be15f6SMel Gorman 	}
1572d43006d5SMel Gorman 
15738e950282SMel Gorman 	/*
15748e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
15758e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
15768e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
15778e950282SMel Gorman 	 */
15788e950282SMel Gorman 	if (!sc->hibernation_mode && !current_is_kswapd())
15798e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
15808e950282SMel Gorman 
1581e11da5b4SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1582e11da5b4SMel Gorman 		zone_idx(zone),
1583e11da5b4SMel Gorman 		nr_scanned, nr_reclaimed,
15849e3b2f8cSKonstantin Khlebnikov 		sc->priority,
158523b9da55SMel Gorman 		trace_shrink_flags(file));
158605ff5137SAndrew Morton 	return nr_reclaimed;
15871da177e4SLinus Torvalds }
15881da177e4SLinus Torvalds 
15893bb1a852SMartin Bligh /*
15901cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
15911cfb419bSKAMEZAWA Hiroyuki  *
15921cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
15931cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
15941cfb419bSKAMEZAWA Hiroyuki  *
15951cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
15961cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
15971cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
15981cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
15991cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
16001cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
16011cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
16021cfb419bSKAMEZAWA Hiroyuki  *
16031cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
16041cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
16051cfb419bSKAMEZAWA Hiroyuki  */
16061cfb419bSKAMEZAWA Hiroyuki 
1607fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
16083eb4140fSWu Fengguang 				     struct list_head *list,
16092bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
16103eb4140fSWu Fengguang 				     enum lru_list lru)
16113eb4140fSWu Fengguang {
1612fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
16133eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
16143eb4140fSWu Fengguang 	struct page *page;
1615fa9add64SHugh Dickins 	int nr_pages;
16163eb4140fSWu Fengguang 
16173eb4140fSWu Fengguang 	while (!list_empty(list)) {
16183eb4140fSWu Fengguang 		page = lru_to_page(list);
1619fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
16203eb4140fSWu Fengguang 
1621309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
16223eb4140fSWu Fengguang 		SetPageLRU(page);
16233eb4140fSWu Fengguang 
1624fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1625fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1626925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1627fa9add64SHugh Dickins 		pgmoved += nr_pages;
16283eb4140fSWu Fengguang 
16292bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16302bcf8879SHugh Dickins 			__ClearPageLRU(page);
16312bcf8879SHugh Dickins 			__ClearPageActive(page);
1632fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16332bcf8879SHugh Dickins 
16342bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
16353eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
16362bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
16373eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
16382bcf8879SHugh Dickins 			} else
16392bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
16403eb4140fSWu Fengguang 		}
16413eb4140fSWu Fengguang 	}
16423eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
16433eb4140fSWu Fengguang 	if (!is_active_lru(lru))
16443eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
16453eb4140fSWu Fengguang }
16461cfb419bSKAMEZAWA Hiroyuki 
1647f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
16481a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1649f16015fbSJohannes Weiner 			       struct scan_control *sc,
16509e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
16511cfb419bSKAMEZAWA Hiroyuki {
165244c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1653f626012dSHugh Dickins 	unsigned long nr_scanned;
16546fe6b7e3SWu Fengguang 	unsigned long vm_flags;
16551cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
16568cab4754SWu Fengguang 	LIST_HEAD(l_active);
1657b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
16581cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
16591a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
166044c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1661f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16623cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
16631a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
16641cfb419bSKAMEZAWA Hiroyuki 
16651da177e4SLinus Torvalds 	lru_add_drain();
1666f80c0673SMinchan Kim 
1667f80c0673SMinchan Kim 	if (!sc->may_unmap)
166861317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1669f80c0673SMinchan Kim 	if (!sc->may_writepage)
167061317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1671f80c0673SMinchan Kim 
16721da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1673925b7673SJohannes Weiner 
16745dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
16755dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
167689b5fae5SJohannes Weiner 	if (global_reclaim(sc))
1677f626012dSHugh Dickins 		zone->pages_scanned += nr_scanned;
167889b5fae5SJohannes Weiner 
1679b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
16801cfb419bSKAMEZAWA Hiroyuki 
1681f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
16823cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1683a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
16841da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
16851da177e4SLinus Torvalds 
16861da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
16871da177e4SLinus Torvalds 		cond_resched();
16881da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
16891da177e4SLinus Torvalds 		list_del(&page->lru);
16907e9cd484SRik van Riel 
169139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1692894bc310SLee Schermerhorn 			putback_lru_page(page);
1693894bc310SLee Schermerhorn 			continue;
1694894bc310SLee Schermerhorn 		}
1695894bc310SLee Schermerhorn 
1696cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1697cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1698cc715d99SMel Gorman 				if (page_has_private(page))
1699cc715d99SMel Gorman 					try_to_release_page(page, 0);
1700cc715d99SMel Gorman 				unlock_page(page);
1701cc715d99SMel Gorman 			}
1702cc715d99SMel Gorman 		}
1703cc715d99SMel Gorman 
1704c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1705c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
17069992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
17078cab4754SWu Fengguang 			/*
17088cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
17098cab4754SWu Fengguang 			 * give them one more trip around the active list. So
17108cab4754SWu Fengguang 			 * that executable code get better chances to stay in
17118cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
17128cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
17138cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
17148cab4754SWu Fengguang 			 * so we ignore them here.
17158cab4754SWu Fengguang 			 */
171641e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
17178cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
17188cab4754SWu Fengguang 				continue;
17198cab4754SWu Fengguang 			}
17208cab4754SWu Fengguang 		}
17217e9cd484SRik van Riel 
17225205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
17231da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
17241da177e4SLinus Torvalds 	}
17251da177e4SLinus Torvalds 
1726b555749aSAndrew Morton 	/*
17278cab4754SWu Fengguang 	 * Move pages back to the lru list.
1728b555749aSAndrew Morton 	 */
17292a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
17304f98a2feSRik van Riel 	/*
17318cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
17328cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
17338cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
17348cab4754SWu Fengguang 	 * get_scan_ratio.
1735556adecbSRik van Riel 	 */
1736b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1737556adecbSRik van Riel 
1738fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1739fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1740a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1741f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
17422bcf8879SHugh Dickins 
17432bcf8879SHugh Dickins 	free_hot_cold_page_list(&l_hold, 1);
17441da177e4SLinus Torvalds }
17451da177e4SLinus Torvalds 
174674e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
174714797e23SKOSAKI Motohiro static int inactive_anon_is_low_global(struct zone *zone)
1748f89eb90eSKOSAKI Motohiro {
1749f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1750f89eb90eSKOSAKI Motohiro 
1751f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1752f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1753f89eb90eSKOSAKI Motohiro 
1754f89eb90eSKOSAKI Motohiro 	if (inactive * zone->inactive_ratio < active)
1755f89eb90eSKOSAKI Motohiro 		return 1;
1756f89eb90eSKOSAKI Motohiro 
1757f89eb90eSKOSAKI Motohiro 	return 0;
1758f89eb90eSKOSAKI Motohiro }
1759f89eb90eSKOSAKI Motohiro 
176014797e23SKOSAKI Motohiro /**
176114797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1762c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
176314797e23SKOSAKI Motohiro  *
176414797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
176514797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
176614797e23SKOSAKI Motohiro  */
1767c56d5c7dSKonstantin Khlebnikov static int inactive_anon_is_low(struct lruvec *lruvec)
176814797e23SKOSAKI Motohiro {
176974e3f3c3SMinchan Kim 	/*
177074e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
177174e3f3c3SMinchan Kim 	 * is pointless.
177274e3f3c3SMinchan Kim 	 */
177374e3f3c3SMinchan Kim 	if (!total_swap_pages)
177474e3f3c3SMinchan Kim 		return 0;
177574e3f3c3SMinchan Kim 
1776c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1777c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1778f16015fbSJohannes Weiner 
1779c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
178014797e23SKOSAKI Motohiro }
178174e3f3c3SMinchan Kim #else
1782c56d5c7dSKonstantin Khlebnikov static inline int inactive_anon_is_low(struct lruvec *lruvec)
178374e3f3c3SMinchan Kim {
178474e3f3c3SMinchan Kim 	return 0;
178574e3f3c3SMinchan Kim }
178674e3f3c3SMinchan Kim #endif
178714797e23SKOSAKI Motohiro 
178856e49d21SRik van Riel /**
178956e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1790c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
179156e49d21SRik van Riel  *
179256e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
179356e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
179456e49d21SRik van Riel  * than half of the file pages are on the inactive list.
179556e49d21SRik van Riel  *
179656e49d21SRik van Riel  * Once we get to that situation, protect the system's working
179756e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
179856e49d21SRik van Riel  *
179956e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
180056e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
180156e49d21SRik van Riel  */
1802c56d5c7dSKonstantin Khlebnikov static int inactive_file_is_low(struct lruvec *lruvec)
180356e49d21SRik van Riel {
1804e3790144SJohannes Weiner 	unsigned long inactive;
1805e3790144SJohannes Weiner 	unsigned long active;
180656e49d21SRik van Riel 
1807e3790144SJohannes Weiner 	inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1808e3790144SJohannes Weiner 	active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1809e3790144SJohannes Weiner 
1810e3790144SJohannes Weiner 	return active > inactive;
181156e49d21SRik van Riel }
181256e49d21SRik van Riel 
181375b00af7SHugh Dickins static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1814b39415b2SRik van Riel {
181575b00af7SHugh Dickins 	if (is_file_lru(lru))
1816c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1817b39415b2SRik van Riel 	else
1818c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1819b39415b2SRik van Riel }
1820b39415b2SRik van Riel 
18214f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
18221a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1823b69408e8SChristoph Lameter {
1824b39415b2SRik van Riel 	if (is_active_lru(lru)) {
182575b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
18261a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1827556adecbSRik van Riel 		return 0;
1828556adecbSRik van Riel 	}
1829556adecbSRik van Riel 
18301a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1831b69408e8SChristoph Lameter }
1832b69408e8SChristoph Lameter 
18333d58ab5cSKonstantin Khlebnikov static int vmscan_swappiness(struct scan_control *sc)
18341f4c025bSKAMEZAWA Hiroyuki {
183589b5fae5SJohannes Weiner 	if (global_reclaim(sc))
18361f4c025bSKAMEZAWA Hiroyuki 		return vm_swappiness;
18373d58ab5cSKonstantin Khlebnikov 	return mem_cgroup_swappiness(sc->target_mem_cgroup);
18381f4c025bSKAMEZAWA Hiroyuki }
18391f4c025bSKAMEZAWA Hiroyuki 
18409a265114SJohannes Weiner enum scan_balance {
18419a265114SJohannes Weiner 	SCAN_EQUAL,
18429a265114SJohannes Weiner 	SCAN_FRACT,
18439a265114SJohannes Weiner 	SCAN_ANON,
18449a265114SJohannes Weiner 	SCAN_FILE,
18459a265114SJohannes Weiner };
18469a265114SJohannes Weiner 
18471da177e4SLinus Torvalds /*
18484f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
18494f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
18504f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
18514f98a2feSRik van Riel  * onto the active list instead of evict.
18524f98a2feSRik van Riel  *
1853be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1854be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
18554f98a2feSRik van Riel  */
185690126375SKonstantin Khlebnikov static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
18579e3b2f8cSKonstantin Khlebnikov 			   unsigned long *nr)
18584f98a2feSRik van Riel {
185990126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
18609a265114SJohannes Weiner 	u64 fraction[2];
18619a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
186290126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
18639a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
18649a265114SJohannes Weiner 	enum scan_balance scan_balance;
1865*0bf1457fSJohannes Weiner 	unsigned long anon, file;
18669a265114SJohannes Weiner 	bool force_scan = false;
18679a265114SJohannes Weiner 	unsigned long ap, fp;
18689a265114SJohannes Weiner 	enum lru_list lru;
1869246e87a9SKAMEZAWA Hiroyuki 
1870f11c0ca5SJohannes Weiner 	/*
1871f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1872f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1873f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1874f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1875f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1876f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1877f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1878f11c0ca5SJohannes Weiner 	 * well.
1879f11c0ca5SJohannes Weiner 	 */
18806e543d57SLisa Du 	if (current_is_kswapd() && !zone_reclaimable(zone))
1881a4d3e9e7SJohannes Weiner 		force_scan = true;
188289b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1883a4d3e9e7SJohannes Weiner 		force_scan = true;
188476a33fc3SShaohua Li 
188576a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
1886ec8acf20SShaohua Li 	if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
18879a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
188876a33fc3SShaohua Li 		goto out;
188976a33fc3SShaohua Li 	}
18904f98a2feSRik van Riel 
189110316b31SJohannes Weiner 	/*
189210316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
189310316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
189410316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
189510316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
189610316b31SJohannes Weiner 	 * too expensive.
189710316b31SJohannes Weiner 	 */
189810316b31SJohannes Weiner 	if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
18999a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
190010316b31SJohannes Weiner 		goto out;
190110316b31SJohannes Weiner 	}
190210316b31SJohannes Weiner 
190310316b31SJohannes Weiner 	/*
190410316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
190510316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
190610316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
190710316b31SJohannes Weiner 	 */
190810316b31SJohannes Weiner 	if (!sc->priority && vmscan_swappiness(sc)) {
19099a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
191010316b31SJohannes Weiner 		goto out;
191110316b31SJohannes Weiner 	}
191210316b31SJohannes Weiner 
19134d7dcca2SHugh Dickins 	anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
19144d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_ANON);
19154d7dcca2SHugh Dickins 	file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
19164d7dcca2SHugh Dickins 		get_lru_size(lruvec, LRU_INACTIVE_FILE);
1917a4d3e9e7SJohannes Weiner 
191811d16c25SJohannes Weiner 	/*
19197c5bd705SJohannes Weiner 	 * There is enough inactive page cache, do not reclaim
19207c5bd705SJohannes Weiner 	 * anything from the anonymous working set right now.
1921e9868505SRik van Riel 	 */
19227c5bd705SJohannes Weiner 	if (!inactive_file_is_low(lruvec)) {
19239a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
1924e9868505SRik van Riel 		goto out;
19254f98a2feSRik van Riel 	}
19264f98a2feSRik van Riel 
19279a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
19289a265114SJohannes Weiner 
19294f98a2feSRik van Riel 	/*
193058c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
193158c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
193258c37f6eSKOSAKI Motohiro 	 */
19333d58ab5cSKonstantin Khlebnikov 	anon_prio = vmscan_swappiness(sc);
193475b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
193558c37f6eSKOSAKI Motohiro 
193658c37f6eSKOSAKI Motohiro 	/*
19374f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
19384f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
19394f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
19404f98a2feSRik van Riel 	 *
19414f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
19424f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
19434f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
19444f98a2feSRik van Riel 	 *
19454f98a2feSRik van Riel 	 * anon in [0], file in [1]
19464f98a2feSRik van Riel 	 */
194790126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
194858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
19496e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
19506e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
19514f98a2feSRik van Riel 	}
19524f98a2feSRik van Riel 
19536e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
19546e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
19556e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
19564f98a2feSRik van Riel 	}
19574f98a2feSRik van Riel 
19584f98a2feSRik van Riel 	/*
195900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
196000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
196100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
19624f98a2feSRik van Riel 	 */
1963fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
19646e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
19654f98a2feSRik van Riel 
1966fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
19676e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
196890126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
19694f98a2feSRik van Riel 
197076a33fc3SShaohua Li 	fraction[0] = ap;
197176a33fc3SShaohua Li 	fraction[1] = fp;
197276a33fc3SShaohua Li 	denominator = ap + fp + 1;
197376a33fc3SShaohua Li out:
19744111304dSHugh Dickins 	for_each_evictable_lru(lru) {
19754111304dSHugh Dickins 		int file = is_file_lru(lru);
1976d778df51SJohannes Weiner 		unsigned long size;
197776a33fc3SShaohua Li 		unsigned long scan;
197876a33fc3SShaohua Li 
1979d778df51SJohannes Weiner 		size = get_lru_size(lruvec, lru);
1980d778df51SJohannes Weiner 		scan = size >> sc->priority;
19819a265114SJohannes Weiner 
1982f11c0ca5SJohannes Weiner 		if (!scan && force_scan)
1983d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
19849a265114SJohannes Weiner 
19859a265114SJohannes Weiner 		switch (scan_balance) {
19869a265114SJohannes Weiner 		case SCAN_EQUAL:
19879a265114SJohannes Weiner 			/* Scan lists relative to size */
19889a265114SJohannes Weiner 			break;
19899a265114SJohannes Weiner 		case SCAN_FRACT:
19909a265114SJohannes Weiner 			/*
19919a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
19929a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
19939a265114SJohannes Weiner 			 */
199476a33fc3SShaohua Li 			scan = div64_u64(scan * fraction[file], denominator);
19959a265114SJohannes Weiner 			break;
19969a265114SJohannes Weiner 		case SCAN_FILE:
19979a265114SJohannes Weiner 		case SCAN_ANON:
19989a265114SJohannes Weiner 			/* Scan one type exclusively */
19999a265114SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file)
20009a265114SJohannes Weiner 				scan = 0;
20019a265114SJohannes Weiner 			break;
20029a265114SJohannes Weiner 		default:
20039a265114SJohannes Weiner 			/* Look ma, no brain */
20049a265114SJohannes Weiner 			BUG();
20059a265114SJohannes Weiner 		}
20064111304dSHugh Dickins 		nr[lru] = scan;
200776a33fc3SShaohua Li 	}
20086e08a369SWu Fengguang }
20094f98a2feSRik van Riel 
20109b4f98cdSJohannes Weiner /*
20119b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
20129b4f98cdSJohannes Weiner  */
20139b4f98cdSJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
20149b4f98cdSJohannes Weiner {
20159b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2016e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
20179b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
20189b4f98cdSJohannes Weiner 	enum lru_list lru;
20199b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
20209b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
20219b4f98cdSJohannes Weiner 	struct blk_plug plug;
2022e82e0561SMel Gorman 	bool scan_adjusted = false;
20239b4f98cdSJohannes Weiner 
20249b4f98cdSJohannes Weiner 	get_scan_count(lruvec, sc, nr);
20259b4f98cdSJohannes Weiner 
2026e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2027e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2028e82e0561SMel Gorman 
20299b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
20309b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
20319b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2032e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2033e82e0561SMel Gorman 		unsigned long nr_scanned;
2034e82e0561SMel Gorman 
20359b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
20369b4f98cdSJohannes Weiner 			if (nr[lru]) {
20379b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
20389b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
20399b4f98cdSJohannes Weiner 
20409b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
20419b4f98cdSJohannes Weiner 							    lruvec, sc);
20429b4f98cdSJohannes Weiner 			}
20439b4f98cdSJohannes Weiner 		}
2044e82e0561SMel Gorman 
2045e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2046e82e0561SMel Gorman 			continue;
2047e82e0561SMel Gorman 
20489b4f98cdSJohannes Weiner 		/*
2049e82e0561SMel Gorman 		 * For global direct reclaim, reclaim only the number of pages
2050e82e0561SMel Gorman 		 * requested. Less care is taken to scan proportionally as it
2051e82e0561SMel Gorman 		 * is more important to minimise direct reclaim stall latency
2052e82e0561SMel Gorman 		 * than it is to properly age the LRU lists.
20539b4f98cdSJohannes Weiner 		 */
2054e82e0561SMel Gorman 		if (global_reclaim(sc) && !current_is_kswapd())
20559b4f98cdSJohannes Weiner 			break;
2056e82e0561SMel Gorman 
2057e82e0561SMel Gorman 		/*
2058e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
2059e82e0561SMel Gorman 		 * requested. Ensure that the anon and file LRUs shrink
2060e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2061e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2062e82e0561SMel Gorman 		 * proportional to the original scan target.
2063e82e0561SMel Gorman 		 */
2064e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2065e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2066e82e0561SMel Gorman 
2067e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2068e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2069e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2070e82e0561SMel Gorman 			lru = LRU_BASE;
2071e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2072e82e0561SMel Gorman 		} else {
2073e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2074e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2075e82e0561SMel Gorman 			lru = LRU_FILE;
2076e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2077e82e0561SMel Gorman 		}
2078e82e0561SMel Gorman 
2079e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2080e82e0561SMel Gorman 		nr[lru] = 0;
2081e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2082e82e0561SMel Gorman 
2083e82e0561SMel Gorman 		/*
2084e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2085e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2086e82e0561SMel Gorman 		 */
2087e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2088e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2089e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2090e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2091e82e0561SMel Gorman 
2092e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2093e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2094e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2095e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2096e82e0561SMel Gorman 
2097e82e0561SMel Gorman 		scan_adjusted = true;
20989b4f98cdSJohannes Weiner 	}
20999b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
21009b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
21019b4f98cdSJohannes Weiner 
21029b4f98cdSJohannes Weiner 	/*
21039b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
21049b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
21059b4f98cdSJohannes Weiner 	 */
21069b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
21079b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
21089b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
21099b4f98cdSJohannes Weiner 
21109b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
21119b4f98cdSJohannes Weiner }
21129b4f98cdSJohannes Weiner 
211323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
21149e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
211523b9da55SMel Gorman {
2116d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
211723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
21189e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
211923b9da55SMel Gorman 		return true;
212023b9da55SMel Gorman 
212123b9da55SMel Gorman 	return false;
212223b9da55SMel Gorman }
212323b9da55SMel Gorman 
21244f98a2feSRik van Riel /*
212523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
212623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
212723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
212823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
212923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
21303e7d3449SMel Gorman  */
21319b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
21323e7d3449SMel Gorman 					unsigned long nr_reclaimed,
21333e7d3449SMel Gorman 					unsigned long nr_scanned,
21343e7d3449SMel Gorman 					struct scan_control *sc)
21353e7d3449SMel Gorman {
21363e7d3449SMel Gorman 	unsigned long pages_for_compaction;
21373e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
21383e7d3449SMel Gorman 
21393e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
21409e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
21413e7d3449SMel Gorman 		return false;
21423e7d3449SMel Gorman 
21432876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
21442876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
21453e7d3449SMel Gorman 		/*
21462876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
21472876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
21482876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
21492876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
21503e7d3449SMel Gorman 		 */
21513e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
21523e7d3449SMel Gorman 			return false;
21532876592fSMel Gorman 	} else {
21542876592fSMel Gorman 		/*
21552876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
21562876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
21572876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
21582876592fSMel Gorman 		 * pages that were scanned. This will return to the
21592876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
21602876592fSMel Gorman 		 * the resulting allocation attempt fails
21612876592fSMel Gorman 		 */
21622876592fSMel Gorman 		if (!nr_reclaimed)
21632876592fSMel Gorman 			return false;
21642876592fSMel Gorman 	}
21653e7d3449SMel Gorman 
21663e7d3449SMel Gorman 	/*
21673e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
21683e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
21693e7d3449SMel Gorman 	 */
21703e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
21719b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2172ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
21739b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
21743e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
21753e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
21763e7d3449SMel Gorman 		return true;
21773e7d3449SMel Gorman 
21783e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
21799b4f98cdSJohannes Weiner 	switch (compaction_suitable(zone, sc->order)) {
21803e7d3449SMel Gorman 	case COMPACT_PARTIAL:
21813e7d3449SMel Gorman 	case COMPACT_CONTINUE:
21823e7d3449SMel Gorman 		return false;
21833e7d3449SMel Gorman 	default:
21843e7d3449SMel Gorman 		return true;
21853e7d3449SMel Gorman 	}
21863e7d3449SMel Gorman }
21873e7d3449SMel Gorman 
21880608f43dSAndrew Morton static void shrink_zone(struct zone *zone, struct scan_control *sc)
2189f16015fbSJohannes Weiner {
21909b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
21919b4f98cdSJohannes Weiner 
21929b4f98cdSJohannes Weiner 	do {
21935660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
21945660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
21955660048cSJohannes Weiner 			.zone = zone,
21969e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
21975660048cSJohannes Weiner 		};
2198694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
21995660048cSJohannes Weiner 
22009b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
22019b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
22029b4f98cdSJohannes Weiner 
2203694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2204694fbc0fSAndrew Morton 		do {
22059b4f98cdSJohannes Weiner 			struct lruvec *lruvec;
22069b4f98cdSJohannes Weiner 
22079b4f98cdSJohannes Weiner 			lruvec = mem_cgroup_zone_lruvec(zone, memcg);
22085660048cSJohannes Weiner 
2209f9be23d6SKonstantin Khlebnikov 			shrink_lruvec(lruvec, sc);
2210f9be23d6SKonstantin Khlebnikov 
22115660048cSJohannes Weiner 			/*
2212a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2213a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
22149b4f98cdSJohannes Weiner 			 * zone.
2215a394cb8eSMichal Hocko 			 *
2216a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2217a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2218a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2219a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
22205660048cSJohannes Weiner 			 */
2221a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2222a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
22235660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
22245660048cSJohannes Weiner 				break;
22255660048cSJohannes Weiner 			}
2226694fbc0fSAndrew Morton 			memcg = mem_cgroup_iter(root, memcg, &reclaim);
2227694fbc0fSAndrew Morton 		} while (memcg);
222870ddf637SAnton Vorontsov 
222970ddf637SAnton Vorontsov 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
223070ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
223170ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
223270ddf637SAnton Vorontsov 
22339b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
22349b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
2235f16015fbSJohannes Weiner }
2236f16015fbSJohannes Weiner 
2237fe4b1b24SMel Gorman /* Returns true if compaction should go ahead for a high-order request */
2238fe4b1b24SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2239fe4b1b24SMel Gorman {
2240fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2241fe4b1b24SMel Gorman 	bool watermark_ok;
2242fe4b1b24SMel Gorman 
2243fe4b1b24SMel Gorman 	/* Do not consider compaction for orders reclaim is meant to satisfy */
2244fe4b1b24SMel Gorman 	if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2245fe4b1b24SMel Gorman 		return false;
2246fe4b1b24SMel Gorman 
2247fe4b1b24SMel Gorman 	/*
2248fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2249fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2250fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2251fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2252fe4b1b24SMel Gorman 	 */
2253fe4b1b24SMel Gorman 	balance_gap = min(low_wmark_pages(zone),
2254b40da049SJiang Liu 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2255fe4b1b24SMel Gorman 			KSWAPD_ZONE_BALANCE_GAP_RATIO);
2256fe4b1b24SMel Gorman 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2257fe4b1b24SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2258fe4b1b24SMel Gorman 
2259fe4b1b24SMel Gorman 	/*
2260fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2261fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2262fe4b1b24SMel Gorman 	 */
2263aff62249SRik van Riel 	if (compaction_deferred(zone, sc->order))
2264fe4b1b24SMel Gorman 		return watermark_ok;
2265fe4b1b24SMel Gorman 
2266fe4b1b24SMel Gorman 	/* If compaction is not ready to start, keep reclaiming */
2267fe4b1b24SMel Gorman 	if (!compaction_suitable(zone, sc->order))
2268fe4b1b24SMel Gorman 		return false;
2269fe4b1b24SMel Gorman 
2270fe4b1b24SMel Gorman 	return watermark_ok;
2271fe4b1b24SMel Gorman }
2272fe4b1b24SMel Gorman 
22731da177e4SLinus Torvalds /*
22741da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
22751da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
22761da177e4SLinus Torvalds  * request.
22771da177e4SLinus Torvalds  *
227841858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
227941858966SMel Gorman  * Because:
22801da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
22811da177e4SLinus Torvalds  *    allocation or
228241858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
228341858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
228441858966SMel Gorman  *    zone defense algorithm.
22851da177e4SLinus Torvalds  *
22861da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
22871da177e4SLinus Torvalds  * scan then give up on it.
2288e0c23279SMel Gorman  *
2289e0c23279SMel Gorman  * This function returns true if a zone is being reclaimed for a costly
2290fe4b1b24SMel Gorman  * high-order allocation and compaction is ready to begin. This indicates to
22910cee34fdSMel Gorman  * the caller that it should consider retrying the allocation instead of
22920cee34fdSMel Gorman  * further reclaim.
22931da177e4SLinus Torvalds  */
22943115cd91SVladimir Davydov static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
22951da177e4SLinus Torvalds {
2296dd1a239fSMel Gorman 	struct zoneref *z;
229754a6eb5cSMel Gorman 	struct zone *zone;
22980608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
22990608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
230065ec02cbSVladimir Davydov 	unsigned long lru_pages = 0;
23010cee34fdSMel Gorman 	bool aborted_reclaim = false;
230265ec02cbSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
2303619d0d76SWeijie Yang 	gfp_t orig_mask;
23043115cd91SVladimir Davydov 	struct shrink_control shrink = {
23053115cd91SVladimir Davydov 		.gfp_mask = sc->gfp_mask,
23063115cd91SVladimir Davydov 	};
23079bbc04eeSWeijie Yang 	enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
23081cfb419bSKAMEZAWA Hiroyuki 
2309cc715d99SMel Gorman 	/*
2310cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2311cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2312cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2313cc715d99SMel Gorman 	 */
2314619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2315cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2316cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2317cc715d99SMel Gorman 
23183115cd91SVladimir Davydov 	nodes_clear(shrink.nodes_to_scan);
231965ec02cbSVladimir Davydov 
2320d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2321d4debc66SMel Gorman 					gfp_zone(sc->gfp_mask), sc->nodemask) {
2322f3fe6512SCon Kolivas 		if (!populated_zone(zone))
23231da177e4SLinus Torvalds 			continue;
23241cfb419bSKAMEZAWA Hiroyuki 		/*
23251cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
23261cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
23271cfb419bSKAMEZAWA Hiroyuki 		 */
232889b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
232902a0e53dSPaul Jackson 			if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
23301da177e4SLinus Torvalds 				continue;
233165ec02cbSVladimir Davydov 
233265ec02cbSVladimir Davydov 			lru_pages += zone_reclaimable_pages(zone);
23333115cd91SVladimir Davydov 			node_set(zone_to_nid(zone), shrink.nodes_to_scan);
233465ec02cbSVladimir Davydov 
23356e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
23366e543d57SLisa Du 			    !zone_reclaimable(zone))
23371da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
2338d84da3f9SKirill A. Shutemov 			if (IS_ENABLED(CONFIG_COMPACTION)) {
2339e0887c19SRik van Riel 				/*
2340e0c23279SMel Gorman 				 * If we already have plenty of memory free for
2341e0c23279SMel Gorman 				 * compaction in this zone, don't free any more.
2342e0c23279SMel Gorman 				 * Even though compaction is invoked for any
2343e0c23279SMel Gorman 				 * non-zero order, only frequent costly order
2344e0c23279SMel Gorman 				 * reclamation is disruptive enough to become a
2345c7cfa37bSCopot Alexandru 				 * noticeable problem, like transparent huge
2346c7cfa37bSCopot Alexandru 				 * page allocations.
2347e0887c19SRik van Riel 				 */
23489bbc04eeSWeijie Yang 				if ((zonelist_zone_idx(z) <= requested_highidx)
23499bbc04eeSWeijie Yang 				    && compaction_ready(zone, sc)) {
23500cee34fdSMel Gorman 					aborted_reclaim = true;
2351e0887c19SRik van Riel 					continue;
2352e0887c19SRik van Riel 				}
2353e0c23279SMel Gorman 			}
23540608f43dSAndrew Morton 			/*
23550608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
23560608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
23570608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
23580608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
23590608f43dSAndrew Morton 			 */
23600608f43dSAndrew Morton 			nr_soft_scanned = 0;
23610608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
23620608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
23630608f43dSAndrew Morton 						&nr_soft_scanned);
23640608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
23650608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2366ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2367ac34a1a3SKAMEZAWA Hiroyuki 		}
2368d149e3b2SYing Han 
23699e3b2f8cSKonstantin Khlebnikov 		shrink_zone(zone, sc);
23701da177e4SLinus Torvalds 	}
2371e0c23279SMel Gorman 
237265ec02cbSVladimir Davydov 	/*
237365ec02cbSVladimir Davydov 	 * Don't shrink slabs when reclaiming memory from over limit cgroups
237465ec02cbSVladimir Davydov 	 * but do shrink slab at least once when aborting reclaim for
237565ec02cbSVladimir Davydov 	 * compaction to avoid unevenly scanning file/anon LRU pages over slab
237665ec02cbSVladimir Davydov 	 * pages.
237765ec02cbSVladimir Davydov 	 */
237865ec02cbSVladimir Davydov 	if (global_reclaim(sc)) {
23793115cd91SVladimir Davydov 		shrink_slab(&shrink, sc->nr_scanned, lru_pages);
238065ec02cbSVladimir Davydov 		if (reclaim_state) {
238165ec02cbSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
238265ec02cbSVladimir Davydov 			reclaim_state->reclaimed_slab = 0;
238365ec02cbSVladimir Davydov 		}
238465ec02cbSVladimir Davydov 	}
238565ec02cbSVladimir Davydov 
2386619d0d76SWeijie Yang 	/*
2387619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2388619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2389619d0d76SWeijie Yang 	 */
2390619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
2391619d0d76SWeijie Yang 
23920cee34fdSMel Gorman 	return aborted_reclaim;
2393d1908362SMinchan Kim }
2394d1908362SMinchan Kim 
2395929bea7cSKOSAKI Motohiro /* All zones in zonelist are unreclaimable? */
2396d1908362SMinchan Kim static bool all_unreclaimable(struct zonelist *zonelist,
2397d1908362SMinchan Kim 		struct scan_control *sc)
2398d1908362SMinchan Kim {
2399d1908362SMinchan Kim 	struct zoneref *z;
2400d1908362SMinchan Kim 	struct zone *zone;
2401d1908362SMinchan Kim 
2402d1908362SMinchan Kim 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2403d1908362SMinchan Kim 			gfp_zone(sc->gfp_mask), sc->nodemask) {
2404d1908362SMinchan Kim 		if (!populated_zone(zone))
2405d1908362SMinchan Kim 			continue;
2406d1908362SMinchan Kim 		if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2407d1908362SMinchan Kim 			continue;
24086e543d57SLisa Du 		if (zone_reclaimable(zone))
2409929bea7cSKOSAKI Motohiro 			return false;
2410d1908362SMinchan Kim 	}
2411d1908362SMinchan Kim 
2412929bea7cSKOSAKI Motohiro 	return true;
24131da177e4SLinus Torvalds }
24141da177e4SLinus Torvalds 
24151da177e4SLinus Torvalds /*
24161da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
24171da177e4SLinus Torvalds  *
24181da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
24191da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
24201da177e4SLinus Torvalds  *
24211da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
24221da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
24235b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
24245b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
24255b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
24265b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2427a41f24eaSNishanth Aravamudan  *
2428a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2429a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
24301da177e4SLinus Torvalds  */
2431dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
24323115cd91SVladimir Davydov 					  struct scan_control *sc)
24331da177e4SLinus Torvalds {
243469e05944SAndrew Morton 	unsigned long total_scanned = 0;
243522fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
24360cee34fdSMel Gorman 	bool aborted_reclaim;
24371da177e4SLinus Torvalds 
2438873b4771SKeika Kobayashi 	delayacct_freepages_start();
2439873b4771SKeika Kobayashi 
244089b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2441f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
24421da177e4SLinus Torvalds 
24439e3b2f8cSKonstantin Khlebnikov 	do {
244470ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
244570ddf637SAnton Vorontsov 				sc->priority);
244666e1707bSBalbir Singh 		sc->nr_scanned = 0;
24473115cd91SVladimir Davydov 		aborted_reclaim = shrink_zones(zonelist, sc);
2448e0c23279SMel Gorman 
244966e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2450bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
24511da177e4SLinus Torvalds 			goto out;
24521da177e4SLinus Torvalds 
24531da177e4SLinus Torvalds 		/*
24540e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
24550e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
24560e50ce3bSMinchan Kim 		 */
24570e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
24580e50ce3bSMinchan Kim 			sc->may_writepage = 1;
24590e50ce3bSMinchan Kim 
24600e50ce3bSMinchan Kim 		/*
24611da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
24621da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
24631da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
24641da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
24651da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
24661da177e4SLinus Torvalds 		 */
246722fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
246822fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
24690e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
24700e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
247166e1707bSBalbir Singh 			sc->may_writepage = 1;
24721da177e4SLinus Torvalds 		}
24735a1c9cbcSMel Gorman 	} while (--sc->priority >= 0 && !aborted_reclaim);
2474bb21c7ceSKOSAKI Motohiro 
24751da177e4SLinus Torvalds out:
2476873b4771SKeika Kobayashi 	delayacct_freepages_end();
2477873b4771SKeika Kobayashi 
2478bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2479bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2480bb21c7ceSKOSAKI Motohiro 
2481929bea7cSKOSAKI Motohiro 	/*
2482929bea7cSKOSAKI Motohiro 	 * As hibernation is going on, kswapd is freezed so that it can't mark
2483929bea7cSKOSAKI Motohiro 	 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2484929bea7cSKOSAKI Motohiro 	 * check.
2485929bea7cSKOSAKI Motohiro 	 */
2486929bea7cSKOSAKI Motohiro 	if (oom_killer_disabled)
2487929bea7cSKOSAKI Motohiro 		return 0;
2488929bea7cSKOSAKI Motohiro 
24890cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
24900cee34fdSMel Gorman 	if (aborted_reclaim)
24917335084dSMel Gorman 		return 1;
24927335084dSMel Gorman 
2493bb21c7ceSKOSAKI Motohiro 	/* top priority shrink_zones still had more to do? don't OOM, then */
249489b5fae5SJohannes Weiner 	if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2495bb21c7ceSKOSAKI Motohiro 		return 1;
2496bb21c7ceSKOSAKI Motohiro 
2497bb21c7ceSKOSAKI Motohiro 	return 0;
24981da177e4SLinus Torvalds }
24991da177e4SLinus Torvalds 
25005515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
25015515061dSMel Gorman {
25025515061dSMel Gorman 	struct zone *zone;
25035515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
25045515061dSMel Gorman 	unsigned long free_pages = 0;
25055515061dSMel Gorman 	int i;
25065515061dSMel Gorman 	bool wmark_ok;
25075515061dSMel Gorman 
25085515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
25095515061dSMel Gorman 		zone = &pgdat->node_zones[i];
25105515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
25115515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
25125515061dSMel Gorman 	}
25135515061dSMel Gorman 
25145515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
25155515061dSMel Gorman 
25165515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
25175515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
25185515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
25195515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
25205515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
25215515061dSMel Gorman 	}
25225515061dSMel Gorman 
25235515061dSMel Gorman 	return wmark_ok;
25245515061dSMel Gorman }
25255515061dSMel Gorman 
25265515061dSMel Gorman /*
25275515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
25285515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
25295515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
253050694c28SMel Gorman  * when the low watermark is reached.
253150694c28SMel Gorman  *
253250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
253350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
25345515061dSMel Gorman  */
253550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
25365515061dSMel Gorman 					nodemask_t *nodemask)
25375515061dSMel Gorman {
25385515061dSMel Gorman 	struct zone *zone;
25395515061dSMel Gorman 	int high_zoneidx = gfp_zone(gfp_mask);
25405515061dSMel Gorman 	pg_data_t *pgdat;
25415515061dSMel Gorman 
25425515061dSMel Gorman 	/*
25435515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
25445515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
25455515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
25465515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
25475515061dSMel Gorman 	 * processes to block on log_wait_commit().
25485515061dSMel Gorman 	 */
25495515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
255050694c28SMel Gorman 		goto out;
255150694c28SMel Gorman 
255250694c28SMel Gorman 	/*
255350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
255450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
255550694c28SMel Gorman 	 */
255650694c28SMel Gorman 	if (fatal_signal_pending(current))
255750694c28SMel Gorman 		goto out;
25585515061dSMel Gorman 
25595515061dSMel Gorman 	/* Check if the pfmemalloc reserves are ok */
25605515061dSMel Gorman 	first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
25615515061dSMel Gorman 	pgdat = zone->zone_pgdat;
25625515061dSMel Gorman 	if (pfmemalloc_watermark_ok(pgdat))
256350694c28SMel Gorman 		goto out;
25645515061dSMel Gorman 
256568243e76SMel Gorman 	/* Account for the throttling */
256668243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
256768243e76SMel Gorman 
25685515061dSMel Gorman 	/*
25695515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
25705515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
25715515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
25725515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
25735515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
25745515061dSMel Gorman 	 * second before continuing.
25755515061dSMel Gorman 	 */
25765515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
25775515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
25785515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
257950694c28SMel Gorman 
258050694c28SMel Gorman 		goto check_pending;
25815515061dSMel Gorman 	}
25825515061dSMel Gorman 
25835515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
25845515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
25855515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
258650694c28SMel Gorman 
258750694c28SMel Gorman check_pending:
258850694c28SMel Gorman 	if (fatal_signal_pending(current))
258950694c28SMel Gorman 		return true;
259050694c28SMel Gorman 
259150694c28SMel Gorman out:
259250694c28SMel Gorman 	return false;
25935515061dSMel Gorman }
25945515061dSMel Gorman 
2595dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2596327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
259766e1707bSBalbir Singh {
259833906bc5SMel Gorman 	unsigned long nr_reclaimed;
259966e1707bSBalbir Singh 	struct scan_control sc = {
260021caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
260166e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
260222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2603a6dc60f8SJohannes Weiner 		.may_unmap = 1,
26042e2e4259SKOSAKI Motohiro 		.may_swap = 1,
260566e1707bSBalbir Singh 		.order = order,
26069e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
2607f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2608327c0e96SKAMEZAWA Hiroyuki 		.nodemask = nodemask,
260966e1707bSBalbir Singh 	};
261066e1707bSBalbir Singh 
26115515061dSMel Gorman 	/*
261250694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
261350694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
261450694c28SMel Gorman 	 * point.
26155515061dSMel Gorman 	 */
261650694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
26175515061dSMel Gorman 		return 1;
26185515061dSMel Gorman 
261933906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
262033906bc5SMel Gorman 				sc.may_writepage,
262133906bc5SMel Gorman 				gfp_mask);
262233906bc5SMel Gorman 
26233115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
262433906bc5SMel Gorman 
262533906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
262633906bc5SMel Gorman 
262733906bc5SMel Gorman 	return nr_reclaimed;
262866e1707bSBalbir Singh }
262966e1707bSBalbir Singh 
2630c255a458SAndrew Morton #ifdef CONFIG_MEMCG
263166e1707bSBalbir Singh 
263272835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
26334e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
26340ae5e89cSYing Han 						struct zone *zone,
26350ae5e89cSYing Han 						unsigned long *nr_scanned)
26364e416953SBalbir Singh {
26374e416953SBalbir Singh 	struct scan_control sc = {
26380ae5e89cSYing Han 		.nr_scanned = 0,
2639b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
26404e416953SBalbir Singh 		.may_writepage = !laptop_mode,
26414e416953SBalbir Singh 		.may_unmap = 1,
26424e416953SBalbir Singh 		.may_swap = !noswap,
26434e416953SBalbir Singh 		.order = 0,
26449e3b2f8cSKonstantin Khlebnikov 		.priority = 0,
264572835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
26464e416953SBalbir Singh 	};
2647f9be23d6SKonstantin Khlebnikov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
26480ae5e89cSYing Han 
26494e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
26504e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2651bdce6d9eSKOSAKI Motohiro 
26529e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2653bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2654bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2655bdce6d9eSKOSAKI Motohiro 
26564e416953SBalbir Singh 	/*
26574e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
26584e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
26594e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
26604e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
26614e416953SBalbir Singh 	 * the priority and make it zero.
26624e416953SBalbir Singh 	 */
2663f9be23d6SKonstantin Khlebnikov 	shrink_lruvec(lruvec, &sc);
2664bdce6d9eSKOSAKI Motohiro 
2665bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2666bdce6d9eSKOSAKI Motohiro 
26670ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
26684e416953SBalbir Singh 	return sc.nr_reclaimed;
26694e416953SBalbir Singh }
26704e416953SBalbir Singh 
267172835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
26728c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2673185efc0fSJohannes Weiner 					   bool noswap)
267466e1707bSBalbir Singh {
26754e416953SBalbir Singh 	struct zonelist *zonelist;
2676bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2677889976dbSYing Han 	int nid;
267866e1707bSBalbir Singh 	struct scan_control sc = {
267966e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2680a6dc60f8SJohannes Weiner 		.may_unmap = 1,
26812e2e4259SKOSAKI Motohiro 		.may_swap = !noswap,
268222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
268366e1707bSBalbir Singh 		.order = 0,
26849e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
268572835c86SJohannes Weiner 		.target_mem_cgroup = memcg,
2686327c0e96SKAMEZAWA Hiroyuki 		.nodemask = NULL, /* we don't care the placement */
2687a09ed5e0SYing Han 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2688a09ed5e0SYing Han 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2689a09ed5e0SYing Han 	};
269066e1707bSBalbir Singh 
2691889976dbSYing Han 	/*
2692889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2693889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2694889976dbSYing Han 	 * scan does not need to be the current node.
2695889976dbSYing Han 	 */
269672835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2697889976dbSYing Han 
2698889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2699bdce6d9eSKOSAKI Motohiro 
2700bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2701bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2702bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2703bdce6d9eSKOSAKI Motohiro 
27043115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2705bdce6d9eSKOSAKI Motohiro 
2706bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2707bdce6d9eSKOSAKI Motohiro 
2708bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
270966e1707bSBalbir Singh }
271066e1707bSBalbir Singh #endif
271166e1707bSBalbir Singh 
27129e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2713f16015fbSJohannes Weiner {
2714b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2715b95a2f2dSJohannes Weiner 
2716b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2717b95a2f2dSJohannes Weiner 		return;
2718b95a2f2dSJohannes Weiner 
2719b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2720b95a2f2dSJohannes Weiner 	do {
2721c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2722f16015fbSJohannes Weiner 
2723c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
27241a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
27259e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2726b95a2f2dSJohannes Weiner 
2727b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2728b95a2f2dSJohannes Weiner 	} while (memcg);
2729f16015fbSJohannes Weiner }
2730f16015fbSJohannes Weiner 
273160cefed4SJohannes Weiner static bool zone_balanced(struct zone *zone, int order,
273260cefed4SJohannes Weiner 			  unsigned long balance_gap, int classzone_idx)
273360cefed4SJohannes Weiner {
273460cefed4SJohannes Weiner 	if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
273560cefed4SJohannes Weiner 				    balance_gap, classzone_idx, 0))
273660cefed4SJohannes Weiner 		return false;
273760cefed4SJohannes Weiner 
2738d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2739d84da3f9SKirill A. Shutemov 	    !compaction_suitable(zone, order))
274060cefed4SJohannes Weiner 		return false;
274160cefed4SJohannes Weiner 
274260cefed4SJohannes Weiner 	return true;
274360cefed4SJohannes Weiner }
274460cefed4SJohannes Weiner 
27451741c877SMel Gorman /*
27464ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
27474ae0a48bSZlatko Calusic  *
27484ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
27494ae0a48bSZlatko Calusic  *
27504ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
27514ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
27524ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
27534ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
27544ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
27554ae0a48bSZlatko Calusic  * imbalanced zones.
27561741c877SMel Gorman  * The choice of 25% is due to
27571741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
27581741c877SMel Gorman  *     reasonable sized machine
27591741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
276025985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
27611741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
27621741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
27631741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
27641741c877SMel Gorman  */
27654ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
27661741c877SMel Gorman {
2767b40da049SJiang Liu 	unsigned long managed_pages = 0;
27684ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
27691741c877SMel Gorman 	int i;
27701741c877SMel Gorman 
27714ae0a48bSZlatko Calusic 	/* Check the watermark levels */
27724ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
27734ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
27741741c877SMel Gorman 
27754ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
27764ae0a48bSZlatko Calusic 			continue;
27774ae0a48bSZlatko Calusic 
2778b40da049SJiang Liu 		managed_pages += zone->managed_pages;
27794ae0a48bSZlatko Calusic 
27804ae0a48bSZlatko Calusic 		/*
27814ae0a48bSZlatko Calusic 		 * A special case here:
27824ae0a48bSZlatko Calusic 		 *
27834ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
27844ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
27854ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
27864ae0a48bSZlatko Calusic 		 */
27876e543d57SLisa Du 		if (!zone_reclaimable(zone)) {
2788b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27894ae0a48bSZlatko Calusic 			continue;
27904ae0a48bSZlatko Calusic 		}
27914ae0a48bSZlatko Calusic 
27924ae0a48bSZlatko Calusic 		if (zone_balanced(zone, order, 0, i))
2793b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
27944ae0a48bSZlatko Calusic 		else if (!order)
27954ae0a48bSZlatko Calusic 			return false;
27964ae0a48bSZlatko Calusic 	}
27974ae0a48bSZlatko Calusic 
27984ae0a48bSZlatko Calusic 	if (order)
2799b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
28004ae0a48bSZlatko Calusic 	else
28014ae0a48bSZlatko Calusic 		return true;
28021741c877SMel Gorman }
28031741c877SMel Gorman 
28045515061dSMel Gorman /*
28055515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
28065515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
28075515061dSMel Gorman  *
28085515061dSMel Gorman  * Returns true if kswapd is ready to sleep
28095515061dSMel Gorman  */
28105515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2811dc83edd9SMel Gorman 					int classzone_idx)
2812f50de2d3SMel Gorman {
2813f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2814f50de2d3SMel Gorman 	if (remaining)
28155515061dSMel Gorman 		return false;
28165515061dSMel Gorman 
28175515061dSMel Gorman 	/*
28185515061dSMel Gorman 	 * There is a potential race between when kswapd checks its watermarks
28195515061dSMel Gorman 	 * and a process gets throttled. There is also a potential race if
28205515061dSMel Gorman 	 * processes get throttled, kswapd wakes, a large process exits therby
28215515061dSMel Gorman 	 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
28225515061dSMel Gorman 	 * is going to sleep, no process should be sleeping on pfmemalloc_wait
28235515061dSMel Gorman 	 * so wake them now if necessary. If necessary, processes will wake
28245515061dSMel Gorman 	 * kswapd and get throttled again
28255515061dSMel Gorman 	 */
28265515061dSMel Gorman 	if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
28275515061dSMel Gorman 		wake_up(&pgdat->pfmemalloc_wait);
28285515061dSMel Gorman 		return false;
28295515061dSMel Gorman 	}
2830f50de2d3SMel Gorman 
28314ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
2832f50de2d3SMel Gorman }
2833f50de2d3SMel Gorman 
28341da177e4SLinus Torvalds /*
283575485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
283675485363SMel Gorman  * the high watermark.
2837b8e83b94SMel Gorman  *
2838b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
2839283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
2840283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
284175485363SMel Gorman  */
2842b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
28437c954f6dSMel Gorman 			       int classzone_idx,
284475485363SMel Gorman 			       struct scan_control *sc,
28452ab44f43SMel Gorman 			       unsigned long lru_pages,
28462ab44f43SMel Gorman 			       unsigned long *nr_attempted)
284775485363SMel Gorman {
28487c954f6dSMel Gorman 	int testorder = sc->order;
28497c954f6dSMel Gorman 	unsigned long balance_gap;
285075485363SMel Gorman 	struct reclaim_state *reclaim_state = current->reclaim_state;
285175485363SMel Gorman 	struct shrink_control shrink = {
285275485363SMel Gorman 		.gfp_mask = sc->gfp_mask,
285375485363SMel Gorman 	};
28547c954f6dSMel Gorman 	bool lowmem_pressure;
285575485363SMel Gorman 
285675485363SMel Gorman 	/* Reclaim above the high watermark. */
285775485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
28587c954f6dSMel Gorman 
28597c954f6dSMel Gorman 	/*
28607c954f6dSMel Gorman 	 * Kswapd reclaims only single pages with compaction enabled. Trying
28617c954f6dSMel Gorman 	 * too hard to reclaim until contiguous free pages have become
28627c954f6dSMel Gorman 	 * available can hurt performance by evicting too much useful data
28637c954f6dSMel Gorman 	 * from memory. Do not reclaim more than needed for compaction.
28647c954f6dSMel Gorman 	 */
28657c954f6dSMel Gorman 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
28667c954f6dSMel Gorman 			compaction_suitable(zone, sc->order) !=
28677c954f6dSMel Gorman 				COMPACT_SKIPPED)
28687c954f6dSMel Gorman 		testorder = 0;
28697c954f6dSMel Gorman 
28707c954f6dSMel Gorman 	/*
28717c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
28727c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
28737c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
28747c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
28757c954f6dSMel Gorman 	 */
28767c954f6dSMel Gorman 	balance_gap = min(low_wmark_pages(zone),
28777c954f6dSMel Gorman 		(zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
28787c954f6dSMel Gorman 		KSWAPD_ZONE_BALANCE_GAP_RATIO);
28797c954f6dSMel Gorman 
28807c954f6dSMel Gorman 	/*
28817c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
28827c954f6dSMel Gorman 	 * reclaim is necessary
28837c954f6dSMel Gorman 	 */
28847c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
28857c954f6dSMel Gorman 	if (!lowmem_pressure && zone_balanced(zone, testorder,
28867c954f6dSMel Gorman 						balance_gap, classzone_idx))
28877c954f6dSMel Gorman 		return true;
28887c954f6dSMel Gorman 
288975485363SMel Gorman 	shrink_zone(zone, sc);
28900ce3d744SDave Chinner 	nodes_clear(shrink.nodes_to_scan);
28910ce3d744SDave Chinner 	node_set(zone_to_nid(zone), shrink.nodes_to_scan);
289275485363SMel Gorman 
289375485363SMel Gorman 	reclaim_state->reclaimed_slab = 0;
28946e543d57SLisa Du 	shrink_slab(&shrink, sc->nr_scanned, lru_pages);
289575485363SMel Gorman 	sc->nr_reclaimed += reclaim_state->reclaimed_slab;
289675485363SMel Gorman 
28972ab44f43SMel Gorman 	/* Account for the number of pages attempted to reclaim */
28982ab44f43SMel Gorman 	*nr_attempted += sc->nr_to_reclaim;
28992ab44f43SMel Gorman 
2900283aba9fSMel Gorman 	zone_clear_flag(zone, ZONE_WRITEBACK);
2901283aba9fSMel Gorman 
29027c954f6dSMel Gorman 	/*
29037c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
29047c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
29057c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
29067c954f6dSMel Gorman 	 * waits.
29077c954f6dSMel Gorman 	 */
29086e543d57SLisa Du 	if (zone_reclaimable(zone) &&
29097c954f6dSMel Gorman 	    zone_balanced(zone, testorder, 0, classzone_idx)) {
29107c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_CONGESTED);
29117c954f6dSMel Gorman 		zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
29127c954f6dSMel Gorman 	}
29137c954f6dSMel Gorman 
2914b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
291575485363SMel Gorman }
291675485363SMel Gorman 
291775485363SMel Gorman /*
29181da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
291941858966SMel Gorman  * they are all at high_wmark_pages(zone).
29201da177e4SLinus Torvalds  *
29210abdee2bSMel Gorman  * Returns the final order kswapd was reclaiming at
29221da177e4SLinus Torvalds  *
29231da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
29241da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
29251da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
29261da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
29271da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
29281da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
29291da177e4SLinus Torvalds  * the zone for when the problem goes away.
29301da177e4SLinus Torvalds  *
29311da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
293241858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
293341858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
293441858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
293541858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
293641858966SMel Gorman  * of pages is balanced across the zones.
29371da177e4SLinus Torvalds  */
293899504748SMel Gorman static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2939dc83edd9SMel Gorman 							int *classzone_idx)
29401da177e4SLinus Torvalds {
29411da177e4SLinus Torvalds 	int i;
294299504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
29430608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29440608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2945179e9639SAndrew Morton 	struct scan_control sc = {
2946179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
2947b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
2948a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29492e2e4259SKOSAKI Motohiro 		.may_swap = 1,
2950b8e83b94SMel Gorman 		.may_writepage = !laptop_mode,
29515ad333ebSAndy Whitcroft 		.order = order,
2952f16015fbSJohannes Weiner 		.target_mem_cgroup = NULL,
2953179e9639SAndrew Morton 	};
2954f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
29551da177e4SLinus Torvalds 
29569e3b2f8cSKonstantin Khlebnikov 	do {
29571da177e4SLinus Torvalds 		unsigned long lru_pages = 0;
29582ab44f43SMel Gorman 		unsigned long nr_attempted = 0;
2959b8e83b94SMel Gorman 		bool raise_priority = true;
29602ab44f43SMel Gorman 		bool pgdat_needs_compaction = (order > 0);
2961b8e83b94SMel Gorman 
2962b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
29631da177e4SLinus Torvalds 
29641da177e4SLinus Torvalds 		/*
29651da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
29661da177e4SLinus Torvalds 		 * zone which needs scanning
29671da177e4SLinus Torvalds 		 */
29681da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
29691da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
29701da177e4SLinus Torvalds 
2971f3fe6512SCon Kolivas 			if (!populated_zone(zone))
29721da177e4SLinus Torvalds 				continue;
29731da177e4SLinus Torvalds 
29746e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
29756e543d57SLisa Du 			    !zone_reclaimable(zone))
29761da177e4SLinus Torvalds 				continue;
29771da177e4SLinus Torvalds 
2978556adecbSRik van Riel 			/*
2979556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
2980556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
2981556adecbSRik van Riel 			 */
29829e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
2983556adecbSRik van Riel 
2984cc715d99SMel Gorman 			/*
2985cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
2986cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
2987cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
2988cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
2989cc715d99SMel Gorman 			 */
2990cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
2991cc715d99SMel Gorman 				end_zone = i;
2992cc715d99SMel Gorman 				break;
2993cc715d99SMel Gorman 			}
2994cc715d99SMel Gorman 
299560cefed4SJohannes Weiner 			if (!zone_balanced(zone, order, 0, 0)) {
29961da177e4SLinus Torvalds 				end_zone = i;
2997e1dbeda6SAndrew Morton 				break;
2998439423f6SShaohua Li 			} else {
2999d43006d5SMel Gorman 				/*
3000d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
3001d43006d5SMel Gorman 				 * flags
3002d43006d5SMel Gorman 				 */
3003439423f6SShaohua Li 				zone_clear_flag(zone, ZONE_CONGESTED);
3004d43006d5SMel Gorman 				zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
30051da177e4SLinus Torvalds 			}
30061da177e4SLinus Torvalds 		}
3007dafcb73eSZlatko Calusic 
3008b8e83b94SMel Gorman 		if (i < 0)
30091da177e4SLinus Torvalds 			goto out;
3010e1dbeda6SAndrew Morton 
30111da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
30121da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
30131da177e4SLinus Torvalds 
30142ab44f43SMel Gorman 			if (!populated_zone(zone))
30152ab44f43SMel Gorman 				continue;
30162ab44f43SMel Gorman 
3017adea02a1SWu Fengguang 			lru_pages += zone_reclaimable_pages(zone);
30182ab44f43SMel Gorman 
30192ab44f43SMel Gorman 			/*
30202ab44f43SMel Gorman 			 * If any zone is currently balanced then kswapd will
30212ab44f43SMel Gorman 			 * not call compaction as it is expected that the
30222ab44f43SMel Gorman 			 * necessary pages are already available.
30232ab44f43SMel Gorman 			 */
30242ab44f43SMel Gorman 			if (pgdat_needs_compaction &&
30252ab44f43SMel Gorman 					zone_watermark_ok(zone, order,
30262ab44f43SMel Gorman 						low_wmark_pages(zone),
30272ab44f43SMel Gorman 						*classzone_idx, 0))
30282ab44f43SMel Gorman 				pgdat_needs_compaction = false;
30291da177e4SLinus Torvalds 		}
30301da177e4SLinus Torvalds 
30311da177e4SLinus Torvalds 		/*
3032b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3033b7ea3c41SMel Gorman 		 * even in laptop mode.
3034b7ea3c41SMel Gorman 		 */
3035b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
3036b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3037b7ea3c41SMel Gorman 
3038b7ea3c41SMel Gorman 		/*
30391da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
30401da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
30411da177e4SLinus Torvalds 		 *
30421da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
30431da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
30441da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
30451da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
30461da177e4SLinus Torvalds 		 */
30471da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
30481da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
30491da177e4SLinus Torvalds 
3050f3fe6512SCon Kolivas 			if (!populated_zone(zone))
30511da177e4SLinus Torvalds 				continue;
30521da177e4SLinus Torvalds 
30536e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
30546e543d57SLisa Du 			    !zone_reclaimable(zone))
30551da177e4SLinus Torvalds 				continue;
30561da177e4SLinus Torvalds 
30571da177e4SLinus Torvalds 			sc.nr_scanned = 0;
30584e416953SBalbir Singh 
30590608f43dSAndrew Morton 			nr_soft_scanned = 0;
30600608f43dSAndrew Morton 			/*
30610608f43dSAndrew Morton 			 * Call soft limit reclaim before calling shrink_zone.
30620608f43dSAndrew Morton 			 */
30630608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
30640608f43dSAndrew Morton 							order, sc.gfp_mask,
30650608f43dSAndrew Morton 							&nr_soft_scanned);
30660608f43dSAndrew Morton 			sc.nr_reclaimed += nr_soft_reclaimed;
30670608f43dSAndrew Morton 
306832a4330dSRik van Riel 			/*
30697c954f6dSMel Gorman 			 * There should be no need to raise the scanning
30707c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
30717c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
30727c954f6dSMel Gorman 			 * efficiency.
307332a4330dSRik van Riel 			 */
30747c954f6dSMel Gorman 			if (kswapd_shrink_zone(zone, end_zone, &sc,
30757c954f6dSMel Gorman 					lru_pages, &nr_attempted))
3076b8e83b94SMel Gorman 				raise_priority = false;
3077b8e83b94SMel Gorman 		}
3078d7868daeSMel Gorman 
30795515061dSMel Gorman 		/*
30805515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
30815515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
30825515061dSMel Gorman 		 * able to safely make forward progress. Wake them
30835515061dSMel Gorman 		 */
30845515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
30855515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
30865515061dSMel Gorman 			wake_up(&pgdat->pfmemalloc_wait);
30875515061dSMel Gorman 
30881da177e4SLinus Torvalds 		/*
3089b8e83b94SMel Gorman 		 * Fragmentation may mean that the system cannot be rebalanced
3090b8e83b94SMel Gorman 		 * for high-order allocations in all zones. If twice the
3091b8e83b94SMel Gorman 		 * allocation size has been reclaimed and the zones are still
3092b8e83b94SMel Gorman 		 * not balanced then recheck the watermarks at order-0 to
3093b8e83b94SMel Gorman 		 * prevent kswapd reclaiming excessively. Assume that a
3094b8e83b94SMel Gorman 		 * process requested a high-order can direct reclaim/compact.
30951da177e4SLinus Torvalds 		 */
3096b8e83b94SMel Gorman 		if (order && sc.nr_reclaimed >= 2UL << order)
309773ce02e9SKOSAKI Motohiro 			order = sc.order = 0;
309873ce02e9SKOSAKI Motohiro 
3099b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3100b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3101b8e83b94SMel Gorman 			break;
3102b8e83b94SMel Gorman 
3103b8e83b94SMel Gorman 		/*
31042ab44f43SMel Gorman 		 * Compact if necessary and kswapd is reclaiming at least the
31052ab44f43SMel Gorman 		 * high watermark number of pages as requsted
31062ab44f43SMel Gorman 		 */
31072ab44f43SMel Gorman 		if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
31082ab44f43SMel Gorman 			compact_pgdat(pgdat, order);
31092ab44f43SMel Gorman 
31102ab44f43SMel Gorman 		/*
3111b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3112b8e83b94SMel Gorman 		 * progress in reclaiming pages
3113b8e83b94SMel Gorman 		 */
3114b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3115b8e83b94SMel Gorman 			sc.priority--;
31169aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3117b8e83b94SMel Gorman 		 !pgdat_balanced(pgdat, order, *classzone_idx));
31181da177e4SLinus Torvalds 
3119b8e83b94SMel Gorman out:
31200abdee2bSMel Gorman 	/*
31215515061dSMel Gorman 	 * Return the order we were reclaiming at so prepare_kswapd_sleep()
31220abdee2bSMel Gorman 	 * makes a decision on the order we were last reclaiming at. However,
31230abdee2bSMel Gorman 	 * if another caller entered the allocator slow path while kswapd
31240abdee2bSMel Gorman 	 * was awake, order will remain at the higher level
31250abdee2bSMel Gorman 	 */
3126dc83edd9SMel Gorman 	*classzone_idx = end_zone;
31270abdee2bSMel Gorman 	return order;
31281da177e4SLinus Torvalds }
31291da177e4SLinus Torvalds 
3130dc83edd9SMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3131f0bc0a60SKOSAKI Motohiro {
3132f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3133f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3134f0bc0a60SKOSAKI Motohiro 
3135f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3136f0bc0a60SKOSAKI Motohiro 		return;
3137f0bc0a60SKOSAKI Motohiro 
3138f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3139f0bc0a60SKOSAKI Motohiro 
3140f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
31415515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3142f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3143f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3144f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3145f0bc0a60SKOSAKI Motohiro 	}
3146f0bc0a60SKOSAKI Motohiro 
3147f0bc0a60SKOSAKI Motohiro 	/*
3148f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3149f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3150f0bc0a60SKOSAKI Motohiro 	 */
31515515061dSMel Gorman 	if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
3152f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3153f0bc0a60SKOSAKI Motohiro 
3154f0bc0a60SKOSAKI Motohiro 		/*
3155f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3156f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3157f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3158f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3159f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3160f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3161f0bc0a60SKOSAKI Motohiro 		 */
3162f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
31631c7e7f6cSAaditya Kumar 
316462997027SMel Gorman 		/*
316562997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
316662997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
316762997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
316862997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
316962997027SMel Gorman 		 */
317062997027SMel Gorman 		reset_isolation_suitable(pgdat);
317162997027SMel Gorman 
31721c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3173f0bc0a60SKOSAKI Motohiro 			schedule();
31741c7e7f6cSAaditya Kumar 
3175f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3176f0bc0a60SKOSAKI Motohiro 	} else {
3177f0bc0a60SKOSAKI Motohiro 		if (remaining)
3178f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3179f0bc0a60SKOSAKI Motohiro 		else
3180f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3181f0bc0a60SKOSAKI Motohiro 	}
3182f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3183f0bc0a60SKOSAKI Motohiro }
3184f0bc0a60SKOSAKI Motohiro 
31851da177e4SLinus Torvalds /*
31861da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
31871da177e4SLinus Torvalds  * from the init process.
31881da177e4SLinus Torvalds  *
31891da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
31901da177e4SLinus Torvalds  * free memory available even if there is no other activity
31911da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
31921da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
31931da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
31941da177e4SLinus Torvalds  *
31951da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
31961da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
31971da177e4SLinus Torvalds  */
31981da177e4SLinus Torvalds static int kswapd(void *p)
31991da177e4SLinus Torvalds {
3200215ddd66SMel Gorman 	unsigned long order, new_order;
3201d2ebd0f6SAlex,Shi 	unsigned balanced_order;
3202215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3203d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
32041da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
32051da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3206f0bc0a60SKOSAKI Motohiro 
32071da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
32081da177e4SLinus Torvalds 		.reclaimed_slab = 0,
32091da177e4SLinus Torvalds 	};
3210a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
32111da177e4SLinus Torvalds 
3212cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3213cf40bd16SNick Piggin 
3214174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3215c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
32161da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
32171da177e4SLinus Torvalds 
32181da177e4SLinus Torvalds 	/*
32191da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
32201da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
32211da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
32221da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
32231da177e4SLinus Torvalds 	 *
32241da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
32251da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
32261da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
32271da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
32281da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
32291da177e4SLinus Torvalds 	 */
3230930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
323183144186SRafael J. Wysocki 	set_freezable();
32321da177e4SLinus Torvalds 
3233215ddd66SMel Gorman 	order = new_order = 0;
3234d2ebd0f6SAlex,Shi 	balanced_order = 0;
3235215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3236d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
32371da177e4SLinus Torvalds 	for ( ; ; ) {
32386f6313d4SJeff Liu 		bool ret;
32393e1d1d28SChristoph Lameter 
3240215ddd66SMel Gorman 		/*
3241215ddd66SMel Gorman 		 * If the last balance_pgdat was unsuccessful it's unlikely a
3242215ddd66SMel Gorman 		 * new request of a similar or harder type will succeed soon
3243215ddd66SMel Gorman 		 * so consider going to sleep on the basis we reclaimed at
3244215ddd66SMel Gorman 		 */
3245d2ebd0f6SAlex,Shi 		if (balanced_classzone_idx >= new_classzone_idx &&
3246d2ebd0f6SAlex,Shi 					balanced_order == new_order) {
32471da177e4SLinus Torvalds 			new_order = pgdat->kswapd_max_order;
324899504748SMel Gorman 			new_classzone_idx = pgdat->classzone_idx;
32491da177e4SLinus Torvalds 			pgdat->kswapd_max_order =  0;
3250215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
3251215ddd66SMel Gorman 		}
3252215ddd66SMel Gorman 
325399504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
32541da177e4SLinus Torvalds 			/*
32551da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
325699504748SMel Gorman 			 * allocation or has tigher zone constraints
32571da177e4SLinus Torvalds 			 */
32581da177e4SLinus Torvalds 			order = new_order;
325999504748SMel Gorman 			classzone_idx = new_classzone_idx;
32601da177e4SLinus Torvalds 		} else {
3261d2ebd0f6SAlex,Shi 			kswapd_try_to_sleep(pgdat, balanced_order,
3262d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
32631da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
326499504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3265f0dfcde0SAlex,Shi 			new_order = order;
3266f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
32674d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3268215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
32691da177e4SLinus Torvalds 		}
32701da177e4SLinus Torvalds 
32718fe23e05SDavid Rientjes 		ret = try_to_freeze();
32728fe23e05SDavid Rientjes 		if (kthread_should_stop())
32738fe23e05SDavid Rientjes 			break;
32748fe23e05SDavid Rientjes 
32758fe23e05SDavid Rientjes 		/*
32768fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
32778fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3278b1296cc4SRafael J. Wysocki 		 */
327933906bc5SMel Gorman 		if (!ret) {
328033906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3281d2ebd0f6SAlex,Shi 			balanced_classzone_idx = classzone_idx;
3282d2ebd0f6SAlex,Shi 			balanced_order = balance_pgdat(pgdat, order,
3283d2ebd0f6SAlex,Shi 						&balanced_classzone_idx);
32841da177e4SLinus Torvalds 		}
328533906bc5SMel Gorman 	}
3286b0a8cc58STakamori Yamaguchi 
3287b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
32881da177e4SLinus Torvalds 	return 0;
32891da177e4SLinus Torvalds }
32901da177e4SLinus Torvalds 
32911da177e4SLinus Torvalds /*
32921da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
32931da177e4SLinus Torvalds  */
329499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
32951da177e4SLinus Torvalds {
32961da177e4SLinus Torvalds 	pg_data_t *pgdat;
32971da177e4SLinus Torvalds 
3298f3fe6512SCon Kolivas 	if (!populated_zone(zone))
32991da177e4SLinus Torvalds 		return;
33001da177e4SLinus Torvalds 
330102a0e53dSPaul Jackson 	if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
33021da177e4SLinus Torvalds 		return;
330388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
330499504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
330588f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
330699504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
330799504748SMel Gorman 	}
33088d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
33091da177e4SLinus Torvalds 		return;
3310892f795dSJohannes Weiner 	if (zone_balanced(zone, order, 0, 0))
331188f5acf8SMel Gorman 		return;
331288f5acf8SMel Gorman 
331388f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
33148d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
33151da177e4SLinus Torvalds }
33161da177e4SLinus Torvalds 
3317c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
33181da177e4SLinus Torvalds /*
33197b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3320d6277db4SRafael J. Wysocki  * freed pages.
3321d6277db4SRafael J. Wysocki  *
3322d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3323d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3324d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
33251da177e4SLinus Torvalds  */
33267b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
33271da177e4SLinus Torvalds {
3328d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3329d6277db4SRafael J. Wysocki 	struct scan_control sc = {
33307b51755cSKOSAKI Motohiro 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
33317b51755cSKOSAKI Motohiro 		.may_swap = 1,
33327b51755cSKOSAKI Motohiro 		.may_unmap = 1,
3333d6277db4SRafael J. Wysocki 		.may_writepage = 1,
33347b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
33357b51755cSKOSAKI Motohiro 		.hibernation_mode = 1,
33367b51755cSKOSAKI Motohiro 		.order = 0,
33379e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
33381da177e4SLinus Torvalds 	};
33397b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
33407b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
33417b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
33421da177e4SLinus Torvalds 
33437b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
33447b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3345d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
33467b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3347d6277db4SRafael J. Wysocki 
33483115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3349d6277db4SRafael J. Wysocki 
33507b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
33517b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
33527b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3353d6277db4SRafael J. Wysocki 
33547b51755cSKOSAKI Motohiro 	return nr_reclaimed;
33551da177e4SLinus Torvalds }
3356c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
33571da177e4SLinus Torvalds 
33581da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
33591da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
33601da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
33611da177e4SLinus Torvalds    restore their cpu bindings. */
3362fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3363fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
33641da177e4SLinus Torvalds {
336558c0a4a7SYasunori Goto 	int nid;
33661da177e4SLinus Torvalds 
33678bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
336848fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3369c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3370a70f7302SRusty Russell 			const struct cpumask *mask;
3371a70f7302SRusty Russell 
3372a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3373c5f59f08SMike Travis 
33743e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
33751da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3376c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
33771da177e4SLinus Torvalds 		}
33781da177e4SLinus Torvalds 	}
33791da177e4SLinus Torvalds 	return NOTIFY_OK;
33801da177e4SLinus Torvalds }
33811da177e4SLinus Torvalds 
33823218ae14SYasunori Goto /*
33833218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
33843218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
33853218ae14SYasunori Goto  */
33863218ae14SYasunori Goto int kswapd_run(int nid)
33873218ae14SYasunori Goto {
33883218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
33893218ae14SYasunori Goto 	int ret = 0;
33903218ae14SYasunori Goto 
33913218ae14SYasunori Goto 	if (pgdat->kswapd)
33923218ae14SYasunori Goto 		return 0;
33933218ae14SYasunori Goto 
33943218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
33953218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
33963218ae14SYasunori Goto 		/* failure at boot is fatal */
33973218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3398d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3399d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3400d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
34013218ae14SYasunori Goto 	}
34023218ae14SYasunori Goto 	return ret;
34033218ae14SYasunori Goto }
34043218ae14SYasunori Goto 
34058fe23e05SDavid Rientjes /*
3406d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3407d8adde17SJiang Liu  * hold lock_memory_hotplug().
34088fe23e05SDavid Rientjes  */
34098fe23e05SDavid Rientjes void kswapd_stop(int nid)
34108fe23e05SDavid Rientjes {
34118fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
34128fe23e05SDavid Rientjes 
3413d8adde17SJiang Liu 	if (kswapd) {
34148fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3415d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3416d8adde17SJiang Liu 	}
34178fe23e05SDavid Rientjes }
34188fe23e05SDavid Rientjes 
34191da177e4SLinus Torvalds static int __init kswapd_init(void)
34201da177e4SLinus Torvalds {
34213218ae14SYasunori Goto 	int nid;
342269e05944SAndrew Morton 
34231da177e4SLinus Torvalds 	swap_setup();
342448fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
34253218ae14SYasunori Goto  		kswapd_run(nid);
34261da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
34271da177e4SLinus Torvalds 	return 0;
34281da177e4SLinus Torvalds }
34291da177e4SLinus Torvalds 
34301da177e4SLinus Torvalds module_init(kswapd_init)
34319eeff239SChristoph Lameter 
34329eeff239SChristoph Lameter #ifdef CONFIG_NUMA
34339eeff239SChristoph Lameter /*
34349eeff239SChristoph Lameter  * Zone reclaim mode
34359eeff239SChristoph Lameter  *
34369eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
34379eeff239SChristoph Lameter  * the watermarks.
34389eeff239SChristoph Lameter  */
34399eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
34409eeff239SChristoph Lameter 
34411b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
34427d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
34431b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
34441b2ffb78SChristoph Lameter #define RECLAIM_SWAP (1<<2)	/* Swap pages out during reclaim */
34451b2ffb78SChristoph Lameter 
34469eeff239SChristoph Lameter /*
3447a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3448a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3449a92f7126SChristoph Lameter  * a zone.
3450a92f7126SChristoph Lameter  */
3451a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3452a92f7126SChristoph Lameter 
34539eeff239SChristoph Lameter /*
34549614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
34559614634fSChristoph Lameter  * occur.
34569614634fSChristoph Lameter  */
34579614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
34589614634fSChristoph Lameter 
34599614634fSChristoph Lameter /*
34600ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
34610ff38490SChristoph Lameter  * slab reclaim needs to occur.
34620ff38490SChristoph Lameter  */
34630ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
34640ff38490SChristoph Lameter 
346590afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
346690afa5deSMel Gorman {
346790afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
346890afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
346990afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
347090afa5deSMel Gorman 
347190afa5deSMel Gorman 	/*
347290afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
347390afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
347490afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
347590afa5deSMel Gorman 	 */
347690afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
347790afa5deSMel Gorman }
347890afa5deSMel Gorman 
347990afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
348090afa5deSMel Gorman static long zone_pagecache_reclaimable(struct zone *zone)
348190afa5deSMel Gorman {
348290afa5deSMel Gorman 	long nr_pagecache_reclaimable;
348390afa5deSMel Gorman 	long delta = 0;
348490afa5deSMel Gorman 
348590afa5deSMel Gorman 	/*
348690afa5deSMel Gorman 	 * If RECLAIM_SWAP is set, then all file pages are considered
348790afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
348890afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
348990afa5deSMel Gorman 	 * a better estimate
349090afa5deSMel Gorman 	 */
349190afa5deSMel Gorman 	if (zone_reclaim_mode & RECLAIM_SWAP)
349290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
349390afa5deSMel Gorman 	else
349490afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
349590afa5deSMel Gorman 
349690afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
349790afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
349890afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
349990afa5deSMel Gorman 
350090afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
350190afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
350290afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
350390afa5deSMel Gorman 
350490afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
350590afa5deSMel Gorman }
350690afa5deSMel Gorman 
35070ff38490SChristoph Lameter /*
35089eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
35099eeff239SChristoph Lameter  */
3510179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
35119eeff239SChristoph Lameter {
35127fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
351369e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
35149eeff239SChristoph Lameter 	struct task_struct *p = current;
35159eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3516179e9639SAndrew Morton 	struct scan_control sc = {
3517179e9639SAndrew Morton 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3518a6dc60f8SJohannes Weiner 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
35192e2e4259SKOSAKI Motohiro 		.may_swap = 1,
352062b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
352121caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3522bd2f6199SJohannes Weiner 		.order = order,
35239e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3524179e9639SAndrew Morton 	};
3525a09ed5e0SYing Han 	struct shrink_control shrink = {
3526a09ed5e0SYing Han 		.gfp_mask = sc.gfp_mask,
3527a09ed5e0SYing Han 	};
352815748048SKOSAKI Motohiro 	unsigned long nr_slab_pages0, nr_slab_pages1;
35299eeff239SChristoph Lameter 
35309eeff239SChristoph Lameter 	cond_resched();
3531d4f7796eSChristoph Lameter 	/*
3532d4f7796eSChristoph Lameter 	 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3533d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
3534d4f7796eSChristoph Lameter 	 * and RECLAIM_SWAP.
3535d4f7796eSChristoph Lameter 	 */
3536d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
353776ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
35389eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
35399eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3540c84db23cSChristoph Lameter 
354190afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3542a92f7126SChristoph Lameter 		/*
35430ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
35440ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3545a92f7126SChristoph Lameter 		 */
3546a92f7126SChristoph Lameter 		do {
35479e3b2f8cSKonstantin Khlebnikov 			shrink_zone(zone, &sc);
35489e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
35490ff38490SChristoph Lameter 	}
3550a92f7126SChristoph Lameter 
355115748048SKOSAKI Motohiro 	nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
355215748048SKOSAKI Motohiro 	if (nr_slab_pages0 > zone->min_slab_pages) {
35532a16e3f4SChristoph Lameter 		/*
35547fb2d46dSChristoph Lameter 		 * shrink_slab() does not currently allow us to determine how
35550ff38490SChristoph Lameter 		 * many pages were freed in this zone. So we take the current
35560ff38490SChristoph Lameter 		 * number of slab pages and shake the slab until it is reduced
35570ff38490SChristoph Lameter 		 * by the same nr_pages that we used for reclaiming unmapped
35580ff38490SChristoph Lameter 		 * pages.
35592a16e3f4SChristoph Lameter 		 */
35600ce3d744SDave Chinner 		nodes_clear(shrink.nodes_to_scan);
35610ce3d744SDave Chinner 		node_set(zone_to_nid(zone), shrink.nodes_to_scan);
35624dc4b3d9SKOSAKI Motohiro 		for (;;) {
35634dc4b3d9SKOSAKI Motohiro 			unsigned long lru_pages = zone_reclaimable_pages(zone);
35644dc4b3d9SKOSAKI Motohiro 
35654dc4b3d9SKOSAKI Motohiro 			/* No reclaimable slab or very low memory pressure */
35661495f230SYing Han 			if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
35674dc4b3d9SKOSAKI Motohiro 				break;
35684dc4b3d9SKOSAKI Motohiro 
35694dc4b3d9SKOSAKI Motohiro 			/* Freed enough memory */
35704dc4b3d9SKOSAKI Motohiro 			nr_slab_pages1 = zone_page_state(zone,
35714dc4b3d9SKOSAKI Motohiro 							NR_SLAB_RECLAIMABLE);
35724dc4b3d9SKOSAKI Motohiro 			if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
35734dc4b3d9SKOSAKI Motohiro 				break;
35744dc4b3d9SKOSAKI Motohiro 		}
357583e33a47SChristoph Lameter 
357683e33a47SChristoph Lameter 		/*
357783e33a47SChristoph Lameter 		 * Update nr_reclaimed by the number of slab pages we
357883e33a47SChristoph Lameter 		 * reclaimed from this zone.
357983e33a47SChristoph Lameter 		 */
358015748048SKOSAKI Motohiro 		nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
358115748048SKOSAKI Motohiro 		if (nr_slab_pages1 < nr_slab_pages0)
358215748048SKOSAKI Motohiro 			sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
35832a16e3f4SChristoph Lameter 	}
35842a16e3f4SChristoph Lameter 
35859eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3586d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
358776ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3588a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
35899eeff239SChristoph Lameter }
3590179e9639SAndrew Morton 
3591179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3592179e9639SAndrew Morton {
3593179e9639SAndrew Morton 	int node_id;
3594d773ed6bSDavid Rientjes 	int ret;
3595179e9639SAndrew Morton 
3596179e9639SAndrew Morton 	/*
35970ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
35980ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
359934aa1330SChristoph Lameter 	 *
36009614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
36019614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
36029614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
36039614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
36049614634fSChristoph Lameter 	 * unmapped file backed pages.
3605179e9639SAndrew Morton 	 */
360690afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
360790afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3608fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3609179e9639SAndrew Morton 
36106e543d57SLisa Du 	if (!zone_reclaimable(zone))
3611fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3612d773ed6bSDavid Rientjes 
3613179e9639SAndrew Morton 	/*
3614d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3615179e9639SAndrew Morton 	 */
3616d773ed6bSDavid Rientjes 	if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3617fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3618179e9639SAndrew Morton 
3619179e9639SAndrew Morton 	/*
3620179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3621179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3622179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3623179e9639SAndrew Morton 	 * as wide as possible.
3624179e9639SAndrew Morton 	 */
362589fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
362637c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3627fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3628d773ed6bSDavid Rientjes 
3629d773ed6bSDavid Rientjes 	if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3630fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3631fa5e084eSMel Gorman 
3632d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
3633d773ed6bSDavid Rientjes 	zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3634d773ed6bSDavid Rientjes 
363524cf7251SMel Gorman 	if (!ret)
363624cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
363724cf7251SMel Gorman 
3638d773ed6bSDavid Rientjes 	return ret;
3639179e9639SAndrew Morton }
36409eeff239SChristoph Lameter #endif
3641894bc310SLee Schermerhorn 
3642894bc310SLee Schermerhorn /*
3643894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3644894bc310SLee Schermerhorn  * @page: the page to test
3645894bc310SLee Schermerhorn  *
3646894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
364739b5f29aSHugh Dickins  * lists vs unevictable list.
3648894bc310SLee Schermerhorn  *
3649894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3650ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3651b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3652ba9ddf49SLee Schermerhorn  *
3653894bc310SLee Schermerhorn  */
365439b5f29aSHugh Dickins int page_evictable(struct page *page)
3655894bc310SLee Schermerhorn {
365639b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3657894bc310SLee Schermerhorn }
365889e004eaSLee Schermerhorn 
365985046579SHugh Dickins #ifdef CONFIG_SHMEM
366089e004eaSLee Schermerhorn /**
366124513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
366224513264SHugh Dickins  * @pages:	array of pages to check
366324513264SHugh Dickins  * @nr_pages:	number of pages to check
366489e004eaSLee Schermerhorn  *
366524513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
366685046579SHugh Dickins  *
366785046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
366889e004eaSLee Schermerhorn  */
366924513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
367089e004eaSLee Schermerhorn {
3671925b7673SJohannes Weiner 	struct lruvec *lruvec;
367224513264SHugh Dickins 	struct zone *zone = NULL;
367324513264SHugh Dickins 	int pgscanned = 0;
367424513264SHugh Dickins 	int pgrescued = 0;
367589e004eaSLee Schermerhorn 	int i;
367689e004eaSLee Schermerhorn 
367724513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
367824513264SHugh Dickins 		struct page *page = pages[i];
367924513264SHugh Dickins 		struct zone *pagezone;
368089e004eaSLee Schermerhorn 
368124513264SHugh Dickins 		pgscanned++;
368224513264SHugh Dickins 		pagezone = page_zone(page);
368389e004eaSLee Schermerhorn 		if (pagezone != zone) {
368489e004eaSLee Schermerhorn 			if (zone)
368589e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
368689e004eaSLee Schermerhorn 			zone = pagezone;
368789e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
368889e004eaSLee Schermerhorn 		}
3689fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
369089e004eaSLee Schermerhorn 
369124513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
369224513264SHugh Dickins 			continue;
369389e004eaSLee Schermerhorn 
369439b5f29aSHugh Dickins 		if (page_evictable(page)) {
369524513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
369624513264SHugh Dickins 
3697309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
369824513264SHugh Dickins 			ClearPageUnevictable(page);
3699fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3700fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
370124513264SHugh Dickins 			pgrescued++;
370289e004eaSLee Schermerhorn 		}
370389e004eaSLee Schermerhorn 	}
370424513264SHugh Dickins 
370524513264SHugh Dickins 	if (zone) {
370624513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
370724513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
370824513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
370924513264SHugh Dickins 	}
371085046579SHugh Dickins }
371185046579SHugh Dickins #endif /* CONFIG_SHMEM */
3712af936a16SLee Schermerhorn 
3713264e56d8SJohannes Weiner static void warn_scan_unevictable_pages(void)
3714af936a16SLee Schermerhorn {
3715264e56d8SJohannes Weiner 	printk_once(KERN_WARNING
371625bd91bdSKOSAKI Motohiro 		    "%s: The scan_unevictable_pages sysctl/node-interface has been "
3717264e56d8SJohannes Weiner 		    "disabled for lack of a legitimate use case.  If you have "
371825bd91bdSKOSAKI Motohiro 		    "one, please send an email to linux-mm@kvack.org.\n",
371925bd91bdSKOSAKI Motohiro 		    current->comm);
3720af936a16SLee Schermerhorn }
3721af936a16SLee Schermerhorn 
3722af936a16SLee Schermerhorn /*
3723af936a16SLee Schermerhorn  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3724af936a16SLee Schermerhorn  * all nodes' unevictable lists for evictable pages
3725af936a16SLee Schermerhorn  */
3726af936a16SLee Schermerhorn unsigned long scan_unevictable_pages;
3727af936a16SLee Schermerhorn 
3728af936a16SLee Schermerhorn int scan_unevictable_handler(struct ctl_table *table, int write,
37298d65af78SAlexey Dobriyan 			   void __user *buffer,
3730af936a16SLee Schermerhorn 			   size_t *length, loff_t *ppos)
3731af936a16SLee Schermerhorn {
3732264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
37338d65af78SAlexey Dobriyan 	proc_doulongvec_minmax(table, write, buffer, length, ppos);
3734af936a16SLee Schermerhorn 	scan_unevictable_pages = 0;
3735af936a16SLee Schermerhorn 	return 0;
3736af936a16SLee Schermerhorn }
3737af936a16SLee Schermerhorn 
3738e4455abbSThadeu Lima de Souza Cascardo #ifdef CONFIG_NUMA
3739af936a16SLee Schermerhorn /*
3740af936a16SLee Schermerhorn  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3741af936a16SLee Schermerhorn  * a specified node's per zone unevictable lists for evictable pages.
3742af936a16SLee Schermerhorn  */
3743af936a16SLee Schermerhorn 
374410fbcf4cSKay Sievers static ssize_t read_scan_unevictable_node(struct device *dev,
374510fbcf4cSKay Sievers 					  struct device_attribute *attr,
3746af936a16SLee Schermerhorn 					  char *buf)
3747af936a16SLee Schermerhorn {
3748264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3749af936a16SLee Schermerhorn 	return sprintf(buf, "0\n");	/* always zero; should fit... */
3750af936a16SLee Schermerhorn }
3751af936a16SLee Schermerhorn 
375210fbcf4cSKay Sievers static ssize_t write_scan_unevictable_node(struct device *dev,
375310fbcf4cSKay Sievers 					   struct device_attribute *attr,
3754af936a16SLee Schermerhorn 					const char *buf, size_t count)
3755af936a16SLee Schermerhorn {
3756264e56d8SJohannes Weiner 	warn_scan_unevictable_pages();
3757af936a16SLee Schermerhorn 	return 1;
3758af936a16SLee Schermerhorn }
3759af936a16SLee Schermerhorn 
3760af936a16SLee Schermerhorn 
376110fbcf4cSKay Sievers static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3762af936a16SLee Schermerhorn 			read_scan_unevictable_node,
3763af936a16SLee Schermerhorn 			write_scan_unevictable_node);
3764af936a16SLee Schermerhorn 
3765af936a16SLee Schermerhorn int scan_unevictable_register_node(struct node *node)
3766af936a16SLee Schermerhorn {
376710fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3768af936a16SLee Schermerhorn }
3769af936a16SLee Schermerhorn 
3770af936a16SLee Schermerhorn void scan_unevictable_unregister_node(struct node *node)
3771af936a16SLee Schermerhorn {
377210fbcf4cSKay Sievers 	device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3773af936a16SLee Schermerhorn }
3774e4455abbSThadeu Lima de Souza Cascardo #endif
3775