xref: /openbmc/linux/mm/vmscan.c (revision accf62422b3a67fce8ce086aa81c8300ddbf42be)
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 
14b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15b1de0d13SMitchel Humpherys 
161da177e4SLinus Torvalds #include <linux/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
47268bb0ceSLinus Torvalds #include <linux/prefetch.h>
48b1de0d13SMitchel Humpherys #include <linux/printk.h>
49f9fe48beSRoss Zwisler #include <linux/dax.h>
501da177e4SLinus Torvalds 
511da177e4SLinus Torvalds #include <asm/tlbflush.h>
521da177e4SLinus Torvalds #include <asm/div64.h>
531da177e4SLinus Torvalds 
541da177e4SLinus Torvalds #include <linux/swapops.h>
55117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
561da177e4SLinus Torvalds 
570f8053a5SNick Piggin #include "internal.h"
580f8053a5SNick Piggin 
5933906bc5SMel Gorman #define CREATE_TRACE_POINTS
6033906bc5SMel Gorman #include <trace/events/vmscan.h>
6133906bc5SMel Gorman 
621da177e4SLinus Torvalds struct scan_control {
6322fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6422fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6522fba335SKOSAKI Motohiro 
661da177e4SLinus Torvalds 	/* This context's GFP mask */
676daa0e28SAl Viro 	gfp_t gfp_mask;
681da177e4SLinus Torvalds 
69ee814fe2SJohannes Weiner 	/* Allocation order */
705ad333ebSAndy Whitcroft 	int order;
7166e1707bSBalbir Singh 
72ee814fe2SJohannes Weiner 	/*
73ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
74ee814fe2SJohannes Weiner 	 * are scanned.
75ee814fe2SJohannes Weiner 	 */
76ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
779e3b2f8cSKonstantin Khlebnikov 
785f53e762SKOSAKI Motohiro 	/*
79f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
80f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
81f16015fbSJohannes Weiner 	 */
82f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8366e1707bSBalbir Singh 
84ee814fe2SJohannes Weiner 	/* Scan (total_size >> priority) pages at once */
85ee814fe2SJohannes Weiner 	int priority;
86ee814fe2SJohannes Weiner 
87ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
88ee814fe2SJohannes Weiner 
89ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
90ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
91ee814fe2SJohannes Weiner 
92ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
93ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
94ee814fe2SJohannes Weiner 
95241994edSJohannes Weiner 	/* Can cgroups be reclaimed below their normal consumption range? */
96241994edSJohannes Weiner 	unsigned int may_thrash:1;
97241994edSJohannes Weiner 
98ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
99ee814fe2SJohannes Weiner 
100ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
101ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
102ee814fe2SJohannes Weiner 
103ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
104ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
105ee814fe2SJohannes Weiner 
106ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
107ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1081da177e4SLinus Torvalds };
1091da177e4SLinus Torvalds 
1101da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1111da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1121da177e4SLinus Torvalds 	do {								\
1131da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1141da177e4SLinus Torvalds 			struct page *prev;				\
1151da177e4SLinus Torvalds 									\
1161da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1171da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1181da177e4SLinus Torvalds 		}							\
1191da177e4SLinus Torvalds 	} while (0)
1201da177e4SLinus Torvalds #else
1211da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1221da177e4SLinus Torvalds #endif
1231da177e4SLinus Torvalds 
1241da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1251da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1261da177e4SLinus Torvalds 	do {								\
1271da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1281da177e4SLinus Torvalds 			struct page *prev;				\
1291da177e4SLinus Torvalds 									\
1301da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1311da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1321da177e4SLinus Torvalds 		}							\
1331da177e4SLinus Torvalds 	} while (0)
1341da177e4SLinus Torvalds #else
1351da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1361da177e4SLinus Torvalds #endif
1371da177e4SLinus Torvalds 
1381da177e4SLinus Torvalds /*
1391da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1401da177e4SLinus Torvalds  */
1411da177e4SLinus Torvalds int vm_swappiness = 60;
142d0480be4SWang Sheng-Hui /*
143d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
144d0480be4SWang Sheng-Hui  * zones.
145d0480be4SWang Sheng-Hui  */
146d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1471da177e4SLinus Torvalds 
1481da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1491da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1501da177e4SLinus Torvalds 
151c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15289b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15389b5fae5SJohannes Weiner {
154f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
15589b5fae5SJohannes Weiner }
15697c9341fSTejun Heo 
15797c9341fSTejun Heo /**
15897c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
15997c9341fSTejun Heo  * @sc: scan_control in question
16097c9341fSTejun Heo  *
16197c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
16297c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
16397c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
16497c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
16597c9341fSTejun Heo  * allocation and configurability.
16697c9341fSTejun Heo  *
16797c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
16897c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
16997c9341fSTejun Heo  */
17097c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
17197c9341fSTejun Heo {
17297c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
17397c9341fSTejun Heo 
17497c9341fSTejun Heo 	if (!memcg)
17597c9341fSTejun Heo 		return true;
17697c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
17769234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
17897c9341fSTejun Heo 		return true;
17997c9341fSTejun Heo #endif
18097c9341fSTejun Heo 	return false;
18197c9341fSTejun Heo }
18291a45470SKAMEZAWA Hiroyuki #else
18389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
18489b5fae5SJohannes Weiner {
18589b5fae5SJohannes Weiner 	return true;
18689b5fae5SJohannes Weiner }
18797c9341fSTejun Heo 
18897c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
18997c9341fSTejun Heo {
19097c9341fSTejun Heo 	return true;
19197c9341fSTejun Heo }
19291a45470SKAMEZAWA Hiroyuki #endif
19391a45470SKAMEZAWA Hiroyuki 
194a1c3bfb2SJohannes Weiner static unsigned long zone_reclaimable_pages(struct zone *zone)
1956e543d57SLisa Du {
196d031a157SAlexandru Moise 	unsigned long nr;
1976e543d57SLisa Du 
1980db2cb8dSMichal Hocko 	nr = zone_page_state_snapshot(zone, NR_ACTIVE_FILE) +
1990db2cb8dSMichal Hocko 	     zone_page_state_snapshot(zone, NR_INACTIVE_FILE) +
2000db2cb8dSMichal Hocko 	     zone_page_state_snapshot(zone, NR_ISOLATED_FILE);
2016e543d57SLisa Du 
2026e543d57SLisa Du 	if (get_nr_swap_pages() > 0)
2030db2cb8dSMichal Hocko 		nr += zone_page_state_snapshot(zone, NR_ACTIVE_ANON) +
2040db2cb8dSMichal Hocko 		      zone_page_state_snapshot(zone, NR_INACTIVE_ANON) +
2050db2cb8dSMichal Hocko 		      zone_page_state_snapshot(zone, NR_ISOLATED_ANON);
2066e543d57SLisa Du 
2076e543d57SLisa Du 	return nr;
2086e543d57SLisa Du }
2096e543d57SLisa Du 
2106e543d57SLisa Du bool zone_reclaimable(struct zone *zone)
2116e543d57SLisa Du {
2120db2cb8dSMichal Hocko 	return zone_page_state_snapshot(zone, NR_PAGES_SCANNED) <
2130d5d823aSMel Gorman 		zone_reclaimable_pages(zone) * 6;
2146e543d57SLisa Du }
2156e543d57SLisa Du 
21623047a96SJohannes Weiner unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
217c9f299d9SKOSAKI Motohiro {
218c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2194d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
220a3d8e054SKOSAKI Motohiro 
221074291feSKonstantin Khlebnikov 	return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
222c9f299d9SKOSAKI Motohiro }
223c9f299d9SKOSAKI Motohiro 
2241da177e4SLinus Torvalds /*
2251d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2261da177e4SLinus Torvalds  */
2271d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2281da177e4SLinus Torvalds {
2291d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2301d3d4437SGlauber Costa 
2311d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2321d3d4437SGlauber Costa 		size *= nr_node_ids;
2331d3d4437SGlauber Costa 
2341d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2351d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2361d3d4437SGlauber Costa 		return -ENOMEM;
2371d3d4437SGlauber Costa 
2381da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2391da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2401da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2411d3d4437SGlauber Costa 	return 0;
2421da177e4SLinus Torvalds }
2438e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2441da177e4SLinus Torvalds 
2451da177e4SLinus Torvalds /*
2461da177e4SLinus Torvalds  * Remove one
2471da177e4SLinus Torvalds  */
2488e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2491da177e4SLinus Torvalds {
2501da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2511da177e4SLinus Torvalds 	list_del(&shrinker->list);
2521da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
253ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2541da177e4SLinus Torvalds }
2558e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2561da177e4SLinus Torvalds 
2571da177e4SLinus Torvalds #define SHRINK_BATCH 128
2581d3d4437SGlauber Costa 
259cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2606b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2616b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2626b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2631da177e4SLinus Torvalds {
26424f7c6b9SDave Chinner 	unsigned long freed = 0;
2651da177e4SLinus Torvalds 	unsigned long long delta;
266635697c6SKonstantin Khlebnikov 	long total_scan;
267d5bc5fd3SVladimir Davydov 	long freeable;
268acf92b48SDave Chinner 	long nr;
269acf92b48SDave Chinner 	long new_nr;
2701d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
271e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
272e9299f50SDave Chinner 					  : SHRINK_BATCH;
2731da177e4SLinus Torvalds 
274d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
275d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2761d3d4437SGlauber Costa 		return 0;
277635697c6SKonstantin Khlebnikov 
278acf92b48SDave Chinner 	/*
279acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
280acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
281acf92b48SDave Chinner 	 * don't also do this scanning work.
282acf92b48SDave Chinner 	 */
2831d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
284acf92b48SDave Chinner 
285acf92b48SDave Chinner 	total_scan = nr;
2866b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
287d5bc5fd3SVladimir Davydov 	delta *= freeable;
2886b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
289acf92b48SDave Chinner 	total_scan += delta;
290acf92b48SDave Chinner 	if (total_scan < 0) {
2918612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
292a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
293d5bc5fd3SVladimir Davydov 		total_scan = freeable;
294ea164d73SAndrea Arcangeli 	}
295ea164d73SAndrea Arcangeli 
296ea164d73SAndrea Arcangeli 	/*
2973567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
2983567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
2993567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3003567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3013567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
302d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3033567b59aSDave Chinner 	 * memory.
3043567b59aSDave Chinner 	 *
3053567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3063567b59aSDave Chinner 	 * a large delta change is calculated directly.
3073567b59aSDave Chinner 	 */
308d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
309d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3103567b59aSDave Chinner 
3113567b59aSDave Chinner 	/*
312ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
313ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
314ea164d73SAndrea Arcangeli 	 * freeable entries.
315ea164d73SAndrea Arcangeli 	 */
316d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
317d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3181da177e4SLinus Torvalds 
31924f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3206b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
321d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
32209576073SDave Chinner 
3230b1fb40aSVladimir Davydov 	/*
3240b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3250b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3260b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3270b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3280b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3290b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3300b1fb40aSVladimir Davydov 	 * batch_size.
3310b1fb40aSVladimir Davydov 	 *
3320b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3330b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
334d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3350b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3360b1fb40aSVladimir Davydov 	 * possible.
3370b1fb40aSVladimir Davydov 	 */
3380b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
339d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
34024f7c6b9SDave Chinner 		unsigned long ret;
3410b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3421da177e4SLinus Torvalds 
3430b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
34424f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
34524f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3461da177e4SLinus Torvalds 			break;
34724f7c6b9SDave Chinner 		freed += ret;
34824f7c6b9SDave Chinner 
3490b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3500b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3511da177e4SLinus Torvalds 
3521da177e4SLinus Torvalds 		cond_resched();
3531da177e4SLinus Torvalds 	}
3541da177e4SLinus Torvalds 
355acf92b48SDave Chinner 	/*
356acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
357acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
358acf92b48SDave Chinner 	 * scan, there is no need to do an update.
359acf92b48SDave Chinner 	 */
36083aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
36183aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3621d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
36383aeeadaSKonstantin Khlebnikov 	else
3641d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
365acf92b48SDave Chinner 
366df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3671d3d4437SGlauber Costa 	return freed;
3681d3d4437SGlauber Costa }
3691d3d4437SGlauber Costa 
3706b4f7799SJohannes Weiner /**
371cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
3726b4f7799SJohannes Weiner  * @gfp_mask: allocation context
3736b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
374cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
3756b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
3766b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
3771d3d4437SGlauber Costa  *
3786b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
3791d3d4437SGlauber Costa  *
3806b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
3816b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
3821d3d4437SGlauber Costa  *
383cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
384cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
385cb731d6cSVladimir Davydov  * objects from the memory cgroup specified. Otherwise all shrinkers
386cb731d6cSVladimir Davydov  * are called, and memcg aware shrinkers are supposed to scan the
387cb731d6cSVladimir Davydov  * global list then.
388cb731d6cSVladimir Davydov  *
3896b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
3906b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
3916b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
3926b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
3936b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
3946b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
3956b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
3961d3d4437SGlauber Costa  *
3976b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
3981d3d4437SGlauber Costa  */
399cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
400cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4016b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4026b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4031d3d4437SGlauber Costa {
4041d3d4437SGlauber Costa 	struct shrinker *shrinker;
4051d3d4437SGlauber Costa 	unsigned long freed = 0;
4061d3d4437SGlauber Costa 
407567e9ab2SJohannes Weiner 	if (memcg && !memcg_kmem_online(memcg))
408cb731d6cSVladimir Davydov 		return 0;
409cb731d6cSVladimir Davydov 
4106b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4116b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4121d3d4437SGlauber Costa 
4131d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4141d3d4437SGlauber Costa 		/*
4151d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4161d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4171d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4181d3d4437SGlauber Costa 		 * time.
4191d3d4437SGlauber Costa 		 */
4201d3d4437SGlauber Costa 		freed = 1;
4211d3d4437SGlauber Costa 		goto out;
4221d3d4437SGlauber Costa 	}
4231d3d4437SGlauber Costa 
4241d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4256b4f7799SJohannes Weiner 		struct shrink_control sc = {
4266b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4276b4f7799SJohannes Weiner 			.nid = nid,
428cb731d6cSVladimir Davydov 			.memcg = memcg,
4296b4f7799SJohannes Weiner 		};
4306b4f7799SJohannes Weiner 
431cb731d6cSVladimir Davydov 		if (memcg && !(shrinker->flags & SHRINKER_MEMCG_AWARE))
432cb731d6cSVladimir Davydov 			continue;
433cb731d6cSVladimir Davydov 
4346b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4356b4f7799SJohannes Weiner 			sc.nid = 0;
4366b4f7799SJohannes Weiner 
437cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
438ec97097bSVladimir Davydov 	}
4391d3d4437SGlauber Costa 
4401da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
441f06590bdSMinchan Kim out:
442f06590bdSMinchan Kim 	cond_resched();
44324f7c6b9SDave Chinner 	return freed;
4441da177e4SLinus Torvalds }
4451da177e4SLinus Torvalds 
446cb731d6cSVladimir Davydov void drop_slab_node(int nid)
447cb731d6cSVladimir Davydov {
448cb731d6cSVladimir Davydov 	unsigned long freed;
449cb731d6cSVladimir Davydov 
450cb731d6cSVladimir Davydov 	do {
451cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
452cb731d6cSVladimir Davydov 
453cb731d6cSVladimir Davydov 		freed = 0;
454cb731d6cSVladimir Davydov 		do {
455cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
456cb731d6cSVladimir Davydov 					     1000, 1000);
457cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
458cb731d6cSVladimir Davydov 	} while (freed > 10);
459cb731d6cSVladimir Davydov }
460cb731d6cSVladimir Davydov 
461cb731d6cSVladimir Davydov void drop_slab(void)
462cb731d6cSVladimir Davydov {
463cb731d6cSVladimir Davydov 	int nid;
464cb731d6cSVladimir Davydov 
465cb731d6cSVladimir Davydov 	for_each_online_node(nid)
466cb731d6cSVladimir Davydov 		drop_slab_node(nid);
467cb731d6cSVladimir Davydov }
468cb731d6cSVladimir Davydov 
4691da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4701da177e4SLinus Torvalds {
471ceddc3a5SJohannes Weiner 	/*
472ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
473ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
474ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
475ceddc3a5SJohannes Weiner 	 */
476edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
4771da177e4SLinus Torvalds }
4781da177e4SLinus Torvalds 
479703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
4801da177e4SLinus Torvalds {
481930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
4821da177e4SLinus Torvalds 		return 1;
483703c2708STejun Heo 	if (!inode_write_congested(inode))
4841da177e4SLinus Torvalds 		return 1;
485703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
4861da177e4SLinus Torvalds 		return 1;
4871da177e4SLinus Torvalds 	return 0;
4881da177e4SLinus Torvalds }
4891da177e4SLinus Torvalds 
4901da177e4SLinus Torvalds /*
4911da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
4921da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
4931da177e4SLinus Torvalds  * fsync(), msync() or close().
4941da177e4SLinus Torvalds  *
4951da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
4961da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
4971da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
4981da177e4SLinus Torvalds  *
4991da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5001da177e4SLinus Torvalds  * __GFP_FS.
5011da177e4SLinus Torvalds  */
5021da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5031da177e4SLinus Torvalds 				struct page *page, int error)
5041da177e4SLinus Torvalds {
5057eaceaccSJens Axboe 	lock_page(page);
5063e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5073e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5081da177e4SLinus Torvalds 	unlock_page(page);
5091da177e4SLinus Torvalds }
5101da177e4SLinus Torvalds 
51104e62a29SChristoph Lameter /* possible outcome of pageout() */
51204e62a29SChristoph Lameter typedef enum {
51304e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
51404e62a29SChristoph Lameter 	PAGE_KEEP,
51504e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
51604e62a29SChristoph Lameter 	PAGE_ACTIVATE,
51704e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
51804e62a29SChristoph Lameter 	PAGE_SUCCESS,
51904e62a29SChristoph Lameter 	/* page is clean and locked */
52004e62a29SChristoph Lameter 	PAGE_CLEAN,
52104e62a29SChristoph Lameter } pageout_t;
52204e62a29SChristoph Lameter 
5231da177e4SLinus Torvalds /*
5241742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5251742f19fSAndrew Morton  * Calls ->writepage().
5261da177e4SLinus Torvalds  */
527c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5287d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5291da177e4SLinus Torvalds {
5301da177e4SLinus Torvalds 	/*
5311da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5321da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5331da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5341da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5351da177e4SLinus Torvalds 	 * PagePrivate for that.
5361da177e4SLinus Torvalds 	 *
5378174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5381da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5391da177e4SLinus Torvalds 	 * will block.
5401da177e4SLinus Torvalds 	 *
5411da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5421da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5431da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5441da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5451da177e4SLinus Torvalds 	 */
5461da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5471da177e4SLinus Torvalds 		return PAGE_KEEP;
5481da177e4SLinus Torvalds 	if (!mapping) {
5491da177e4SLinus Torvalds 		/*
5501da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5511da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5521da177e4SLinus Torvalds 		 */
553266cf658SDavid Howells 		if (page_has_private(page)) {
5541da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5551da177e4SLinus Torvalds 				ClearPageDirty(page);
556b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5571da177e4SLinus Torvalds 				return PAGE_CLEAN;
5581da177e4SLinus Torvalds 			}
5591da177e4SLinus Torvalds 		}
5601da177e4SLinus Torvalds 		return PAGE_KEEP;
5611da177e4SLinus Torvalds 	}
5621da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
5631da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
564703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
5651da177e4SLinus Torvalds 		return PAGE_KEEP;
5661da177e4SLinus Torvalds 
5671da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5681da177e4SLinus Torvalds 		int res;
5691da177e4SLinus Torvalds 		struct writeback_control wbc = {
5701da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5711da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
572111ebb6eSOGAWA Hirofumi 			.range_start = 0,
573111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
5741da177e4SLinus Torvalds 			.for_reclaim = 1,
5751da177e4SLinus Torvalds 		};
5761da177e4SLinus Torvalds 
5771da177e4SLinus Torvalds 		SetPageReclaim(page);
5781da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
5791da177e4SLinus Torvalds 		if (res < 0)
5801da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
581994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
5821da177e4SLinus Torvalds 			ClearPageReclaim(page);
5831da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
5841da177e4SLinus Torvalds 		}
585c661b078SAndy Whitcroft 
5861da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
5871da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
5881da177e4SLinus Torvalds 			ClearPageReclaim(page);
5891da177e4SLinus Torvalds 		}
5903aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
591e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
5921da177e4SLinus Torvalds 		return PAGE_SUCCESS;
5931da177e4SLinus Torvalds 	}
5941da177e4SLinus Torvalds 
5951da177e4SLinus Torvalds 	return PAGE_CLEAN;
5961da177e4SLinus Torvalds }
5971da177e4SLinus Torvalds 
598a649fd92SAndrew Morton /*
599e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
600e286781dSNick Piggin  * gets returned with a refcount of 0.
601a649fd92SAndrew Morton  */
602a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
603a528910eSJohannes Weiner 			    bool reclaimed)
60449d2e9ccSChristoph Lameter {
605c4843a75SGreg Thelen 	unsigned long flags;
606c4843a75SGreg Thelen 
60728e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
60828e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
60949d2e9ccSChristoph Lameter 
610c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
61149d2e9ccSChristoph Lameter 	/*
6120fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6130fd0e6b0SNick Piggin 	 *
6140fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6150fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6160fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6170fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6180fd0e6b0SNick Piggin 	 *
6190fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6200fd0e6b0SNick Piggin 	 * [user mapping goes away]
6210fd0e6b0SNick Piggin 	 * write_to(page);
6220fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6230fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6240fd0e6b0SNick Piggin 	 * put_page(page);
6250fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6260fd0e6b0SNick Piggin 	 *
6270fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6280fd0e6b0SNick Piggin 	 *
6290fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6300fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6310fd0e6b0SNick Piggin 	 * load is not satisfied before that of page->_count.
6320fd0e6b0SNick Piggin 	 *
6330fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6340fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
63549d2e9ccSChristoph Lameter 	 */
636e286781dSNick Piggin 	if (!page_freeze_refs(page, 2))
63749d2e9ccSChristoph Lameter 		goto cannot_free;
638e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
639e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
640e286781dSNick Piggin 		page_unfreeze_refs(page, 2);
64149d2e9ccSChristoph Lameter 		goto cannot_free;
642e286781dSNick Piggin 	}
64349d2e9ccSChristoph Lameter 
64449d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
64549d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6460a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
64749d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
648c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6490a31bc97SJohannes Weiner 		swapcache_free(swap);
650e286781dSNick Piggin 	} else {
6516072d13cSLinus Torvalds 		void (*freepage)(struct page *);
652a528910eSJohannes Weiner 		void *shadow = NULL;
6536072d13cSLinus Torvalds 
6546072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
655a528910eSJohannes Weiner 		/*
656a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
657a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
658a528910eSJohannes Weiner 		 *
659a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
660a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
661a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
662a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
663a528910eSJohannes Weiner 		 * back.
664f9fe48beSRoss Zwisler 		 *
665f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
666f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
667f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
668f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
669f9fe48beSRoss Zwisler 		 * same page_tree.
670a528910eSJohannes Weiner 		 */
671a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
672f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
673a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
67462cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
675c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6766072d13cSLinus Torvalds 
6776072d13cSLinus Torvalds 		if (freepage != NULL)
6786072d13cSLinus Torvalds 			freepage(page);
679e286781dSNick Piggin 	}
680e286781dSNick Piggin 
68149d2e9ccSChristoph Lameter 	return 1;
68249d2e9ccSChristoph Lameter 
68349d2e9ccSChristoph Lameter cannot_free:
684c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
68549d2e9ccSChristoph Lameter 	return 0;
68649d2e9ccSChristoph Lameter }
68749d2e9ccSChristoph Lameter 
6881da177e4SLinus Torvalds /*
689e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
690e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
691e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
692e286781dSNick Piggin  * this page.
693e286781dSNick Piggin  */
694e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
695e286781dSNick Piggin {
696a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
697e286781dSNick Piggin 		/*
698e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
699e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
700e286781dSNick Piggin 		 * atomic operation.
701e286781dSNick Piggin 		 */
702e286781dSNick Piggin 		page_unfreeze_refs(page, 1);
703e286781dSNick Piggin 		return 1;
704e286781dSNick Piggin 	}
705e286781dSNick Piggin 	return 0;
706e286781dSNick Piggin }
707e286781dSNick Piggin 
708894bc310SLee Schermerhorn /**
709894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
710894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
711894bc310SLee Schermerhorn  *
712894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
713894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
714894bc310SLee Schermerhorn  *
715894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
716894bc310SLee Schermerhorn  */
717894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
718894bc310SLee Schermerhorn {
7190ec3b74cSVlastimil Babka 	bool is_unevictable;
720bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
721894bc310SLee Schermerhorn 
722309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
723894bc310SLee Schermerhorn 
724894bc310SLee Schermerhorn redo:
725894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
726894bc310SLee Schermerhorn 
72739b5f29aSHugh Dickins 	if (page_evictable(page)) {
728894bc310SLee Schermerhorn 		/*
729894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
730894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
731894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
732894bc310SLee Schermerhorn 		 * We know how to handle that.
733894bc310SLee Schermerhorn 		 */
7340ec3b74cSVlastimil Babka 		is_unevictable = false;
735c53954a0SMel Gorman 		lru_cache_add(page);
736894bc310SLee Schermerhorn 	} else {
737894bc310SLee Schermerhorn 		/*
738894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
739894bc310SLee Schermerhorn 		 * list.
740894bc310SLee Schermerhorn 		 */
7410ec3b74cSVlastimil Babka 		is_unevictable = true;
742894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7436a7b9548SJohannes Weiner 		/*
74421ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
74521ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
74621ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
74724513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
74821ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7496a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7506a7b9548SJohannes Weiner 		 *
75121ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7526a7b9548SJohannes Weiner 		 */
7536a7b9548SJohannes Weiner 		smp_mb();
754894bc310SLee Schermerhorn 	}
755894bc310SLee Schermerhorn 
756894bc310SLee Schermerhorn 	/*
757894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
758894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
759894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
760894bc310SLee Schermerhorn 	 */
7610ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
762894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
763894bc310SLee Schermerhorn 			put_page(page);
764894bc310SLee Schermerhorn 			goto redo;
765894bc310SLee Schermerhorn 		}
766894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
767894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
768894bc310SLee Schermerhorn 		 * nothing to do here.
769894bc310SLee Schermerhorn 		 */
770894bc310SLee Schermerhorn 	}
771894bc310SLee Schermerhorn 
7720ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
773bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
7740ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
775bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
776bbfd28eeSLee Schermerhorn 
777894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
778894bc310SLee Schermerhorn }
779894bc310SLee Schermerhorn 
780dfc8d636SJohannes Weiner enum page_references {
781dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
782dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
78364574746SJohannes Weiner 	PAGEREF_KEEP,
784dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
785dfc8d636SJohannes Weiner };
786dfc8d636SJohannes Weiner 
787dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
788dfc8d636SJohannes Weiner 						  struct scan_control *sc)
789dfc8d636SJohannes Weiner {
79064574746SJohannes Weiner 	int referenced_ptes, referenced_page;
791dfc8d636SJohannes Weiner 	unsigned long vm_flags;
792dfc8d636SJohannes Weiner 
793c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
794c3ac9a8aSJohannes Weiner 					  &vm_flags);
79564574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
796dfc8d636SJohannes Weiner 
797dfc8d636SJohannes Weiner 	/*
798dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
799dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
800dfc8d636SJohannes Weiner 	 */
801dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
802dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
803dfc8d636SJohannes Weiner 
80464574746SJohannes Weiner 	if (referenced_ptes) {
805e4898273SMichal Hocko 		if (PageSwapBacked(page))
80664574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
80764574746SJohannes Weiner 		/*
80864574746SJohannes Weiner 		 * All mapped pages start out with page table
80964574746SJohannes Weiner 		 * references from the instantiating fault, so we need
81064574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
81164574746SJohannes Weiner 		 * than once.
81264574746SJohannes Weiner 		 *
81364574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
81464574746SJohannes Weiner 		 * inactive list.  Another page table reference will
81564574746SJohannes Weiner 		 * lead to its activation.
81664574746SJohannes Weiner 		 *
81764574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
81864574746SJohannes Weiner 		 * so that recently deactivated but used pages are
81964574746SJohannes Weiner 		 * quickly recovered.
82064574746SJohannes Weiner 		 */
82164574746SJohannes Weiner 		SetPageReferenced(page);
82264574746SJohannes Weiner 
82334dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
824dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
825dfc8d636SJohannes Weiner 
826c909e993SKonstantin Khlebnikov 		/*
827c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
828c909e993SKonstantin Khlebnikov 		 */
829c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
830c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
831c909e993SKonstantin Khlebnikov 
83264574746SJohannes Weiner 		return PAGEREF_KEEP;
83364574746SJohannes Weiner 	}
83464574746SJohannes Weiner 
835dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8362e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
837dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
83864574746SJohannes Weiner 
83964574746SJohannes Weiner 	return PAGEREF_RECLAIM;
840dfc8d636SJohannes Weiner }
841dfc8d636SJohannes Weiner 
842e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
843e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
844e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
845e2be15f6SMel Gorman {
846b4597226SMel Gorman 	struct address_space *mapping;
847b4597226SMel Gorman 
848e2be15f6SMel Gorman 	/*
849e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
850e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
851e2be15f6SMel Gorman 	 */
852e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
853e2be15f6SMel Gorman 		*dirty = false;
854e2be15f6SMel Gorman 		*writeback = false;
855e2be15f6SMel Gorman 		return;
856e2be15f6SMel Gorman 	}
857e2be15f6SMel Gorman 
858e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
859e2be15f6SMel Gorman 	*dirty = PageDirty(page);
860e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
861b4597226SMel Gorman 
862b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
863b4597226SMel Gorman 	if (!page_has_private(page))
864b4597226SMel Gorman 		return;
865b4597226SMel Gorman 
866b4597226SMel Gorman 	mapping = page_mapping(page);
867b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
868b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
869e2be15f6SMel Gorman }
870e2be15f6SMel Gorman 
871e286781dSNick Piggin /*
8721742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8731da177e4SLinus Torvalds  */
8741742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
8756a18adb3SKonstantin Khlebnikov 				      struct zone *zone,
876f84f6e2bSMel Gorman 				      struct scan_control *sc,
87702c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
8788e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
879d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
8808e950282SMel Gorman 				      unsigned long *ret_nr_congested,
88102c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
882b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
88302c6de8dSMinchan Kim 				      bool force_reclaim)
8841da177e4SLinus Torvalds {
8851da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
886abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
8871da177e4SLinus Torvalds 	int pgactivate = 0;
888d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
8890e093d99SMel Gorman 	unsigned long nr_dirty = 0;
8900e093d99SMel Gorman 	unsigned long nr_congested = 0;
89105ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
89292df3a72SMel Gorman 	unsigned long nr_writeback = 0;
893b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
8941da177e4SLinus Torvalds 
8951da177e4SLinus Torvalds 	cond_resched();
8961da177e4SLinus Torvalds 
8971da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
8981da177e4SLinus Torvalds 		struct address_space *mapping;
8991da177e4SLinus Torvalds 		struct page *page;
9001da177e4SLinus Torvalds 		int may_enter_fs;
90102c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
902e2be15f6SMel Gorman 		bool dirty, writeback;
903854e9ed0SMinchan Kim 		bool lazyfree = false;
904854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9051da177e4SLinus Torvalds 
9061da177e4SLinus Torvalds 		cond_resched();
9071da177e4SLinus Torvalds 
9081da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9091da177e4SLinus Torvalds 		list_del(&page->lru);
9101da177e4SLinus Torvalds 
911529ae9aaSNick Piggin 		if (!trylock_page(page))
9121da177e4SLinus Torvalds 			goto keep;
9131da177e4SLinus Torvalds 
914309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
915309381feSSasha Levin 		VM_BUG_ON_PAGE(page_zone(page) != zone, page);
9161da177e4SLinus Torvalds 
9171da177e4SLinus Torvalds 		sc->nr_scanned++;
91880e43426SChristoph Lameter 
91939b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
920b291f000SNick Piggin 			goto cull_mlocked;
921894bc310SLee Schermerhorn 
922a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
92380e43426SChristoph Lameter 			goto keep_locked;
92480e43426SChristoph Lameter 
9251da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9261da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9271da177e4SLinus Torvalds 			sc->nr_scanned++;
9281da177e4SLinus Torvalds 
929c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
930c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
931c661b078SAndy Whitcroft 
932e62e384eSMichal Hocko 		/*
933e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
934e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
935e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
936e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
937e2be15f6SMel Gorman 		 */
938e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
939e2be15f6SMel Gorman 		if (dirty || writeback)
940e2be15f6SMel Gorman 			nr_dirty++;
941e2be15f6SMel Gorman 
942e2be15f6SMel Gorman 		if (dirty && !writeback)
943e2be15f6SMel Gorman 			nr_unqueued_dirty++;
944e2be15f6SMel Gorman 
945d04e8acdSMel Gorman 		/*
946d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
947d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
948d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
949d04e8acdSMel Gorman 		 * end of the LRU a second time.
950d04e8acdSMel Gorman 		 */
951e2be15f6SMel Gorman 		mapping = page_mapping(page);
9521da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
953703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
954d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
955e2be15f6SMel Gorman 			nr_congested++;
956e2be15f6SMel Gorman 
957e2be15f6SMel Gorman 		/*
958283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
959283aba9fSMel Gorman 		 * are three cases to consider.
960e62e384eSMichal Hocko 		 *
961283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
962283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
963283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
964283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
965283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
966283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
967283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
968b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
969b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
970c3b94f44SHugh Dickins 		 *
97197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
972ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
973ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
974ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
97597c9341fSTejun Heo 		 *    reclaim and continue scanning.
976283aba9fSMel Gorman 		 *
977ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
978ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
979283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
980283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
981283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
982283aba9fSMel Gorman 		 *    would probably show more reasons.
983283aba9fSMel Gorman 		 *
9847fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
985283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
986283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
987283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
988283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
989e62e384eSMichal Hocko 		 */
990283aba9fSMel Gorman 		if (PageWriteback(page)) {
991283aba9fSMel Gorman 			/* Case 1 above */
992283aba9fSMel Gorman 			if (current_is_kswapd() &&
993283aba9fSMel Gorman 			    PageReclaim(page) &&
99457054651SJohannes Weiner 			    test_bit(ZONE_WRITEBACK, &zone->flags)) {
995b1a6f21eSMel Gorman 				nr_immediate++;
996b1a6f21eSMel Gorman 				goto keep_locked;
997283aba9fSMel Gorman 
998283aba9fSMel Gorman 			/* Case 2 above */
99997c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1000ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1001c3b94f44SHugh Dickins 				/*
1002c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1003c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1004c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1005c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1006c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1007c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1008c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1009c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1010c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1011c3b94f44SHugh Dickins 				 */
1012c3b94f44SHugh Dickins 				SetPageReclaim(page);
101392df3a72SMel Gorman 				nr_writeback++;
1014c3b94f44SHugh Dickins 				goto keep_locked;
1015283aba9fSMel Gorman 
1016283aba9fSMel Gorman 			/* Case 3 above */
1017283aba9fSMel Gorman 			} else {
10187fadc820SHugh Dickins 				unlock_page(page);
1019c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10207fadc820SHugh Dickins 				/* then go back and try same page again */
10217fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10227fadc820SHugh Dickins 				continue;
1023e62e384eSMichal Hocko 			}
1024283aba9fSMel Gorman 		}
10251da177e4SLinus Torvalds 
102602c6de8dSMinchan Kim 		if (!force_reclaim)
10276a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
102802c6de8dSMinchan Kim 
1029dfc8d636SJohannes Weiner 		switch (references) {
1030dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10311da177e4SLinus Torvalds 			goto activate_locked;
103264574746SJohannes Weiner 		case PAGEREF_KEEP:
103364574746SJohannes Weiner 			goto keep_locked;
1034dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1035dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1036dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1037dfc8d636SJohannes Weiner 		}
10381da177e4SLinus Torvalds 
10391da177e4SLinus Torvalds 		/*
10401da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10411da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10421da177e4SLinus Torvalds 		 */
1043b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
104463eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
104563eb6b93SHugh Dickins 				goto keep_locked;
10465bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10471da177e4SLinus Torvalds 				goto activate_locked;
1048854e9ed0SMinchan Kim 			lazyfree = true;
104963eb6b93SHugh Dickins 			may_enter_fs = 1;
10501da177e4SLinus Torvalds 
1051e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10521da177e4SLinus Torvalds 			mapping = page_mapping(page);
1053e2be15f6SMel Gorman 		}
10541da177e4SLinus Torvalds 
10551da177e4SLinus Torvalds 		/*
10561da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10571da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10581da177e4SLinus Torvalds 		 */
10591da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1060854e9ed0SMinchan Kim 			switch (ret = try_to_unmap(page, lazyfree ?
1061854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
1062854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH))) {
10631da177e4SLinus Torvalds 			case SWAP_FAIL:
10641da177e4SLinus Torvalds 				goto activate_locked;
10651da177e4SLinus Torvalds 			case SWAP_AGAIN:
10661da177e4SLinus Torvalds 				goto keep_locked;
1067b291f000SNick Piggin 			case SWAP_MLOCK:
1068b291f000SNick Piggin 				goto cull_mlocked;
1069854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1070854e9ed0SMinchan Kim 				goto lazyfree;
10711da177e4SLinus Torvalds 			case SWAP_SUCCESS:
10721da177e4SLinus Torvalds 				; /* try to free the page below */
10731da177e4SLinus Torvalds 			}
10741da177e4SLinus Torvalds 		}
10751da177e4SLinus Torvalds 
10761da177e4SLinus Torvalds 		if (PageDirty(page)) {
1077ee72886dSMel Gorman 			/*
1078ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1079d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1080d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1081ee72886dSMel Gorman 			 */
1082f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
10839e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
108457054651SJohannes Weiner 					 !test_bit(ZONE_DIRTY, &zone->flags))) {
108549ea7eb6SMel Gorman 				/*
108649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
108749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
108849ea7eb6SMel Gorman 				 * except we already have the page isolated
108949ea7eb6SMel Gorman 				 * and know it's dirty
109049ea7eb6SMel Gorman 				 */
109149ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
109249ea7eb6SMel Gorman 				SetPageReclaim(page);
109349ea7eb6SMel Gorman 
1094ee72886dSMel Gorman 				goto keep_locked;
1095ee72886dSMel Gorman 			}
1096ee72886dSMel Gorman 
1097dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
10981da177e4SLinus Torvalds 				goto keep_locked;
10994dd4b920SAndrew Morton 			if (!may_enter_fs)
11001da177e4SLinus Torvalds 				goto keep_locked;
110152a8363eSChristoph Lameter 			if (!sc->may_writepage)
11021da177e4SLinus Torvalds 				goto keep_locked;
11031da177e4SLinus Torvalds 
1104d950c947SMel Gorman 			/*
1105d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1106d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1107d950c947SMel Gorman 			 * starts and then write it out here.
1108d950c947SMel Gorman 			 */
1109d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11107d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11111da177e4SLinus Torvalds 			case PAGE_KEEP:
11121da177e4SLinus Torvalds 				goto keep_locked;
11131da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11141da177e4SLinus Torvalds 				goto activate_locked;
11151da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11167d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
111741ac1999SMel Gorman 					goto keep;
11187d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11191da177e4SLinus Torvalds 					goto keep;
11207d3579e8SKOSAKI Motohiro 
11211da177e4SLinus Torvalds 				/*
11221da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11231da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11241da177e4SLinus Torvalds 				 */
1125529ae9aaSNick Piggin 				if (!trylock_page(page))
11261da177e4SLinus Torvalds 					goto keep;
11271da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11281da177e4SLinus Torvalds 					goto keep_locked;
11291da177e4SLinus Torvalds 				mapping = page_mapping(page);
11301da177e4SLinus Torvalds 			case PAGE_CLEAN:
11311da177e4SLinus Torvalds 				; /* try to free the page below */
11321da177e4SLinus Torvalds 			}
11331da177e4SLinus Torvalds 		}
11341da177e4SLinus Torvalds 
11351da177e4SLinus Torvalds 		/*
11361da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11371da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11381da177e4SLinus Torvalds 		 * the page as well.
11391da177e4SLinus Torvalds 		 *
11401da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11411da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11421da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11431da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11441da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11451da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11461da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11471da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11481da177e4SLinus Torvalds 		 *
11491da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11501da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11511da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11521da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11531da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11541da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11551da177e4SLinus Torvalds 		 */
1156266cf658SDavid Howells 		if (page_has_private(page)) {
11571da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11581da177e4SLinus Torvalds 				goto activate_locked;
1159e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1160e286781dSNick Piggin 				unlock_page(page);
1161e286781dSNick Piggin 				if (put_page_testzero(page))
11621da177e4SLinus Torvalds 					goto free_it;
1163e286781dSNick Piggin 				else {
1164e286781dSNick Piggin 					/*
1165e286781dSNick Piggin 					 * rare race with speculative reference.
1166e286781dSNick Piggin 					 * the speculative reference will free
1167e286781dSNick Piggin 					 * this page shortly, so we may
1168e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1169e286781dSNick Piggin 					 * leave it off the LRU).
1170e286781dSNick Piggin 					 */
1171e286781dSNick Piggin 					nr_reclaimed++;
1172e286781dSNick Piggin 					continue;
1173e286781dSNick Piggin 				}
1174e286781dSNick Piggin 			}
11751da177e4SLinus Torvalds 		}
11761da177e4SLinus Torvalds 
1177854e9ed0SMinchan Kim lazyfree:
1178a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
117949d2e9ccSChristoph Lameter 			goto keep_locked;
11801da177e4SLinus Torvalds 
1181a978d6f5SNick Piggin 		/*
1182a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1183a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1184a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1185a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1186a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1187a978d6f5SNick Piggin 		 */
118848c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1189e286781dSNick Piggin free_it:
1190854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1191854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1192854e9ed0SMinchan Kim 
119305ff5137SAndrew Morton 		nr_reclaimed++;
1194abe4c3b5SMel Gorman 
1195abe4c3b5SMel Gorman 		/*
1196abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1197abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1198abe4c3b5SMel Gorman 		 */
1199abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12001da177e4SLinus Torvalds 		continue;
12011da177e4SLinus Torvalds 
1202b291f000SNick Piggin cull_mlocked:
120363d6c5adSHugh Dickins 		if (PageSwapCache(page))
120463d6c5adSHugh Dickins 			try_to_free_swap(page);
1205b291f000SNick Piggin 		unlock_page(page);
1206c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1207b291f000SNick Piggin 		continue;
1208b291f000SNick Piggin 
12091da177e4SLinus Torvalds activate_locked:
121068a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12115ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1212a2c43eedSHugh Dickins 			try_to_free_swap(page);
1213309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12141da177e4SLinus Torvalds 		SetPageActive(page);
12151da177e4SLinus Torvalds 		pgactivate++;
12161da177e4SLinus Torvalds keep_locked:
12171da177e4SLinus Torvalds 		unlock_page(page);
12181da177e4SLinus Torvalds keep:
12191da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1220309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12211da177e4SLinus Torvalds 	}
1222abe4c3b5SMel Gorman 
1223747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
122472b252aeSMel Gorman 	try_to_unmap_flush();
1225b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1226abe4c3b5SMel Gorman 
12271da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1228f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12290a31bc97SJohannes Weiner 
12308e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12318e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1232d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
123392df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1234b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
123505ff5137SAndrew Morton 	return nr_reclaimed;
12361da177e4SLinus Torvalds }
12371da177e4SLinus Torvalds 
123802c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
123902c6de8dSMinchan Kim 					    struct list_head *page_list)
124002c6de8dSMinchan Kim {
124102c6de8dSMinchan Kim 	struct scan_control sc = {
124202c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
124302c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
124402c6de8dSMinchan Kim 		.may_unmap = 1,
124502c6de8dSMinchan Kim 	};
12468e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
124702c6de8dSMinchan Kim 	struct page *page, *next;
124802c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
124902c6de8dSMinchan Kim 
125002c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1251117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1252117aad1eSRafael Aquini 		    !isolated_balloon_page(page)) {
125302c6de8dSMinchan Kim 			ClearPageActive(page);
125402c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
125502c6de8dSMinchan Kim 		}
125602c6de8dSMinchan Kim 	}
125702c6de8dSMinchan Kim 
125802c6de8dSMinchan Kim 	ret = shrink_page_list(&clean_pages, zone, &sc,
125902c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
12608e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
126102c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
126283da7510SChristoph Lameter 	mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
126302c6de8dSMinchan Kim 	return ret;
126402c6de8dSMinchan Kim }
126502c6de8dSMinchan Kim 
12665ad333ebSAndy Whitcroft /*
12675ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
12685ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
12695ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
12705ad333ebSAndy Whitcroft  *
12715ad333ebSAndy Whitcroft  * page:	page to consider
12725ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
12735ad333ebSAndy Whitcroft  *
12745ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
12755ad333ebSAndy Whitcroft  */
1276f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
12775ad333ebSAndy Whitcroft {
12785ad333ebSAndy Whitcroft 	int ret = -EINVAL;
12795ad333ebSAndy Whitcroft 
12805ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
12815ad333ebSAndy Whitcroft 	if (!PageLRU(page))
12825ad333ebSAndy Whitcroft 		return ret;
12835ad333ebSAndy Whitcroft 
1284e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1285e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1286894bc310SLee Schermerhorn 		return ret;
1287894bc310SLee Schermerhorn 
12885ad333ebSAndy Whitcroft 	ret = -EBUSY;
128908e552c6SKAMEZAWA Hiroyuki 
1290c8244935SMel Gorman 	/*
1291c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1292c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1293c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1294c8244935SMel Gorman 	 *
1295c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1296c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1297c8244935SMel Gorman 	 *
1298c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1299c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1300c8244935SMel Gorman 	 */
1301c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1302c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1303c8244935SMel Gorman 		if (PageWriteback(page))
130439deaf85SMinchan Kim 			return ret;
130539deaf85SMinchan Kim 
1306c8244935SMel Gorman 		if (PageDirty(page)) {
1307c8244935SMel Gorman 			struct address_space *mapping;
1308c8244935SMel Gorman 
1309c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1310c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1311c8244935SMel Gorman 				return ret;
1312c8244935SMel Gorman 
1313c8244935SMel Gorman 			/*
1314c8244935SMel Gorman 			 * Only pages without mappings or that have a
1315c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1316c8244935SMel Gorman 			 * without blocking
1317c8244935SMel Gorman 			 */
1318c8244935SMel Gorman 			mapping = page_mapping(page);
1319c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1320c8244935SMel Gorman 				return ret;
1321c8244935SMel Gorman 		}
1322c8244935SMel Gorman 	}
1323c8244935SMel Gorman 
1324f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1325f80c0673SMinchan Kim 		return ret;
1326f80c0673SMinchan Kim 
13275ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13285ad333ebSAndy Whitcroft 		/*
13295ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13305ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13315ad333ebSAndy Whitcroft 		 * page release code relies on it.
13325ad333ebSAndy Whitcroft 		 */
13335ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13345ad333ebSAndy Whitcroft 		ret = 0;
13355ad333ebSAndy Whitcroft 	}
13365ad333ebSAndy Whitcroft 
13375ad333ebSAndy Whitcroft 	return ret;
13385ad333ebSAndy Whitcroft }
13395ad333ebSAndy Whitcroft 
134049d2e9ccSChristoph Lameter /*
13411da177e4SLinus Torvalds  * zone->lru_lock is heavily contended.  Some of the functions that
13421da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
13431da177e4SLinus Torvalds  * and working on them outside the LRU lock.
13441da177e4SLinus Torvalds  *
13451da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
13461da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
13471da177e4SLinus Torvalds  *
13481da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
13491da177e4SLinus Torvalds  *
13501da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
13515dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
13521da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1353f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1354fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
13555ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
13563cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
13571da177e4SLinus Torvalds  *
13581da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
13591da177e4SLinus Torvalds  */
136069e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
13615dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1362fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
13633cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
13641da177e4SLinus Torvalds {
136575b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
136669e05944SAndrew Morton 	unsigned long nr_taken = 0;
1367c9b02d97SWu Fengguang 	unsigned long scan;
13681da177e4SLinus Torvalds 
13690b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
13700b802f10SVladimir Davydov 					!list_empty(src); scan++) {
13715ad333ebSAndy Whitcroft 		struct page *page;
1372fa9add64SHugh Dickins 		int nr_pages;
13735ad333ebSAndy Whitcroft 
13741da177e4SLinus Torvalds 		page = lru_to_page(src);
13751da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
13761da177e4SLinus Torvalds 
1377309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
13788d438f96SNick Piggin 
1379f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
13805ad333ebSAndy Whitcroft 		case 0:
1381fa9add64SHugh Dickins 			nr_pages = hpage_nr_pages(page);
1382fa9add64SHugh Dickins 			mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
13835ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
1384fa9add64SHugh Dickins 			nr_taken += nr_pages;
13855ad333ebSAndy Whitcroft 			break;
13867c8ee9a8SNick Piggin 
13875ad333ebSAndy Whitcroft 		case -EBUSY:
13885ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
13895ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
13905ad333ebSAndy Whitcroft 			continue;
13915ad333ebSAndy Whitcroft 
13925ad333ebSAndy Whitcroft 		default:
13935ad333ebSAndy Whitcroft 			BUG();
13945ad333ebSAndy Whitcroft 		}
13955ad333ebSAndy Whitcroft 	}
13961da177e4SLinus Torvalds 
1397f626012dSHugh Dickins 	*nr_scanned = scan;
139875b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
139975b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
14001da177e4SLinus Torvalds 	return nr_taken;
14011da177e4SLinus Torvalds }
14021da177e4SLinus Torvalds 
140362695a84SNick Piggin /**
140462695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
140562695a84SNick Piggin  * @page: page to isolate from its LRU list
140662695a84SNick Piggin  *
140762695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
140862695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
140962695a84SNick Piggin  *
141062695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
141162695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
141262695a84SNick Piggin  *
141362695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1414894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1415894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1416894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
141762695a84SNick Piggin  *
141862695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
141962695a84SNick Piggin  * found will be decremented.
142062695a84SNick Piggin  *
142162695a84SNick Piggin  * Restrictions:
142262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
142362695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
142462695a84SNick Piggin  *     without a stable reference).
142562695a84SNick Piggin  * (2) the lru_lock must not be held.
142662695a84SNick Piggin  * (3) interrupts must be enabled.
142762695a84SNick Piggin  */
142862695a84SNick Piggin int isolate_lru_page(struct page *page)
142962695a84SNick Piggin {
143062695a84SNick Piggin 	int ret = -EBUSY;
143162695a84SNick Piggin 
1432309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1433cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
14340c917313SKonstantin Khlebnikov 
143562695a84SNick Piggin 	if (PageLRU(page)) {
143662695a84SNick Piggin 		struct zone *zone = page_zone(page);
1437fa9add64SHugh Dickins 		struct lruvec *lruvec;
143862695a84SNick Piggin 
143962695a84SNick Piggin 		spin_lock_irq(&zone->lru_lock);
1440fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
14410c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1442894bc310SLee Schermerhorn 			int lru = page_lru(page);
14430c917313SKonstantin Khlebnikov 			get_page(page);
144462695a84SNick Piggin 			ClearPageLRU(page);
1445fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1446fa9add64SHugh Dickins 			ret = 0;
144762695a84SNick Piggin 		}
144862695a84SNick Piggin 		spin_unlock_irq(&zone->lru_lock);
144962695a84SNick Piggin 	}
145062695a84SNick Piggin 	return ret;
145162695a84SNick Piggin }
145262695a84SNick Piggin 
14535ad333ebSAndy Whitcroft /*
1454d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1455d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1456d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1457d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1458d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
145935cd7815SRik van Riel  */
146035cd7815SRik van Riel static int too_many_isolated(struct zone *zone, int file,
146135cd7815SRik van Riel 		struct scan_control *sc)
146235cd7815SRik van Riel {
146335cd7815SRik van Riel 	unsigned long inactive, isolated;
146435cd7815SRik van Riel 
146535cd7815SRik van Riel 	if (current_is_kswapd())
146635cd7815SRik van Riel 		return 0;
146735cd7815SRik van Riel 
146897c9341fSTejun Heo 	if (!sane_reclaim(sc))
146935cd7815SRik van Riel 		return 0;
147035cd7815SRik van Riel 
147135cd7815SRik van Riel 	if (file) {
147235cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_FILE);
147335cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_FILE);
147435cd7815SRik van Riel 	} else {
147535cd7815SRik van Riel 		inactive = zone_page_state(zone, NR_INACTIVE_ANON);
147635cd7815SRik van Riel 		isolated = zone_page_state(zone, NR_ISOLATED_ANON);
147735cd7815SRik van Riel 	}
147835cd7815SRik van Riel 
14793cf23841SFengguang Wu 	/*
14803cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
14813cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
14823cf23841SFengguang Wu 	 * deadlock.
14833cf23841SFengguang Wu 	 */
1484d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
14853cf23841SFengguang Wu 		inactive >>= 3;
14863cf23841SFengguang Wu 
148735cd7815SRik van Riel 	return isolated > inactive;
148835cd7815SRik van Riel }
148935cd7815SRik van Riel 
149066635629SMel Gorman static noinline_for_stack void
149175b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
149266635629SMel Gorman {
149327ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
149427ac81d8SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
14953f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
149666635629SMel Gorman 
149766635629SMel Gorman 	/*
149866635629SMel Gorman 	 * Put back any unfreeable pages.
149966635629SMel Gorman 	 */
150066635629SMel Gorman 	while (!list_empty(page_list)) {
15013f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
150266635629SMel Gorman 		int lru;
15033f79768fSHugh Dickins 
1504309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
150566635629SMel Gorman 		list_del(&page->lru);
150639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
150766635629SMel Gorman 			spin_unlock_irq(&zone->lru_lock);
150866635629SMel Gorman 			putback_lru_page(page);
150966635629SMel Gorman 			spin_lock_irq(&zone->lru_lock);
151066635629SMel Gorman 			continue;
151166635629SMel Gorman 		}
1512fa9add64SHugh Dickins 
1513fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
1514fa9add64SHugh Dickins 
15157a608572SLinus Torvalds 		SetPageLRU(page);
151666635629SMel Gorman 		lru = page_lru(page);
1517fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1518fa9add64SHugh Dickins 
151966635629SMel Gorman 		if (is_active_lru(lru)) {
152066635629SMel Gorman 			int file = is_file_lru(lru);
15219992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
15229992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
152366635629SMel Gorman 		}
15242bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15252bcf8879SHugh Dickins 			__ClearPageLRU(page);
15262bcf8879SHugh Dickins 			__ClearPageActive(page);
1527fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15282bcf8879SHugh Dickins 
15292bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
153066635629SMel Gorman 				spin_unlock_irq(&zone->lru_lock);
1531747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
15322bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
153366635629SMel Gorman 				spin_lock_irq(&zone->lru_lock);
15342bcf8879SHugh Dickins 			} else
15352bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
153666635629SMel Gorman 		}
153766635629SMel Gorman 	}
153866635629SMel Gorman 
15393f79768fSHugh Dickins 	/*
15403f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
15413f79768fSHugh Dickins 	 */
15423f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
154366635629SMel Gorman }
154466635629SMel Gorman 
154566635629SMel Gorman /*
1546399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1547399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1548399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1549399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1550399ba0b9SNeilBrown  */
1551399ba0b9SNeilBrown static int current_may_throttle(void)
1552399ba0b9SNeilBrown {
1553399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1554399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1555399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1556399ba0b9SNeilBrown }
1557399ba0b9SNeilBrown 
1558399ba0b9SNeilBrown /*
15591742f19fSAndrew Morton  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
15601742f19fSAndrew Morton  * of reclaimed pages
15611da177e4SLinus Torvalds  */
156266635629SMel Gorman static noinline_for_stack unsigned long
15631a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
15649e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
15651da177e4SLinus Torvalds {
15661da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1567e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
156805ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1569e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
15708e950282SMel Gorman 	unsigned long nr_dirty = 0;
15718e950282SMel Gorman 	unsigned long nr_congested = 0;
1572e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
157392df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1574b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1575f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
15763cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
15771a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
15781a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
157978dc583dSKOSAKI Motohiro 
158035cd7815SRik van Riel 	while (unlikely(too_many_isolated(zone, file, sc))) {
158158355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
158235cd7815SRik van Riel 
158335cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
158435cd7815SRik van Riel 		if (fatal_signal_pending(current))
158535cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
158635cd7815SRik van Riel 	}
158735cd7815SRik van Riel 
15881da177e4SLinus Torvalds 	lru_add_drain();
1589f80c0673SMinchan Kim 
1590f80c0673SMinchan Kim 	if (!sc->may_unmap)
159161317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1592f80c0673SMinchan Kim 	if (!sc->may_writepage)
159361317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1594f80c0673SMinchan Kim 
15951da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
15961da177e4SLinus Torvalds 
15975dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
15985dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
159995d918fcSKonstantin Khlebnikov 
160095d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
160195d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
160295d918fcSKonstantin Khlebnikov 
160389b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
16040d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
1605b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
160675b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1607b35ea17bSKOSAKI Motohiro 		else
160875b00af7SHugh Dickins 			__count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1609b35ea17bSKOSAKI Motohiro 	}
161066635629SMel Gorman 	spin_unlock_irq(&zone->lru_lock);
1611d563c050SHillf Danton 
1612d563c050SHillf Danton 	if (nr_taken == 0)
161366635629SMel Gorman 		return 0;
1614b35ea17bSKOSAKI Motohiro 
161502c6de8dSMinchan Kim 	nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
16168e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
16178e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1618b1a6f21eSMel Gorman 				false);
1619c661b078SAndy Whitcroft 
16203f79768fSHugh Dickins 	spin_lock_irq(&zone->lru_lock);
16213f79768fSHugh Dickins 
162295d918fcSKonstantin Khlebnikov 	reclaim_stat->recent_scanned[file] += nr_taken;
1623d563c050SHillf Danton 
1624904249aaSYing Han 	if (global_reclaim(sc)) {
1625b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1626904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1627904249aaSYing Han 					       nr_reclaimed);
1628904249aaSYing Han 		else
1629904249aaSYing Han 			__count_zone_vm_events(PGSTEAL_DIRECT, zone,
1630904249aaSYing Han 					       nr_reclaimed);
1631904249aaSYing Han 	}
1632a74609faSNick Piggin 
163327ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
16343f79768fSHugh Dickins 
163595d918fcSKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
16363f79768fSHugh Dickins 
16373f79768fSHugh Dickins 	spin_unlock_irq(&zone->lru_lock);
16383f79768fSHugh Dickins 
1639747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1640b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1641e11da5b4SMel Gorman 
164292df3a72SMel Gorman 	/*
164392df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
164492df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
164592df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
164692df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
164792df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
164892df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
164992df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
165092df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
165192df3a72SMel Gorman 	 *
16528e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
16538e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
16548e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
165592df3a72SMel Gorman 	 */
1656918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
165757054651SJohannes Weiner 		set_bit(ZONE_WRITEBACK, &zone->flags);
165892df3a72SMel Gorman 
1659d43006d5SMel Gorman 	/*
166097c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
166197c9341fSTejun Heo 	 * stalling here.
1662d43006d5SMel Gorman 	 */
166397c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1664b1a6f21eSMel Gorman 		/*
16658e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
16668e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
16678e950282SMel Gorman 		 */
16688e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
166957054651SJohannes Weiner 			set_bit(ZONE_CONGESTED, &zone->flags);
16708e950282SMel Gorman 
16718e950282SMel Gorman 		/*
1672b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1673b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
167457054651SJohannes Weiner 		 * the zone ZONE_DIRTY and kswapd will start writing pages from
167557054651SJohannes Weiner 		 * reclaim context.
1676b1a6f21eSMel Gorman 		 */
1677b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
167857054651SJohannes Weiner 			set_bit(ZONE_DIRTY, &zone->flags);
1679b1a6f21eSMel Gorman 
1680b1a6f21eSMel Gorman 		/*
1681b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1682b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1683b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1684b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1685b1a6f21eSMel Gorman 		 */
1686b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1687b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1688e2be15f6SMel Gorman 	}
1689d43006d5SMel Gorman 
16908e950282SMel Gorman 	/*
16918e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
16928e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
16938e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
16948e950282SMel Gorman 	 */
1695399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1696399ba0b9SNeilBrown 	    current_may_throttle())
16978e950282SMel Gorman 		wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
16988e950282SMel Gorman 
1699ba5e9579Syalin wang 	trace_mm_vmscan_lru_shrink_inactive(zone, nr_scanned, nr_reclaimed,
1700ba5e9579Syalin wang 			sc->priority, file);
170105ff5137SAndrew Morton 	return nr_reclaimed;
17021da177e4SLinus Torvalds }
17031da177e4SLinus Torvalds 
17043bb1a852SMartin Bligh /*
17051cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
17061cfb419bSKAMEZAWA Hiroyuki  *
17071cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
17081cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
17091cfb419bSKAMEZAWA Hiroyuki  *
17101cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
17111cfb419bSKAMEZAWA Hiroyuki  * appropriate to hold zone->lru_lock across the whole operation.  But if
17121cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
17131cfb419bSKAMEZAWA Hiroyuki  * should drop zone->lru_lock around each page.  It's impossible to balance
17141cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
17151cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
17161cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
17171cfb419bSKAMEZAWA Hiroyuki  *
17181cfb419bSKAMEZAWA Hiroyuki  * The downside is that we have to touch page->_count against each page.
17191cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
17201cfb419bSKAMEZAWA Hiroyuki  */
17211cfb419bSKAMEZAWA Hiroyuki 
1722fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
17233eb4140fSWu Fengguang 				     struct list_head *list,
17242bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
17253eb4140fSWu Fengguang 				     enum lru_list lru)
17263eb4140fSWu Fengguang {
1727fa9add64SHugh Dickins 	struct zone *zone = lruvec_zone(lruvec);
17283eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
17293eb4140fSWu Fengguang 	struct page *page;
1730fa9add64SHugh Dickins 	int nr_pages;
17313eb4140fSWu Fengguang 
17323eb4140fSWu Fengguang 	while (!list_empty(list)) {
17333eb4140fSWu Fengguang 		page = lru_to_page(list);
1734fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
17353eb4140fSWu Fengguang 
1736309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
17373eb4140fSWu Fengguang 		SetPageLRU(page);
17383eb4140fSWu Fengguang 
1739fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1740fa9add64SHugh Dickins 		mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1741925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1742fa9add64SHugh Dickins 		pgmoved += nr_pages;
17433eb4140fSWu Fengguang 
17442bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
17452bcf8879SHugh Dickins 			__ClearPageLRU(page);
17462bcf8879SHugh Dickins 			__ClearPageActive(page);
1747fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
17482bcf8879SHugh Dickins 
17492bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
17503eb4140fSWu Fengguang 				spin_unlock_irq(&zone->lru_lock);
1751747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
17522bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
17533eb4140fSWu Fengguang 				spin_lock_irq(&zone->lru_lock);
17542bcf8879SHugh Dickins 			} else
17552bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
17563eb4140fSWu Fengguang 		}
17573eb4140fSWu Fengguang 	}
17583eb4140fSWu Fengguang 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
17593eb4140fSWu Fengguang 	if (!is_active_lru(lru))
17603eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
17613eb4140fSWu Fengguang }
17621cfb419bSKAMEZAWA Hiroyuki 
1763f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
17641a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1765f16015fbSJohannes Weiner 			       struct scan_control *sc,
17669e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
17671cfb419bSKAMEZAWA Hiroyuki {
176844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1769f626012dSHugh Dickins 	unsigned long nr_scanned;
17706fe6b7e3SWu Fengguang 	unsigned long vm_flags;
17711cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
17728cab4754SWu Fengguang 	LIST_HEAD(l_active);
1773b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
17741cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
17751a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
177644c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1777f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17783cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
17791a93be0eSKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
17801cfb419bSKAMEZAWA Hiroyuki 
17811da177e4SLinus Torvalds 	lru_add_drain();
1782f80c0673SMinchan Kim 
1783f80c0673SMinchan Kim 	if (!sc->may_unmap)
178461317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1785f80c0673SMinchan Kim 	if (!sc->may_writepage)
178661317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1787f80c0673SMinchan Kim 
17881da177e4SLinus Torvalds 	spin_lock_irq(&zone->lru_lock);
1789925b7673SJohannes Weiner 
17905dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
17915dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
179289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
17930d5d823aSMel Gorman 		__mod_zone_page_state(zone, NR_PAGES_SCANNED, nr_scanned);
179489b5fae5SJohannes Weiner 
1795b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
17961cfb419bSKAMEZAWA Hiroyuki 
1797f626012dSHugh Dickins 	__count_zone_vm_events(PGREFILL, zone, nr_scanned);
17983cb99451SKonstantin Khlebnikov 	__mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1799a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
18001da177e4SLinus Torvalds 	spin_unlock_irq(&zone->lru_lock);
18011da177e4SLinus Torvalds 
18021da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
18031da177e4SLinus Torvalds 		cond_resched();
18041da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
18051da177e4SLinus Torvalds 		list_del(&page->lru);
18067e9cd484SRik van Riel 
180739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1808894bc310SLee Schermerhorn 			putback_lru_page(page);
1809894bc310SLee Schermerhorn 			continue;
1810894bc310SLee Schermerhorn 		}
1811894bc310SLee Schermerhorn 
1812cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1813cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1814cc715d99SMel Gorman 				if (page_has_private(page))
1815cc715d99SMel Gorman 					try_to_release_page(page, 0);
1816cc715d99SMel Gorman 				unlock_page(page);
1817cc715d99SMel Gorman 			}
1818cc715d99SMel Gorman 		}
1819cc715d99SMel Gorman 
1820c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1821c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
18229992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
18238cab4754SWu Fengguang 			/*
18248cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
18258cab4754SWu Fengguang 			 * give them one more trip around the active list. So
18268cab4754SWu Fengguang 			 * that executable code get better chances to stay in
18278cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
18288cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
18298cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
18308cab4754SWu Fengguang 			 * so we ignore them here.
18318cab4754SWu Fengguang 			 */
183241e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
18338cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
18348cab4754SWu Fengguang 				continue;
18358cab4754SWu Fengguang 			}
18368cab4754SWu Fengguang 		}
18377e9cd484SRik van Riel 
18385205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
18391da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
18401da177e4SLinus Torvalds 	}
18411da177e4SLinus Torvalds 
1842b555749aSAndrew Morton 	/*
18438cab4754SWu Fengguang 	 * Move pages back to the lru list.
1844b555749aSAndrew Morton 	 */
18452a1dc509SJohannes Weiner 	spin_lock_irq(&zone->lru_lock);
18464f98a2feSRik van Riel 	/*
18478cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
18488cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
18498cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
18507c0db9e9SJerome Marchand 	 * get_scan_count.
1851556adecbSRik van Riel 	 */
1852b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1853556adecbSRik van Riel 
1854fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1855fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1856a731286dSKOSAKI Motohiro 	__mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1857f8891e5eSChristoph Lameter 	spin_unlock_irq(&zone->lru_lock);
18582bcf8879SHugh Dickins 
1859747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1860b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
18611da177e4SLinus Torvalds }
18621da177e4SLinus Torvalds 
186374e3f3c3SMinchan Kim #ifdef CONFIG_SWAP
186442e2e457SYaowei Bai static bool inactive_anon_is_low_global(struct zone *zone)
1865f89eb90eSKOSAKI Motohiro {
1866f89eb90eSKOSAKI Motohiro 	unsigned long active, inactive;
1867f89eb90eSKOSAKI Motohiro 
1868f89eb90eSKOSAKI Motohiro 	active = zone_page_state(zone, NR_ACTIVE_ANON);
1869f89eb90eSKOSAKI Motohiro 	inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1870f89eb90eSKOSAKI Motohiro 
187129d06bbbSYaowei Bai 	return inactive * zone->inactive_ratio < active;
1872f89eb90eSKOSAKI Motohiro }
1873f89eb90eSKOSAKI Motohiro 
187414797e23SKOSAKI Motohiro /**
187514797e23SKOSAKI Motohiro  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1876c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
187714797e23SKOSAKI Motohiro  *
187814797e23SKOSAKI Motohiro  * Returns true if the zone does not have enough inactive anon pages,
187914797e23SKOSAKI Motohiro  * meaning some active anon pages need to be deactivated.
188014797e23SKOSAKI Motohiro  */
188142e2e457SYaowei Bai static bool inactive_anon_is_low(struct lruvec *lruvec)
188214797e23SKOSAKI Motohiro {
188374e3f3c3SMinchan Kim 	/*
188474e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
188574e3f3c3SMinchan Kim 	 * is pointless.
188674e3f3c3SMinchan Kim 	 */
188774e3f3c3SMinchan Kim 	if (!total_swap_pages)
188842e2e457SYaowei Bai 		return false;
188974e3f3c3SMinchan Kim 
1890c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
1891c56d5c7dSKonstantin Khlebnikov 		return mem_cgroup_inactive_anon_is_low(lruvec);
1892f16015fbSJohannes Weiner 
1893c56d5c7dSKonstantin Khlebnikov 	return inactive_anon_is_low_global(lruvec_zone(lruvec));
189414797e23SKOSAKI Motohiro }
189574e3f3c3SMinchan Kim #else
189642e2e457SYaowei Bai static inline bool inactive_anon_is_low(struct lruvec *lruvec)
189774e3f3c3SMinchan Kim {
189842e2e457SYaowei Bai 	return false;
189974e3f3c3SMinchan Kim }
190074e3f3c3SMinchan Kim #endif
190114797e23SKOSAKI Motohiro 
190256e49d21SRik van Riel /**
190356e49d21SRik van Riel  * inactive_file_is_low - check if file pages need to be deactivated
1904c56d5c7dSKonstantin Khlebnikov  * @lruvec: LRU vector to check
190556e49d21SRik van Riel  *
190656e49d21SRik van Riel  * When the system is doing streaming IO, memory pressure here
190756e49d21SRik van Riel  * ensures that active file pages get deactivated, until more
190856e49d21SRik van Riel  * than half of the file pages are on the inactive list.
190956e49d21SRik van Riel  *
191056e49d21SRik van Riel  * Once we get to that situation, protect the system's working
191156e49d21SRik van Riel  * set from being evicted by disabling active file page aging.
191256e49d21SRik van Riel  *
191356e49d21SRik van Riel  * This uses a different ratio than the anonymous pages, because
191456e49d21SRik van Riel  * the page cache uses a use-once replacement algorithm.
191556e49d21SRik van Riel  */
191642e2e457SYaowei Bai static bool inactive_file_is_low(struct lruvec *lruvec)
191756e49d21SRik van Riel {
1918e3790144SJohannes Weiner 	unsigned long inactive;
1919e3790144SJohannes Weiner 	unsigned long active;
192056e49d21SRik van Riel 
192123047a96SJohannes Weiner 	inactive = lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
192223047a96SJohannes Weiner 	active = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE);
1923e3790144SJohannes Weiner 
1924e3790144SJohannes Weiner 	return active > inactive;
192556e49d21SRik van Riel }
192656e49d21SRik van Riel 
192742e2e457SYaowei Bai static bool inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1928b39415b2SRik van Riel {
192975b00af7SHugh Dickins 	if (is_file_lru(lru))
1930c56d5c7dSKonstantin Khlebnikov 		return inactive_file_is_low(lruvec);
1931b39415b2SRik van Riel 	else
1932c56d5c7dSKonstantin Khlebnikov 		return inactive_anon_is_low(lruvec);
1933b39415b2SRik van Riel }
1934b39415b2SRik van Riel 
19354f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
19361a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1937b69408e8SChristoph Lameter {
1938b39415b2SRik van Riel 	if (is_active_lru(lru)) {
193975b00af7SHugh Dickins 		if (inactive_list_is_low(lruvec, lru))
19401a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1941556adecbSRik van Riel 		return 0;
1942556adecbSRik van Riel 	}
1943556adecbSRik van Riel 
19441a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1945b69408e8SChristoph Lameter }
1946b69408e8SChristoph Lameter 
19479a265114SJohannes Weiner enum scan_balance {
19489a265114SJohannes Weiner 	SCAN_EQUAL,
19499a265114SJohannes Weiner 	SCAN_FRACT,
19509a265114SJohannes Weiner 	SCAN_ANON,
19519a265114SJohannes Weiner 	SCAN_FILE,
19529a265114SJohannes Weiner };
19539a265114SJohannes Weiner 
19541da177e4SLinus Torvalds /*
19554f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
19564f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
19574f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
19584f98a2feSRik van Riel  * onto the active list instead of evict.
19594f98a2feSRik van Riel  *
1960be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1961be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
19624f98a2feSRik van Riel  */
196333377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
19646b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
19656b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
19664f98a2feSRik van Riel {
196733377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
196890126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19699a265114SJohannes Weiner 	u64 fraction[2];
19709a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
197190126375SKonstantin Khlebnikov 	struct zone *zone = lruvec_zone(lruvec);
19729a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
19739a265114SJohannes Weiner 	enum scan_balance scan_balance;
19740bf1457fSJohannes Weiner 	unsigned long anon, file;
19759a265114SJohannes Weiner 	bool force_scan = false;
19769a265114SJohannes Weiner 	unsigned long ap, fp;
19779a265114SJohannes Weiner 	enum lru_list lru;
19786f04f48dSSuleiman Souhlal 	bool some_scanned;
19796f04f48dSSuleiman Souhlal 	int pass;
1980246e87a9SKAMEZAWA Hiroyuki 
1981f11c0ca5SJohannes Weiner 	/*
1982f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
1983f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
1984f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
1985f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
1986f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
1987f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
1988f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
1989f11c0ca5SJohannes Weiner 	 * well.
1990f11c0ca5SJohannes Weiner 	 */
199190cbc250SVladimir Davydov 	if (current_is_kswapd()) {
199290cbc250SVladimir Davydov 		if (!zone_reclaimable(zone))
1993a4d3e9e7SJohannes Weiner 			force_scan = true;
1994eb01aaabSVladimir Davydov 		if (!mem_cgroup_online(memcg))
199590cbc250SVladimir Davydov 			force_scan = true;
199690cbc250SVladimir Davydov 	}
199789b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
1998a4d3e9e7SJohannes Weiner 		force_scan = true;
199976a33fc3SShaohua Li 
200076a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2001d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
20029a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
200376a33fc3SShaohua Li 		goto out;
200476a33fc3SShaohua Li 	}
20054f98a2feSRik van Riel 
200610316b31SJohannes Weiner 	/*
200710316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
200810316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
200910316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
201010316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
201110316b31SJohannes Weiner 	 * too expensive.
201210316b31SJohannes Weiner 	 */
201302695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
20149a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
201510316b31SJohannes Weiner 		goto out;
201610316b31SJohannes Weiner 	}
201710316b31SJohannes Weiner 
201810316b31SJohannes Weiner 	/*
201910316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
202010316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
202110316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
202210316b31SJohannes Weiner 	 */
202302695175SJohannes Weiner 	if (!sc->priority && swappiness) {
20249a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
202510316b31SJohannes Weiner 		goto out;
202610316b31SJohannes Weiner 	}
202710316b31SJohannes Weiner 
202811d16c25SJohannes Weiner 	/*
202962376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
203062376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
203162376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
203262376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
203362376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
203462376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
203562376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
203662376251SJohannes Weiner 	 */
203762376251SJohannes Weiner 	if (global_reclaim(sc)) {
20382ab051e1SJerome Marchand 		unsigned long zonefile;
20392ab051e1SJerome Marchand 		unsigned long zonefree;
204062376251SJohannes Weiner 
20412ab051e1SJerome Marchand 		zonefree = zone_page_state(zone, NR_FREE_PAGES);
20422ab051e1SJerome Marchand 		zonefile = zone_page_state(zone, NR_ACTIVE_FILE) +
20432ab051e1SJerome Marchand 			   zone_page_state(zone, NR_INACTIVE_FILE);
20442ab051e1SJerome Marchand 
20452ab051e1SJerome Marchand 		if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) {
204662376251SJohannes Weiner 			scan_balance = SCAN_ANON;
204762376251SJohannes Weiner 			goto out;
204862376251SJohannes Weiner 		}
204962376251SJohannes Weiner 	}
205062376251SJohannes Weiner 
205162376251SJohannes Weiner 	/*
2052316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2053316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2054316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2055316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2056316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2057316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2058316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2059e9868505SRik van Riel 	 */
2060316bda0eSVladimir Davydov 	if (!inactive_file_is_low(lruvec) &&
206123047a96SJohannes Weiner 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
20629a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2063e9868505SRik van Riel 		goto out;
20644f98a2feSRik van Riel 	}
20654f98a2feSRik van Riel 
20669a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
20679a265114SJohannes Weiner 
20684f98a2feSRik van Riel 	/*
206958c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
207058c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
207158c37f6eSKOSAKI Motohiro 	 */
207202695175SJohannes Weiner 	anon_prio = swappiness;
207375b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
207458c37f6eSKOSAKI Motohiro 
207558c37f6eSKOSAKI Motohiro 	/*
20764f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
20774f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
20784f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
20794f98a2feSRik van Riel 	 *
20804f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
20814f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
20824f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
20834f98a2feSRik van Riel 	 *
20844f98a2feSRik van Riel 	 * anon in [0], file in [1]
20854f98a2feSRik van Riel 	 */
20862ab051e1SJerome Marchand 
208723047a96SJohannes Weiner 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
208823047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
208923047a96SJohannes Weiner 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
209023047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
20912ab051e1SJerome Marchand 
209290126375SKonstantin Khlebnikov 	spin_lock_irq(&zone->lru_lock);
209358c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
20946e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
20956e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
20964f98a2feSRik van Riel 	}
20974f98a2feSRik van Riel 
20986e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
20996e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
21006e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
21014f98a2feSRik van Riel 	}
21024f98a2feSRik van Riel 
21034f98a2feSRik van Riel 	/*
210400d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
210500d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
210600d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
21074f98a2feSRik van Riel 	 */
2108fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
21096e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
21104f98a2feSRik van Riel 
2111fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
21126e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
211390126375SKonstantin Khlebnikov 	spin_unlock_irq(&zone->lru_lock);
21144f98a2feSRik van Riel 
211576a33fc3SShaohua Li 	fraction[0] = ap;
211676a33fc3SShaohua Li 	fraction[1] = fp;
211776a33fc3SShaohua Li 	denominator = ap + fp + 1;
211876a33fc3SShaohua Li out:
21196f04f48dSSuleiman Souhlal 	some_scanned = false;
21206f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
21216f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
21226b4f7799SJohannes Weiner 		*lru_pages = 0;
21234111304dSHugh Dickins 		for_each_evictable_lru(lru) {
21244111304dSHugh Dickins 			int file = is_file_lru(lru);
2125d778df51SJohannes Weiner 			unsigned long size;
212676a33fc3SShaohua Li 			unsigned long scan;
212776a33fc3SShaohua Li 
212823047a96SJohannes Weiner 			size = lruvec_lru_size(lruvec, lru);
2129d778df51SJohannes Weiner 			scan = size >> sc->priority;
21309a265114SJohannes Weiner 
21316f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2132d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
21339a265114SJohannes Weiner 
21349a265114SJohannes Weiner 			switch (scan_balance) {
21359a265114SJohannes Weiner 			case SCAN_EQUAL:
21369a265114SJohannes Weiner 				/* Scan lists relative to size */
21379a265114SJohannes Weiner 				break;
21389a265114SJohannes Weiner 			case SCAN_FRACT:
21399a265114SJohannes Weiner 				/*
21409a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
21419a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
21429a265114SJohannes Weiner 				 */
21436f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
21446f04f48dSSuleiman Souhlal 							denominator);
21459a265114SJohannes Weiner 				break;
21469a265114SJohannes Weiner 			case SCAN_FILE:
21479a265114SJohannes Weiner 			case SCAN_ANON:
21489a265114SJohannes Weiner 				/* Scan one type exclusively */
21496b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
21506b4f7799SJohannes Weiner 					size = 0;
21519a265114SJohannes Weiner 					scan = 0;
21526b4f7799SJohannes Weiner 				}
21539a265114SJohannes Weiner 				break;
21549a265114SJohannes Weiner 			default:
21559a265114SJohannes Weiner 				/* Look ma, no brain */
21569a265114SJohannes Weiner 				BUG();
21579a265114SJohannes Weiner 			}
21586b4f7799SJohannes Weiner 
21596b4f7799SJohannes Weiner 			*lru_pages += size;
21604111304dSHugh Dickins 			nr[lru] = scan;
21616b4f7799SJohannes Weiner 
21626f04f48dSSuleiman Souhlal 			/*
21636f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
21646f04f48dSSuleiman Souhlal 			 * if we found something to scan.
21656f04f48dSSuleiman Souhlal 			 */
21666f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
21676f04f48dSSuleiman Souhlal 		}
216876a33fc3SShaohua Li 	}
21696e08a369SWu Fengguang }
21704f98a2feSRik van Riel 
217172b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
217272b252aeSMel Gorman static void init_tlb_ubc(void)
217372b252aeSMel Gorman {
217472b252aeSMel Gorman 	/*
217572b252aeSMel Gorman 	 * This deliberately does not clear the cpumask as it's expensive
217672b252aeSMel Gorman 	 * and unnecessary. If there happens to be data in there then the
217772b252aeSMel Gorman 	 * first SWAP_CLUSTER_MAX pages will send an unnecessary IPI and
217872b252aeSMel Gorman 	 * then will be cleared.
217972b252aeSMel Gorman 	 */
218072b252aeSMel Gorman 	current->tlb_ubc.flush_required = false;
218172b252aeSMel Gorman }
218272b252aeSMel Gorman #else
218372b252aeSMel Gorman static inline void init_tlb_ubc(void)
218472b252aeSMel Gorman {
218572b252aeSMel Gorman }
218672b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
218772b252aeSMel Gorman 
21889b4f98cdSJohannes Weiner /*
21899b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
21909b4f98cdSJohannes Weiner  */
219133377678SVladimir Davydov static void shrink_zone_memcg(struct zone *zone, struct mem_cgroup *memcg,
21926b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
21939b4f98cdSJohannes Weiner {
219433377678SVladimir Davydov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
21959b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2196e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
21979b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
21989b4f98cdSJohannes Weiner 	enum lru_list lru;
21999b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
22009b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
22019b4f98cdSJohannes Weiner 	struct blk_plug plug;
22021a501907SMel Gorman 	bool scan_adjusted;
22039b4f98cdSJohannes Weiner 
220433377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
22059b4f98cdSJohannes Weiner 
2206e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2207e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2208e82e0561SMel Gorman 
22091a501907SMel Gorman 	/*
22101a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
22111a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
22121a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
22131a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
22141a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
22151a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
22161a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
22171a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
22181a501907SMel Gorman 	 * dropped to zero at the first pass.
22191a501907SMel Gorman 	 */
22201a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
22211a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
22221a501907SMel Gorman 
222372b252aeSMel Gorman 	init_tlb_ubc();
222472b252aeSMel Gorman 
22259b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
22269b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
22279b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2228e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2229e82e0561SMel Gorman 		unsigned long nr_scanned;
2230e82e0561SMel Gorman 
22319b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
22329b4f98cdSJohannes Weiner 			if (nr[lru]) {
22339b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
22349b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
22359b4f98cdSJohannes Weiner 
22369b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
22379b4f98cdSJohannes Weiner 							    lruvec, sc);
22389b4f98cdSJohannes Weiner 			}
22399b4f98cdSJohannes Weiner 		}
2240e82e0561SMel Gorman 
2241e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2242e82e0561SMel Gorman 			continue;
2243e82e0561SMel Gorman 
22449b4f98cdSJohannes Weiner 		/*
2245e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
22461a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2247e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2248e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2249e82e0561SMel Gorman 		 * proportional to the original scan target.
2250e82e0561SMel Gorman 		 */
2251e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2252e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2253e82e0561SMel Gorman 
22541a501907SMel Gorman 		/*
22551a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
22561a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
22571a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
22581a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
22591a501907SMel Gorman 		 */
22601a501907SMel Gorman 		if (!nr_file || !nr_anon)
22611a501907SMel Gorman 			break;
22621a501907SMel Gorman 
2263e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2264e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2265e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2266e82e0561SMel Gorman 			lru = LRU_BASE;
2267e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2268e82e0561SMel Gorman 		} else {
2269e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2270e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2271e82e0561SMel Gorman 			lru = LRU_FILE;
2272e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2273e82e0561SMel Gorman 		}
2274e82e0561SMel Gorman 
2275e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2276e82e0561SMel Gorman 		nr[lru] = 0;
2277e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2278e82e0561SMel Gorman 
2279e82e0561SMel Gorman 		/*
2280e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2281e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2282e82e0561SMel Gorman 		 */
2283e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2284e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2285e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2286e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2287e82e0561SMel Gorman 
2288e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2289e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2290e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2291e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2292e82e0561SMel Gorman 
2293e82e0561SMel Gorman 		scan_adjusted = true;
22949b4f98cdSJohannes Weiner 	}
22959b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
22969b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
22979b4f98cdSJohannes Weiner 
22989b4f98cdSJohannes Weiner 	/*
22999b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
23009b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
23019b4f98cdSJohannes Weiner 	 */
23029b4f98cdSJohannes Weiner 	if (inactive_anon_is_low(lruvec))
23039b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
23049b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
23059b4f98cdSJohannes Weiner 
23069b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
23079b4f98cdSJohannes Weiner }
23089b4f98cdSJohannes Weiner 
230923b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
23109e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
231123b9da55SMel Gorman {
2312d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
231323b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
23149e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
231523b9da55SMel Gorman 		return true;
231623b9da55SMel Gorman 
231723b9da55SMel Gorman 	return false;
231823b9da55SMel Gorman }
231923b9da55SMel Gorman 
23204f98a2feSRik van Riel /*
232123b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
232223b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
232323b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
232423b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
232523b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
23263e7d3449SMel Gorman  */
23279b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
23283e7d3449SMel Gorman 					unsigned long nr_reclaimed,
23293e7d3449SMel Gorman 					unsigned long nr_scanned,
23303e7d3449SMel Gorman 					struct scan_control *sc)
23313e7d3449SMel Gorman {
23323e7d3449SMel Gorman 	unsigned long pages_for_compaction;
23333e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
23343e7d3449SMel Gorman 
23353e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
23369e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
23373e7d3449SMel Gorman 		return false;
23383e7d3449SMel Gorman 
23392876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
23402876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
23413e7d3449SMel Gorman 		/*
23422876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
23432876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
23442876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
23452876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
23463e7d3449SMel Gorman 		 */
23473e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
23483e7d3449SMel Gorman 			return false;
23492876592fSMel Gorman 	} else {
23502876592fSMel Gorman 		/*
23512876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
23522876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
23532876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
23542876592fSMel Gorman 		 * pages that were scanned. This will return to the
23552876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
23562876592fSMel Gorman 		 * the resulting allocation attempt fails
23572876592fSMel Gorman 		 */
23582876592fSMel Gorman 		if (!nr_reclaimed)
23592876592fSMel Gorman 			return false;
23602876592fSMel Gorman 	}
23613e7d3449SMel Gorman 
23623e7d3449SMel Gorman 	/*
23633e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
23643e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
23653e7d3449SMel Gorman 	 */
23663e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
23679b4f98cdSJohannes Weiner 	inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
2368ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
23699b4f98cdSJohannes Weiner 		inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
23703e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
23713e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
23723e7d3449SMel Gorman 		return true;
23733e7d3449SMel Gorman 
23743e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2375ebff3980SVlastimil Babka 	switch (compaction_suitable(zone, sc->order, 0, 0)) {
23763e7d3449SMel Gorman 	case COMPACT_PARTIAL:
23773e7d3449SMel Gorman 	case COMPACT_CONTINUE:
23783e7d3449SMel Gorman 		return false;
23793e7d3449SMel Gorman 	default:
23803e7d3449SMel Gorman 		return true;
23813e7d3449SMel Gorman 	}
23823e7d3449SMel Gorman }
23833e7d3449SMel Gorman 
23846b4f7799SJohannes Weiner static bool shrink_zone(struct zone *zone, struct scan_control *sc,
23856b4f7799SJohannes Weiner 			bool is_classzone)
2386f16015fbSJohannes Weiner {
2387cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
23889b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
23892344d7e4SJohannes Weiner 	bool reclaimable = false;
23909b4f98cdSJohannes Weiner 
23919b4f98cdSJohannes Weiner 	do {
23925660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
23935660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
23945660048cSJohannes Weiner 			.zone = zone,
23959e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
23965660048cSJohannes Weiner 		};
23976b4f7799SJohannes Weiner 		unsigned long zone_lru_pages = 0;
2398694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
23995660048cSJohannes Weiner 
24009b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
24019b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
24029b4f98cdSJohannes Weiner 
2403694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2404694fbc0fSAndrew Morton 		do {
24056b4f7799SJohannes Weiner 			unsigned long lru_pages;
24068e8ae645SJohannes Weiner 			unsigned long reclaimed;
2407cb731d6cSVladimir Davydov 			unsigned long scanned;
24089b4f98cdSJohannes Weiner 
2409241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2410241994edSJohannes Weiner 				if (!sc->may_thrash)
2411241994edSJohannes Weiner 					continue;
2412241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2413241994edSJohannes Weiner 			}
2414241994edSJohannes Weiner 
24158e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2416cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
24175660048cSJohannes Weiner 
241833377678SVladimir Davydov 			shrink_zone_memcg(zone, memcg, sc, &lru_pages);
24196b4f7799SJohannes Weiner 			zone_lru_pages += lru_pages;
2420f9be23d6SKonstantin Khlebnikov 
2421cb731d6cSVladimir Davydov 			if (memcg && is_classzone)
2422cb731d6cSVladimir Davydov 				shrink_slab(sc->gfp_mask, zone_to_nid(zone),
2423cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2424cb731d6cSVladimir Davydov 					    lru_pages);
2425cb731d6cSVladimir Davydov 
24268e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
24278e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
24288e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
24298e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
24308e8ae645SJohannes Weiner 
24315660048cSJohannes Weiner 			/*
2432a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2433a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
24349b4f98cdSJohannes Weiner 			 * zone.
2435a394cb8eSMichal Hocko 			 *
2436a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2437a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2438a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2439a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
24405660048cSJohannes Weiner 			 */
2441a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2442a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
24435660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
24445660048cSJohannes Weiner 				break;
24455660048cSJohannes Weiner 			}
2446241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
244770ddf637SAnton Vorontsov 
24486b4f7799SJohannes Weiner 		/*
24496b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
24506b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
24516b4f7799SJohannes Weiner 		 */
2452cb731d6cSVladimir Davydov 		if (global_reclaim(sc) && is_classzone)
2453cb731d6cSVladimir Davydov 			shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL,
24546b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
24556b4f7799SJohannes Weiner 				    zone_lru_pages);
24566b4f7799SJohannes Weiner 
24576b4f7799SJohannes Weiner 		if (reclaim_state) {
2458cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
24596b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
24606b4f7799SJohannes Weiner 		}
24616b4f7799SJohannes Weiner 
24628e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
24638e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
246470ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
246570ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
246670ddf637SAnton Vorontsov 
24672344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
24682344d7e4SJohannes Weiner 			reclaimable = true;
24692344d7e4SJohannes Weiner 
24709b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
24719b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
24722344d7e4SJohannes Weiner 
24732344d7e4SJohannes Weiner 	return reclaimable;
2474f16015fbSJohannes Weiner }
2475f16015fbSJohannes Weiner 
247653853e2dSVlastimil Babka /*
247753853e2dSVlastimil Babka  * Returns true if compaction should go ahead for a high-order request, or
247853853e2dSVlastimil Babka  * the high-order allocation would succeed without compaction.
247953853e2dSVlastimil Babka  */
24800b06496aSJohannes Weiner static inline bool compaction_ready(struct zone *zone, int order)
2481fe4b1b24SMel Gorman {
2482fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2483fe4b1b24SMel Gorman 	bool watermark_ok;
2484fe4b1b24SMel Gorman 
2485fe4b1b24SMel Gorman 	/*
2486fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2487fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2488fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2489fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2490fe4b1b24SMel Gorman 	 */
24914be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
24924be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
24930b06496aSJohannes Weiner 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
2494e2b19197SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0);
2495fe4b1b24SMel Gorman 
2496fe4b1b24SMel Gorman 	/*
2497fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2498fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2499fe4b1b24SMel Gorman 	 */
25000b06496aSJohannes Weiner 	if (compaction_deferred(zone, order))
2501fe4b1b24SMel Gorman 		return watermark_ok;
2502fe4b1b24SMel Gorman 
250353853e2dSVlastimil Babka 	/*
250453853e2dSVlastimil Babka 	 * If compaction is not ready to start and allocation is not likely
250553853e2dSVlastimil Babka 	 * to succeed without it, then keep reclaiming.
250653853e2dSVlastimil Babka 	 */
2507ebff3980SVlastimil Babka 	if (compaction_suitable(zone, order, 0, 0) == COMPACT_SKIPPED)
2508fe4b1b24SMel Gorman 		return false;
2509fe4b1b24SMel Gorman 
2510fe4b1b24SMel Gorman 	return watermark_ok;
2511fe4b1b24SMel Gorman }
2512fe4b1b24SMel Gorman 
25131da177e4SLinus Torvalds /*
25141da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
25151da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
25161da177e4SLinus Torvalds  * request.
25171da177e4SLinus Torvalds  *
251841858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
251941858966SMel Gorman  * Because:
25201da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
25211da177e4SLinus Torvalds  *    allocation or
252241858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
252341858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
252441858966SMel Gorman  *    zone defense algorithm.
25251da177e4SLinus Torvalds  *
25261da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
25271da177e4SLinus Torvalds  * scan then give up on it.
25282344d7e4SJohannes Weiner  *
25292344d7e4SJohannes Weiner  * Returns true if a zone was reclaimable.
25301da177e4SLinus Torvalds  */
25312344d7e4SJohannes Weiner static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
25321da177e4SLinus Torvalds {
2533dd1a239fSMel Gorman 	struct zoneref *z;
253454a6eb5cSMel Gorman 	struct zone *zone;
25350608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
25360608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2537619d0d76SWeijie Yang 	gfp_t orig_mask;
25389bbc04eeSWeijie Yang 	enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
25392344d7e4SJohannes Weiner 	bool reclaimable = false;
25401cfb419bSKAMEZAWA Hiroyuki 
2541cc715d99SMel Gorman 	/*
2542cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2543cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2544cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2545cc715d99SMel Gorman 	 */
2546619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2547cc715d99SMel Gorman 	if (buffer_heads_over_limit)
2548cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2549cc715d99SMel Gorman 
2550d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
25516b4f7799SJohannes Weiner 					requested_highidx, sc->nodemask) {
25526b4f7799SJohannes Weiner 		enum zone_type classzone_idx;
25536b4f7799SJohannes Weiner 
2554f3fe6512SCon Kolivas 		if (!populated_zone(zone))
25551da177e4SLinus Torvalds 			continue;
25566b4f7799SJohannes Weiner 
25576b4f7799SJohannes Weiner 		classzone_idx = requested_highidx;
25586b4f7799SJohannes Weiner 		while (!populated_zone(zone->zone_pgdat->node_zones +
25596b4f7799SJohannes Weiner 							classzone_idx))
25606b4f7799SJohannes Weiner 			classzone_idx--;
25616b4f7799SJohannes Weiner 
25621cfb419bSKAMEZAWA Hiroyuki 		/*
25631cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
25641cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
25651cfb419bSKAMEZAWA Hiroyuki 		 */
256689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2567344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2568344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
25691da177e4SLinus Torvalds 				continue;
257065ec02cbSVladimir Davydov 
25716e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
25726e543d57SLisa Du 			    !zone_reclaimable(zone))
25731da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
25740b06496aSJohannes Weiner 
2575e0887c19SRik van Riel 			/*
2576e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2577e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2578e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2579e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2580e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2581c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2582c7cfa37bSCopot Alexandru 			 * page allocations.
2583e0887c19SRik van Riel 			 */
25840b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
25850b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
25860b06496aSJohannes Weiner 			    zonelist_zone_idx(z) <= requested_highidx &&
25870b06496aSJohannes Weiner 			    compaction_ready(zone, sc->order)) {
25880b06496aSJohannes Weiner 				sc->compaction_ready = true;
2589e0887c19SRik van Riel 				continue;
2590e0887c19SRik van Riel 			}
25910b06496aSJohannes Weiner 
25920608f43dSAndrew Morton 			/*
25930608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
25940608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
25950608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
25960608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
25970608f43dSAndrew Morton 			 */
25980608f43dSAndrew Morton 			nr_soft_scanned = 0;
25990608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
26000608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
26010608f43dSAndrew Morton 						&nr_soft_scanned);
26020608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
26030608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
26042344d7e4SJohannes Weiner 			if (nr_soft_reclaimed)
26052344d7e4SJohannes Weiner 				reclaimable = true;
2606ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2607ac34a1a3SKAMEZAWA Hiroyuki 		}
2608d149e3b2SYing Han 
26096b4f7799SJohannes Weiner 		if (shrink_zone(zone, sc, zone_idx(zone) == classzone_idx))
26102344d7e4SJohannes Weiner 			reclaimable = true;
26112344d7e4SJohannes Weiner 
26122344d7e4SJohannes Weiner 		if (global_reclaim(sc) &&
26132344d7e4SJohannes Weiner 		    !reclaimable && zone_reclaimable(zone))
26142344d7e4SJohannes Weiner 			reclaimable = true;
26151da177e4SLinus Torvalds 	}
2616e0c23279SMel Gorman 
261765ec02cbSVladimir Davydov 	/*
2618619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2619619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2620619d0d76SWeijie Yang 	 */
2621619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
2622d1908362SMinchan Kim 
26232344d7e4SJohannes Weiner 	return reclaimable;
26241da177e4SLinus Torvalds }
26251da177e4SLinus Torvalds 
26261da177e4SLinus Torvalds /*
26271da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
26281da177e4SLinus Torvalds  *
26291da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
26301da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
26311da177e4SLinus Torvalds  *
26321da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
26331da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
26345b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
26355b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
26365b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
26375b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2638a41f24eaSNishanth Aravamudan  *
2639a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2640a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
26411da177e4SLinus Torvalds  */
2642dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
26433115cd91SVladimir Davydov 					  struct scan_control *sc)
26441da177e4SLinus Torvalds {
2645241994edSJohannes Weiner 	int initial_priority = sc->priority;
264669e05944SAndrew Morton 	unsigned long total_scanned = 0;
264722fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
26482344d7e4SJohannes Weiner 	bool zones_reclaimable;
2649241994edSJohannes Weiner retry:
2650873b4771SKeika Kobayashi 	delayacct_freepages_start();
2651873b4771SKeika Kobayashi 
265289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2653f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
26541da177e4SLinus Torvalds 
26559e3b2f8cSKonstantin Khlebnikov 	do {
265670ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
265770ddf637SAnton Vorontsov 				sc->priority);
265866e1707bSBalbir Singh 		sc->nr_scanned = 0;
26592344d7e4SJohannes Weiner 		zones_reclaimable = shrink_zones(zonelist, sc);
2660e0c23279SMel Gorman 
266166e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2662bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
26630b06496aSJohannes Weiner 			break;
26640b06496aSJohannes Weiner 
26650b06496aSJohannes Weiner 		if (sc->compaction_ready)
26660b06496aSJohannes Weiner 			break;
26671da177e4SLinus Torvalds 
26681da177e4SLinus Torvalds 		/*
26690e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
26700e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
26710e50ce3bSMinchan Kim 		 */
26720e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
26730e50ce3bSMinchan Kim 			sc->may_writepage = 1;
26740e50ce3bSMinchan Kim 
26750e50ce3bSMinchan Kim 		/*
26761da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
26771da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
26781da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
26791da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
26801da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
26811da177e4SLinus Torvalds 		 */
268222fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
268322fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
26840e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
26850e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
268666e1707bSBalbir Singh 			sc->may_writepage = 1;
26871da177e4SLinus Torvalds 		}
26880b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2689bb21c7ceSKOSAKI Motohiro 
2690873b4771SKeika Kobayashi 	delayacct_freepages_end();
2691873b4771SKeika Kobayashi 
2692bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2693bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2694bb21c7ceSKOSAKI Motohiro 
26950cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
26960b06496aSJohannes Weiner 	if (sc->compaction_ready)
26977335084dSMel Gorman 		return 1;
26987335084dSMel Gorman 
2699241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2700241994edSJohannes Weiner 	if (!sc->may_thrash) {
2701241994edSJohannes Weiner 		sc->priority = initial_priority;
2702241994edSJohannes Weiner 		sc->may_thrash = 1;
2703241994edSJohannes Weiner 		goto retry;
2704241994edSJohannes Weiner 	}
2705241994edSJohannes Weiner 
27062344d7e4SJohannes Weiner 	/* Any of the zones still reclaimable?  Don't OOM. */
27072344d7e4SJohannes Weiner 	if (zones_reclaimable)
2708bb21c7ceSKOSAKI Motohiro 		return 1;
2709bb21c7ceSKOSAKI Motohiro 
2710bb21c7ceSKOSAKI Motohiro 	return 0;
27111da177e4SLinus Torvalds }
27121da177e4SLinus Torvalds 
27135515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
27145515061dSMel Gorman {
27155515061dSMel Gorman 	struct zone *zone;
27165515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
27175515061dSMel Gorman 	unsigned long free_pages = 0;
27185515061dSMel Gorman 	int i;
27195515061dSMel Gorman 	bool wmark_ok;
27205515061dSMel Gorman 
27215515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
27225515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2723f012a84aSNishanth Aravamudan 		if (!populated_zone(zone) ||
2724f012a84aSNishanth Aravamudan 		    zone_reclaimable_pages(zone) == 0)
2725675becceSMel Gorman 			continue;
2726675becceSMel Gorman 
27275515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
27285515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
27295515061dSMel Gorman 	}
27305515061dSMel Gorman 
2731675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2732675becceSMel Gorman 	if (!pfmemalloc_reserve)
2733675becceSMel Gorman 		return true;
2734675becceSMel Gorman 
27355515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
27365515061dSMel Gorman 
27375515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
27385515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
27395515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
27405515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
27415515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
27425515061dSMel Gorman 	}
27435515061dSMel Gorman 
27445515061dSMel Gorman 	return wmark_ok;
27455515061dSMel Gorman }
27465515061dSMel Gorman 
27475515061dSMel Gorman /*
27485515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
27495515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
27505515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
275150694c28SMel Gorman  * when the low watermark is reached.
275250694c28SMel Gorman  *
275350694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
275450694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
27555515061dSMel Gorman  */
275650694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
27575515061dSMel Gorman 					nodemask_t *nodemask)
27585515061dSMel Gorman {
2759675becceSMel Gorman 	struct zoneref *z;
27605515061dSMel Gorman 	struct zone *zone;
2761675becceSMel Gorman 	pg_data_t *pgdat = NULL;
27625515061dSMel Gorman 
27635515061dSMel Gorman 	/*
27645515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
27655515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
27665515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
27675515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
27685515061dSMel Gorman 	 * processes to block on log_wait_commit().
27695515061dSMel Gorman 	 */
27705515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
277150694c28SMel Gorman 		goto out;
277250694c28SMel Gorman 
277350694c28SMel Gorman 	/*
277450694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
277550694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
277650694c28SMel Gorman 	 */
277750694c28SMel Gorman 	if (fatal_signal_pending(current))
277850694c28SMel Gorman 		goto out;
27795515061dSMel Gorman 
2780675becceSMel Gorman 	/*
2781675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2782675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2783675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2784675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2785675becceSMel Gorman 	 *
2786675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2787675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2788675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2789675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2790675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2791675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2792675becceSMel Gorman 	 * should make reasonable progress.
2793675becceSMel Gorman 	 */
2794675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
279517636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2796675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2797675becceSMel Gorman 			continue;
2798675becceSMel Gorman 
2799675becceSMel Gorman 		/* Throttle based on the first usable node */
28005515061dSMel Gorman 		pgdat = zone->zone_pgdat;
28015515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
280250694c28SMel Gorman 			goto out;
2803675becceSMel Gorman 		break;
2804675becceSMel Gorman 	}
2805675becceSMel Gorman 
2806675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2807675becceSMel Gorman 	if (!pgdat)
2808675becceSMel Gorman 		goto out;
28095515061dSMel Gorman 
281068243e76SMel Gorman 	/* Account for the throttling */
281168243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
281268243e76SMel Gorman 
28135515061dSMel Gorman 	/*
28145515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
28155515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
28165515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
28175515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
28185515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
28195515061dSMel Gorman 	 * second before continuing.
28205515061dSMel Gorman 	 */
28215515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
28225515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
28235515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
282450694c28SMel Gorman 
282550694c28SMel Gorman 		goto check_pending;
28265515061dSMel Gorman 	}
28275515061dSMel Gorman 
28285515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
28295515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
28305515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
283150694c28SMel Gorman 
283250694c28SMel Gorman check_pending:
283350694c28SMel Gorman 	if (fatal_signal_pending(current))
283450694c28SMel Gorman 		return true;
283550694c28SMel Gorman 
283650694c28SMel Gorman out:
283750694c28SMel Gorman 	return false;
28385515061dSMel Gorman }
28395515061dSMel Gorman 
2840dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2841327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
284266e1707bSBalbir Singh {
284333906bc5SMel Gorman 	unsigned long nr_reclaimed;
284466e1707bSBalbir Singh 	struct scan_control sc = {
284522fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2846ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2847ee814fe2SJohannes Weiner 		.order = order,
2848ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2849ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2850ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2851a6dc60f8SJohannes Weiner 		.may_unmap = 1,
28522e2e4259SKOSAKI Motohiro 		.may_swap = 1,
285366e1707bSBalbir Singh 	};
285466e1707bSBalbir Singh 
28555515061dSMel Gorman 	/*
285650694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
285750694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
285850694c28SMel Gorman 	 * point.
28595515061dSMel Gorman 	 */
286050694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
28615515061dSMel Gorman 		return 1;
28625515061dSMel Gorman 
286333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
286433906bc5SMel Gorman 				sc.may_writepage,
286533906bc5SMel Gorman 				gfp_mask);
286633906bc5SMel Gorman 
28673115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
286833906bc5SMel Gorman 
286933906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
287033906bc5SMel Gorman 
287133906bc5SMel Gorman 	return nr_reclaimed;
287266e1707bSBalbir Singh }
287366e1707bSBalbir Singh 
2874c255a458SAndrew Morton #ifdef CONFIG_MEMCG
287566e1707bSBalbir Singh 
287672835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
28774e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
28780ae5e89cSYing Han 						struct zone *zone,
28790ae5e89cSYing Han 						unsigned long *nr_scanned)
28804e416953SBalbir Singh {
28814e416953SBalbir Singh 	struct scan_control sc = {
2882b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2883ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
28844e416953SBalbir Singh 		.may_writepage = !laptop_mode,
28854e416953SBalbir Singh 		.may_unmap = 1,
28864e416953SBalbir Singh 		.may_swap = !noswap,
28874e416953SBalbir Singh 	};
28886b4f7799SJohannes Weiner 	unsigned long lru_pages;
28890ae5e89cSYing Han 
28904e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
28914e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2892bdce6d9eSKOSAKI Motohiro 
28939e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2894bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2895bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2896bdce6d9eSKOSAKI Motohiro 
28974e416953SBalbir Singh 	/*
28984e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
28994e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
29004e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
29014e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
29024e416953SBalbir Singh 	 * the priority and make it zero.
29034e416953SBalbir Singh 	 */
290433377678SVladimir Davydov 	shrink_zone_memcg(zone, memcg, &sc, &lru_pages);
2905bdce6d9eSKOSAKI Motohiro 
2906bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2907bdce6d9eSKOSAKI Motohiro 
29080ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
29094e416953SBalbir Singh 	return sc.nr_reclaimed;
29104e416953SBalbir Singh }
29114e416953SBalbir Singh 
291272835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2913b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
29148c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2915b70a2a21SJohannes Weiner 					   bool may_swap)
291666e1707bSBalbir Singh {
29174e416953SBalbir Singh 	struct zonelist *zonelist;
2918bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2919889976dbSYing Han 	int nid;
292066e1707bSBalbir Singh 	struct scan_control sc = {
2921b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2922ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2923ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2924ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2925ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
292666e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2927a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2928b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2929a09ed5e0SYing Han 	};
293066e1707bSBalbir Singh 
2931889976dbSYing Han 	/*
2932889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2933889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2934889976dbSYing Han 	 * scan does not need to be the current node.
2935889976dbSYing Han 	 */
293672835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2937889976dbSYing Han 
2938889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2939bdce6d9eSKOSAKI Motohiro 
2940bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2941bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2942bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2943bdce6d9eSKOSAKI Motohiro 
29443115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2945bdce6d9eSKOSAKI Motohiro 
2946bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2947bdce6d9eSKOSAKI Motohiro 
2948bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
294966e1707bSBalbir Singh }
295066e1707bSBalbir Singh #endif
295166e1707bSBalbir Singh 
29529e3b2f8cSKonstantin Khlebnikov static void age_active_anon(struct zone *zone, struct scan_control *sc)
2953f16015fbSJohannes Weiner {
2954b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2955b95a2f2dSJohannes Weiner 
2956b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2957b95a2f2dSJohannes Weiner 		return;
2958b95a2f2dSJohannes Weiner 
2959b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2960b95a2f2dSJohannes Weiner 	do {
2961c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2962f16015fbSJohannes Weiner 
2963c56d5c7dSKonstantin Khlebnikov 		if (inactive_anon_is_low(lruvec))
29641a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
29659e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2966b95a2f2dSJohannes Weiner 
2967b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
2968b95a2f2dSJohannes Weiner 	} while (memcg);
2969f16015fbSJohannes Weiner }
2970f16015fbSJohannes Weiner 
2971*accf6242SVlastimil Babka static bool zone_balanced(struct zone *zone, int order, bool highorder,
297260cefed4SJohannes Weiner 			unsigned long balance_gap, int classzone_idx)
297360cefed4SJohannes Weiner {
2974*accf6242SVlastimil Babka 	unsigned long mark = high_wmark_pages(zone) + balance_gap;
297560cefed4SJohannes Weiner 
2976*accf6242SVlastimil Babka 	/*
2977*accf6242SVlastimil Babka 	 * When checking from pgdat_balanced(), kswapd should stop and sleep
2978*accf6242SVlastimil Babka 	 * when it reaches the high order-0 watermark and let kcompactd take
2979*accf6242SVlastimil Babka 	 * over. Other callers such as wakeup_kswapd() want to determine the
2980*accf6242SVlastimil Babka 	 * true high-order watermark.
2981*accf6242SVlastimil Babka 	 */
2982*accf6242SVlastimil Babka 	if (IS_ENABLED(CONFIG_COMPACTION) && !highorder) {
2983*accf6242SVlastimil Babka 		mark += (1UL << order);
2984*accf6242SVlastimil Babka 		order = 0;
2985*accf6242SVlastimil Babka 	}
298660cefed4SJohannes Weiner 
2987*accf6242SVlastimil Babka 	return zone_watermark_ok_safe(zone, order, mark, classzone_idx);
298860cefed4SJohannes Weiner }
298960cefed4SJohannes Weiner 
29901741c877SMel Gorman /*
29914ae0a48bSZlatko Calusic  * pgdat_balanced() is used when checking if a node is balanced.
29924ae0a48bSZlatko Calusic  *
29934ae0a48bSZlatko Calusic  * For order-0, all zones must be balanced!
29944ae0a48bSZlatko Calusic  *
29954ae0a48bSZlatko Calusic  * For high-order allocations only zones that meet watermarks and are in a
29964ae0a48bSZlatko Calusic  * zone allowed by the callers classzone_idx are added to balanced_pages. The
29974ae0a48bSZlatko Calusic  * total of balanced pages must be at least 25% of the zones allowed by
29984ae0a48bSZlatko Calusic  * classzone_idx for the node to be considered balanced. Forcing all zones to
29994ae0a48bSZlatko Calusic  * be balanced for high orders can cause excessive reclaim when there are
30004ae0a48bSZlatko Calusic  * imbalanced zones.
30011741c877SMel Gorman  * The choice of 25% is due to
30021741c877SMel Gorman  *   o a 16M DMA zone that is balanced will not balance a zone on any
30031741c877SMel Gorman  *     reasonable sized machine
30041741c877SMel Gorman  *   o On all other machines, the top zone must be at least a reasonable
300525985edcSLucas De Marchi  *     percentage of the middle zones. For example, on 32-bit x86, highmem
30061741c877SMel Gorman  *     would need to be at least 256M for it to be balance a whole node.
30071741c877SMel Gorman  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
30081741c877SMel Gorman  *     to balance a node on its own. These seemed like reasonable ratios.
30091741c877SMel Gorman  */
30104ae0a48bSZlatko Calusic static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
30111741c877SMel Gorman {
3012b40da049SJiang Liu 	unsigned long managed_pages = 0;
30134ae0a48bSZlatko Calusic 	unsigned long balanced_pages = 0;
30141741c877SMel Gorman 	int i;
30151741c877SMel Gorman 
30164ae0a48bSZlatko Calusic 	/* Check the watermark levels */
30174ae0a48bSZlatko Calusic 	for (i = 0; i <= classzone_idx; i++) {
30184ae0a48bSZlatko Calusic 		struct zone *zone = pgdat->node_zones + i;
30191741c877SMel Gorman 
30204ae0a48bSZlatko Calusic 		if (!populated_zone(zone))
30214ae0a48bSZlatko Calusic 			continue;
30224ae0a48bSZlatko Calusic 
3023b40da049SJiang Liu 		managed_pages += zone->managed_pages;
30244ae0a48bSZlatko Calusic 
30254ae0a48bSZlatko Calusic 		/*
30264ae0a48bSZlatko Calusic 		 * A special case here:
30274ae0a48bSZlatko Calusic 		 *
30284ae0a48bSZlatko Calusic 		 * balance_pgdat() skips over all_unreclaimable after
30294ae0a48bSZlatko Calusic 		 * DEF_PRIORITY. Effectively, it considers them balanced so
30304ae0a48bSZlatko Calusic 		 * they must be considered balanced here as well!
30314ae0a48bSZlatko Calusic 		 */
30326e543d57SLisa Du 		if (!zone_reclaimable(zone)) {
3033b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
30344ae0a48bSZlatko Calusic 			continue;
30354ae0a48bSZlatko Calusic 		}
30364ae0a48bSZlatko Calusic 
3037*accf6242SVlastimil Babka 		if (zone_balanced(zone, order, false, 0, i))
3038b40da049SJiang Liu 			balanced_pages += zone->managed_pages;
30394ae0a48bSZlatko Calusic 		else if (!order)
30404ae0a48bSZlatko Calusic 			return false;
30414ae0a48bSZlatko Calusic 	}
30424ae0a48bSZlatko Calusic 
30434ae0a48bSZlatko Calusic 	if (order)
3044b40da049SJiang Liu 		return balanced_pages >= (managed_pages >> 2);
30454ae0a48bSZlatko Calusic 	else
30464ae0a48bSZlatko Calusic 		return true;
30471741c877SMel Gorman }
30481741c877SMel Gorman 
30495515061dSMel Gorman /*
30505515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30515515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30525515061dSMel Gorman  *
30535515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30545515061dSMel Gorman  */
30555515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
3056dc83edd9SMel Gorman 					int classzone_idx)
3057f50de2d3SMel Gorman {
3058f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
3059f50de2d3SMel Gorman 	if (remaining)
30605515061dSMel Gorman 		return false;
30615515061dSMel Gorman 
30625515061dSMel Gorman 	/*
30639e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
30649e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
30659e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
30669e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
30679e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
30689e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
30699e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
30709e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
30719e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
30729e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
30739e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
30745515061dSMel Gorman 	 */
30759e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
30769e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3077f50de2d3SMel Gorman 
30784ae0a48bSZlatko Calusic 	return pgdat_balanced(pgdat, order, classzone_idx);
3079f50de2d3SMel Gorman }
3080f50de2d3SMel Gorman 
30811da177e4SLinus Torvalds /*
308275485363SMel Gorman  * kswapd shrinks the zone by the number of pages required to reach
308375485363SMel Gorman  * the high watermark.
3084b8e83b94SMel Gorman  *
3085b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3086283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3087283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
308875485363SMel Gorman  */
3089b8e83b94SMel Gorman static bool kswapd_shrink_zone(struct zone *zone,
30907c954f6dSMel Gorman 			       int classzone_idx,
3091*accf6242SVlastimil Babka 			       struct scan_control *sc)
309275485363SMel Gorman {
30937c954f6dSMel Gorman 	unsigned long balance_gap;
30947c954f6dSMel Gorman 	bool lowmem_pressure;
309575485363SMel Gorman 
309675485363SMel Gorman 	/* Reclaim above the high watermark. */
309775485363SMel Gorman 	sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
30987c954f6dSMel Gorman 
30997c954f6dSMel Gorman 	/*
31007c954f6dSMel Gorman 	 * We put equal pressure on every zone, unless one zone has way too
31017c954f6dSMel Gorman 	 * many pages free already. The "too many pages" is defined as the
31027c954f6dSMel Gorman 	 * high wmark plus a "gap" where the gap is either the low
31037c954f6dSMel Gorman 	 * watermark or 1% of the zone, whichever is smaller.
31047c954f6dSMel Gorman 	 */
31054be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
31064be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
31077c954f6dSMel Gorman 
31087c954f6dSMel Gorman 	/*
31097c954f6dSMel Gorman 	 * If there is no low memory pressure or the zone is balanced then no
31107c954f6dSMel Gorman 	 * reclaim is necessary
31117c954f6dSMel Gorman 	 */
31127c954f6dSMel Gorman 	lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
3113*accf6242SVlastimil Babka 	if (!lowmem_pressure && zone_balanced(zone, sc->order, false,
31147c954f6dSMel Gorman 						balance_gap, classzone_idx))
31157c954f6dSMel Gorman 		return true;
31167c954f6dSMel Gorman 
31176b4f7799SJohannes Weiner 	shrink_zone(zone, sc, zone_idx(zone) == classzone_idx);
311875485363SMel Gorman 
311957054651SJohannes Weiner 	clear_bit(ZONE_WRITEBACK, &zone->flags);
3120283aba9fSMel Gorman 
31217c954f6dSMel Gorman 	/*
31227c954f6dSMel Gorman 	 * If a zone reaches its high watermark, consider it to be no longer
31237c954f6dSMel Gorman 	 * congested. It's possible there are dirty pages backed by congested
31247c954f6dSMel Gorman 	 * BDIs but as pressure is relieved, speculatively avoid congestion
31257c954f6dSMel Gorman 	 * waits.
31267c954f6dSMel Gorman 	 */
31276e543d57SLisa Du 	if (zone_reclaimable(zone) &&
3128*accf6242SVlastimil Babka 	    zone_balanced(zone, sc->order, false, 0, classzone_idx)) {
312957054651SJohannes Weiner 		clear_bit(ZONE_CONGESTED, &zone->flags);
313057054651SJohannes Weiner 		clear_bit(ZONE_DIRTY, &zone->flags);
31317c954f6dSMel Gorman 	}
31327c954f6dSMel Gorman 
3133b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
313475485363SMel Gorman }
313575485363SMel Gorman 
313675485363SMel Gorman /*
31371da177e4SLinus Torvalds  * For kswapd, balance_pgdat() will work across all this node's zones until
313841858966SMel Gorman  * they are all at high_wmark_pages(zone).
31391da177e4SLinus Torvalds  *
3140*accf6242SVlastimil Babka  * Returns the highest zone idx kswapd was reclaiming at
31411da177e4SLinus Torvalds  *
31421da177e4SLinus Torvalds  * There is special handling here for zones which are full of pinned pages.
31431da177e4SLinus Torvalds  * This can happen if the pages are all mlocked, or if they are all used by
31441da177e4SLinus Torvalds  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
31451da177e4SLinus Torvalds  * What we do is to detect the case where all pages in the zone have been
31461da177e4SLinus Torvalds  * scanned twice and there has been zero successful reclaim.  Mark the zone as
31471da177e4SLinus Torvalds  * dead and from now on, only perform a short scan.  Basically we're polling
31481da177e4SLinus Torvalds  * the zone for when the problem goes away.
31491da177e4SLinus Torvalds  *
31501da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
315141858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
315241858966SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
315341858966SMel Gorman  * lower zones regardless of the number of free pages in the lower zones. This
315441858966SMel Gorman  * interoperates with the page allocator fallback scheme to ensure that aging
315541858966SMel Gorman  * of pages is balanced across the zones.
31561da177e4SLinus Torvalds  */
3157*accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
31581da177e4SLinus Torvalds {
31591da177e4SLinus Torvalds 	int i;
316099504748SMel Gorman 	int end_zone = 0;	/* Inclusive.  0 = ZONE_DMA */
31610608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31620608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3163179e9639SAndrew Morton 	struct scan_control sc = {
3164179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3165ee814fe2SJohannes Weiner 		.order = order,
3166b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3167ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3168a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31692e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3170179e9639SAndrew Morton 	};
3171f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
31721da177e4SLinus Torvalds 
31739e3b2f8cSKonstantin Khlebnikov 	do {
3174b8e83b94SMel Gorman 		bool raise_priority = true;
3175b8e83b94SMel Gorman 
3176b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
31771da177e4SLinus Torvalds 
31781da177e4SLinus Torvalds 		/*
31791da177e4SLinus Torvalds 		 * Scan in the highmem->dma direction for the highest
31801da177e4SLinus Torvalds 		 * zone which needs scanning
31811da177e4SLinus Torvalds 		 */
31821da177e4SLinus Torvalds 		for (i = pgdat->nr_zones - 1; i >= 0; i--) {
31831da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
31841da177e4SLinus Torvalds 
3185f3fe6512SCon Kolivas 			if (!populated_zone(zone))
31861da177e4SLinus Torvalds 				continue;
31871da177e4SLinus Torvalds 
31886e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
31896e543d57SLisa Du 			    !zone_reclaimable(zone))
31901da177e4SLinus Torvalds 				continue;
31911da177e4SLinus Torvalds 
3192556adecbSRik van Riel 			/*
3193556adecbSRik van Riel 			 * Do some background aging of the anon list, to give
3194556adecbSRik van Riel 			 * pages a chance to be referenced before reclaiming.
3195556adecbSRik van Riel 			 */
31969e3b2f8cSKonstantin Khlebnikov 			age_active_anon(zone, &sc);
3197556adecbSRik van Riel 
3198cc715d99SMel Gorman 			/*
3199cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
3200cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
3201cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
3202cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
3203cc715d99SMel Gorman 			 */
3204cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
3205cc715d99SMel Gorman 				end_zone = i;
3206cc715d99SMel Gorman 				break;
3207cc715d99SMel Gorman 			}
3208cc715d99SMel Gorman 
3209*accf6242SVlastimil Babka 			if (!zone_balanced(zone, order, false, 0, 0)) {
32101da177e4SLinus Torvalds 				end_zone = i;
3211e1dbeda6SAndrew Morton 				break;
3212439423f6SShaohua Li 			} else {
3213d43006d5SMel Gorman 				/*
3214d43006d5SMel Gorman 				 * If balanced, clear the dirty and congested
3215d43006d5SMel Gorman 				 * flags
3216d43006d5SMel Gorman 				 */
321757054651SJohannes Weiner 				clear_bit(ZONE_CONGESTED, &zone->flags);
321857054651SJohannes Weiner 				clear_bit(ZONE_DIRTY, &zone->flags);
32191da177e4SLinus Torvalds 			}
32201da177e4SLinus Torvalds 		}
3221dafcb73eSZlatko Calusic 
3222b8e83b94SMel Gorman 		if (i < 0)
32231da177e4SLinus Torvalds 			goto out;
3224e1dbeda6SAndrew Morton 
32251da177e4SLinus Torvalds 		/*
3226b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3227b7ea3c41SMel Gorman 		 * even in laptop mode.
3228b7ea3c41SMel Gorman 		 */
3229b7ea3c41SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2)
3230b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3231b7ea3c41SMel Gorman 
3232b7ea3c41SMel Gorman 		/*
32331da177e4SLinus Torvalds 		 * Now scan the zone in the dma->highmem direction, stopping
32341da177e4SLinus Torvalds 		 * at the last zone which needs scanning.
32351da177e4SLinus Torvalds 		 *
32361da177e4SLinus Torvalds 		 * We do this because the page allocator works in the opposite
32371da177e4SLinus Torvalds 		 * direction.  This prevents the page allocator from allocating
32381da177e4SLinus Torvalds 		 * pages behind kswapd's direction of progress, which would
32391da177e4SLinus Torvalds 		 * cause too much scanning of the lower zones.
32401da177e4SLinus Torvalds 		 */
32411da177e4SLinus Torvalds 		for (i = 0; i <= end_zone; i++) {
32421da177e4SLinus Torvalds 			struct zone *zone = pgdat->node_zones + i;
32431da177e4SLinus Torvalds 
3244f3fe6512SCon Kolivas 			if (!populated_zone(zone))
32451da177e4SLinus Torvalds 				continue;
32461da177e4SLinus Torvalds 
32476e543d57SLisa Du 			if (sc.priority != DEF_PRIORITY &&
32486e543d57SLisa Du 			    !zone_reclaimable(zone))
32491da177e4SLinus Torvalds 				continue;
32501da177e4SLinus Torvalds 
32511da177e4SLinus Torvalds 			sc.nr_scanned = 0;
32524e416953SBalbir Singh 
32530608f43dSAndrew Morton 			nr_soft_scanned = 0;
32540608f43dSAndrew Morton 			/*
32550608f43dSAndrew Morton 			 * Call soft limit reclaim before calling shrink_zone.
32560608f43dSAndrew Morton 			 */
32570608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
32580608f43dSAndrew Morton 							order, sc.gfp_mask,
32590608f43dSAndrew Morton 							&nr_soft_scanned);
32600608f43dSAndrew Morton 			sc.nr_reclaimed += nr_soft_reclaimed;
32610608f43dSAndrew Morton 
326232a4330dSRik van Riel 			/*
32637c954f6dSMel Gorman 			 * There should be no need to raise the scanning
32647c954f6dSMel Gorman 			 * priority if enough pages are already being scanned
32657c954f6dSMel Gorman 			 * that that high watermark would be met at 100%
32667c954f6dSMel Gorman 			 * efficiency.
326732a4330dSRik van Riel 			 */
3268*accf6242SVlastimil Babka 			if (kswapd_shrink_zone(zone, end_zone, &sc))
3269b8e83b94SMel Gorman 				raise_priority = false;
3270b8e83b94SMel Gorman 		}
3271d7868daeSMel Gorman 
32725515061dSMel Gorman 		/*
32735515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32745515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32755515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32765515061dSMel Gorman 		 */
32775515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
32785515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3279cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32805515061dSMel Gorman 
3281b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3282b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3283b8e83b94SMel Gorman 			break;
3284b8e83b94SMel Gorman 
3285b8e83b94SMel Gorman 		/*
3286b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3287b8e83b94SMel Gorman 		 * progress in reclaiming pages
3288b8e83b94SMel Gorman 		 */
3289b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3290b8e83b94SMel Gorman 			sc.priority--;
32919aa41348SMel Gorman 	} while (sc.priority >= 1 &&
3292*accf6242SVlastimil Babka 			!pgdat_balanced(pgdat, order, classzone_idx));
32931da177e4SLinus Torvalds 
3294b8e83b94SMel Gorman out:
32950abdee2bSMel Gorman 	/*
3296*accf6242SVlastimil Babka 	 * Return the highest zone idx we were reclaiming at so
3297*accf6242SVlastimil Babka 	 * prepare_kswapd_sleep() makes the same decisions as here.
32980abdee2bSMel Gorman 	 */
3299*accf6242SVlastimil Babka 	return end_zone;
33001da177e4SLinus Torvalds }
33011da177e4SLinus Torvalds 
3302*accf6242SVlastimil Babka static void kswapd_try_to_sleep(pg_data_t *pgdat, int order,
3303*accf6242SVlastimil Babka 				int classzone_idx, int balanced_classzone_idx)
3304f0bc0a60SKOSAKI Motohiro {
3305f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3306f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3307f0bc0a60SKOSAKI Motohiro 
3308f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3309f0bc0a60SKOSAKI Motohiro 		return;
3310f0bc0a60SKOSAKI Motohiro 
3311f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3312f0bc0a60SKOSAKI Motohiro 
3313f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3314*accf6242SVlastimil Babka 	if (prepare_kswapd_sleep(pgdat, order, remaining,
3315*accf6242SVlastimil Babka 						balanced_classzone_idx)) {
3316f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3317f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3318f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3319f0bc0a60SKOSAKI Motohiro 	}
3320f0bc0a60SKOSAKI Motohiro 
3321f0bc0a60SKOSAKI Motohiro 	/*
3322f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3323f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3324f0bc0a60SKOSAKI Motohiro 	 */
3325*accf6242SVlastimil Babka 	if (prepare_kswapd_sleep(pgdat, order, remaining,
3326*accf6242SVlastimil Babka 						balanced_classzone_idx)) {
3327f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3328f0bc0a60SKOSAKI Motohiro 
3329f0bc0a60SKOSAKI Motohiro 		/*
3330f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3331f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3332f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3333f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3334f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3335f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3336f0bc0a60SKOSAKI Motohiro 		 */
3337f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33381c7e7f6cSAaditya Kumar 
333962997027SMel Gorman 		/*
334062997027SMel Gorman 		 * Compaction records what page blocks it recently failed to
334162997027SMel Gorman 		 * isolate pages from and skips them in the future scanning.
334262997027SMel Gorman 		 * When kswapd is going to sleep, it is reasonable to assume
334362997027SMel Gorman 		 * that pages and compaction may succeed so reset the cache.
334462997027SMel Gorman 		 */
334562997027SMel Gorman 		reset_isolation_suitable(pgdat);
334662997027SMel Gorman 
3347*accf6242SVlastimil Babka 		/*
3348*accf6242SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3349*accf6242SVlastimil Babka 		 * allocation of the requested order possible.
3350*accf6242SVlastimil Babka 		 */
3351*accf6242SVlastimil Babka 		wakeup_kcompactd(pgdat, order, classzone_idx);
3352*accf6242SVlastimil Babka 
33531c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3354f0bc0a60SKOSAKI Motohiro 			schedule();
33551c7e7f6cSAaditya Kumar 
3356f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3357f0bc0a60SKOSAKI Motohiro 	} else {
3358f0bc0a60SKOSAKI Motohiro 		if (remaining)
3359f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3360f0bc0a60SKOSAKI Motohiro 		else
3361f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3362f0bc0a60SKOSAKI Motohiro 	}
3363f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3364f0bc0a60SKOSAKI Motohiro }
3365f0bc0a60SKOSAKI Motohiro 
33661da177e4SLinus Torvalds /*
33671da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33681da177e4SLinus Torvalds  * from the init process.
33691da177e4SLinus Torvalds  *
33701da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33711da177e4SLinus Torvalds  * free memory available even if there is no other activity
33721da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33731da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33741da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33751da177e4SLinus Torvalds  *
33761da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33771da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33781da177e4SLinus Torvalds  */
33791da177e4SLinus Torvalds static int kswapd(void *p)
33801da177e4SLinus Torvalds {
3381215ddd66SMel Gorman 	unsigned long order, new_order;
3382215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3383d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
33841da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
33851da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3386f0bc0a60SKOSAKI Motohiro 
33871da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
33881da177e4SLinus Torvalds 		.reclaimed_slab = 0,
33891da177e4SLinus Torvalds 	};
3390a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
33911da177e4SLinus Torvalds 
3392cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3393cf40bd16SNick Piggin 
3394174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3395c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
33961da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
33971da177e4SLinus Torvalds 
33981da177e4SLinus Torvalds 	/*
33991da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
34001da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
34011da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
34021da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
34031da177e4SLinus Torvalds 	 *
34041da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
34051da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
34061da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
34071da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34081da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34091da177e4SLinus Torvalds 	 */
3410930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
341183144186SRafael J. Wysocki 	set_freezable();
34121da177e4SLinus Torvalds 
3413215ddd66SMel Gorman 	order = new_order = 0;
3414215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3415d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
34161da177e4SLinus Torvalds 	for ( ; ; ) {
34176f6313d4SJeff Liu 		bool ret;
34183e1d1d28SChristoph Lameter 
3419215ddd66SMel Gorman 		/*
3420*accf6242SVlastimil Babka 		 * While we were reclaiming, there might have been another
3421*accf6242SVlastimil Babka 		 * wakeup, so check the values.
3422215ddd66SMel Gorman 		 */
34231da177e4SLinus Torvalds 		new_order = pgdat->kswapd_max_order;
342499504748SMel Gorman 		new_classzone_idx = pgdat->classzone_idx;
34251da177e4SLinus Torvalds 		pgdat->kswapd_max_order =  0;
3426215ddd66SMel Gorman 		pgdat->classzone_idx = pgdat->nr_zones - 1;
3427215ddd66SMel Gorman 
342899504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
34291da177e4SLinus Torvalds 			/*
34301da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
343199504748SMel Gorman 			 * allocation or has tigher zone constraints
34321da177e4SLinus Torvalds 			 */
34331da177e4SLinus Torvalds 			order = new_order;
343499504748SMel Gorman 			classzone_idx = new_classzone_idx;
34351da177e4SLinus Torvalds 		} else {
3436*accf6242SVlastimil Babka 			kswapd_try_to_sleep(pgdat, order, classzone_idx,
3437d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
34381da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
343999504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3440f0dfcde0SAlex,Shi 			new_order = order;
3441f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
34424d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3443215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
34441da177e4SLinus Torvalds 		}
34451da177e4SLinus Torvalds 
34468fe23e05SDavid Rientjes 		ret = try_to_freeze();
34478fe23e05SDavid Rientjes 		if (kthread_should_stop())
34488fe23e05SDavid Rientjes 			break;
34498fe23e05SDavid Rientjes 
34508fe23e05SDavid Rientjes 		/*
34518fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34528fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3453b1296cc4SRafael J. Wysocki 		 */
345433906bc5SMel Gorman 		if (!ret) {
345533906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3456*accf6242SVlastimil Babka 			balanced_classzone_idx = balance_pgdat(pgdat, order,
3457*accf6242SVlastimil Babka 								classzone_idx);
34581da177e4SLinus Torvalds 		}
345933906bc5SMel Gorman 	}
3460b0a8cc58STakamori Yamaguchi 
346171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3462b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
346371abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
346471abdc15SJohannes Weiner 
34651da177e4SLinus Torvalds 	return 0;
34661da177e4SLinus Torvalds }
34671da177e4SLinus Torvalds 
34681da177e4SLinus Torvalds /*
34691da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34701da177e4SLinus Torvalds  */
347199504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34721da177e4SLinus Torvalds {
34731da177e4SLinus Torvalds 	pg_data_t *pgdat;
34741da177e4SLinus Torvalds 
3475f3fe6512SCon Kolivas 	if (!populated_zone(zone))
34761da177e4SLinus Torvalds 		return;
34771da177e4SLinus Torvalds 
3478344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34791da177e4SLinus Torvalds 		return;
348088f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
348199504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
348288f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
348399504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
348499504748SMel Gorman 	}
34858d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34861da177e4SLinus Torvalds 		return;
3487*accf6242SVlastimil Babka 	if (zone_balanced(zone, order, true, 0, 0))
348888f5acf8SMel Gorman 		return;
348988f5acf8SMel Gorman 
349088f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
34918d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
34921da177e4SLinus Torvalds }
34931da177e4SLinus Torvalds 
3494c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
34951da177e4SLinus Torvalds /*
34967b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3497d6277db4SRafael J. Wysocki  * freed pages.
3498d6277db4SRafael J. Wysocki  *
3499d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3500d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3501d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35021da177e4SLinus Torvalds  */
35037b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35041da177e4SLinus Torvalds {
3505d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3506d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35077b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3508ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
35099e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3510ee814fe2SJohannes Weiner 		.may_writepage = 1,
3511ee814fe2SJohannes Weiner 		.may_unmap = 1,
3512ee814fe2SJohannes Weiner 		.may_swap = 1,
3513ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
35141da177e4SLinus Torvalds 	};
35157b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
35167b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
35177b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
35181da177e4SLinus Torvalds 
35197b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
35207b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3521d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
35227b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3523d6277db4SRafael J. Wysocki 
35243115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3525d6277db4SRafael J. Wysocki 
35267b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35277b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35287b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3529d6277db4SRafael J. Wysocki 
35307b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35311da177e4SLinus Torvalds }
3532c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35331da177e4SLinus Torvalds 
35341da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35351da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35361da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35371da177e4SLinus Torvalds    restore their cpu bindings. */
3538fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3539fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
35401da177e4SLinus Torvalds {
354158c0a4a7SYasunori Goto 	int nid;
35421da177e4SLinus Torvalds 
35438bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
354448fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3545c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3546a70f7302SRusty Russell 			const struct cpumask *mask;
3547a70f7302SRusty Russell 
3548a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3549c5f59f08SMike Travis 
35503e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35511da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3552c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
35531da177e4SLinus Torvalds 		}
35541da177e4SLinus Torvalds 	}
35551da177e4SLinus Torvalds 	return NOTIFY_OK;
35561da177e4SLinus Torvalds }
35571da177e4SLinus Torvalds 
35583218ae14SYasunori Goto /*
35593218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35603218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35613218ae14SYasunori Goto  */
35623218ae14SYasunori Goto int kswapd_run(int nid)
35633218ae14SYasunori Goto {
35643218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35653218ae14SYasunori Goto 	int ret = 0;
35663218ae14SYasunori Goto 
35673218ae14SYasunori Goto 	if (pgdat->kswapd)
35683218ae14SYasunori Goto 		return 0;
35693218ae14SYasunori Goto 
35703218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35713218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35723218ae14SYasunori Goto 		/* failure at boot is fatal */
35733218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3574d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3575d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3576d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35773218ae14SYasunori Goto 	}
35783218ae14SYasunori Goto 	return ret;
35793218ae14SYasunori Goto }
35803218ae14SYasunori Goto 
35818fe23e05SDavid Rientjes /*
3582d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3583bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
35848fe23e05SDavid Rientjes  */
35858fe23e05SDavid Rientjes void kswapd_stop(int nid)
35868fe23e05SDavid Rientjes {
35878fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
35888fe23e05SDavid Rientjes 
3589d8adde17SJiang Liu 	if (kswapd) {
35908fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3591d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3592d8adde17SJiang Liu 	}
35938fe23e05SDavid Rientjes }
35948fe23e05SDavid Rientjes 
35951da177e4SLinus Torvalds static int __init kswapd_init(void)
35961da177e4SLinus Torvalds {
35973218ae14SYasunori Goto 	int nid;
359869e05944SAndrew Morton 
35991da177e4SLinus Torvalds 	swap_setup();
360048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
36013218ae14SYasunori Goto  		kswapd_run(nid);
36021da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
36031da177e4SLinus Torvalds 	return 0;
36041da177e4SLinus Torvalds }
36051da177e4SLinus Torvalds 
36061da177e4SLinus Torvalds module_init(kswapd_init)
36079eeff239SChristoph Lameter 
36089eeff239SChristoph Lameter #ifdef CONFIG_NUMA
36099eeff239SChristoph Lameter /*
36109eeff239SChristoph Lameter  * Zone reclaim mode
36119eeff239SChristoph Lameter  *
36129eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
36139eeff239SChristoph Lameter  * the watermarks.
36149eeff239SChristoph Lameter  */
36159eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
36169eeff239SChristoph Lameter 
36171b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
36187d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
36191b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
362095bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
36211b2ffb78SChristoph Lameter 
36229eeff239SChristoph Lameter /*
3623a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3624a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3625a92f7126SChristoph Lameter  * a zone.
3626a92f7126SChristoph Lameter  */
3627a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3628a92f7126SChristoph Lameter 
36299eeff239SChristoph Lameter /*
36309614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
36319614634fSChristoph Lameter  * occur.
36329614634fSChristoph Lameter  */
36339614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36349614634fSChristoph Lameter 
36359614634fSChristoph Lameter /*
36360ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36370ff38490SChristoph Lameter  * slab reclaim needs to occur.
36380ff38490SChristoph Lameter  */
36390ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36400ff38490SChristoph Lameter 
364190afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
364290afa5deSMel Gorman {
364390afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
364490afa5deSMel Gorman 	unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
364590afa5deSMel Gorman 		zone_page_state(zone, NR_ACTIVE_FILE);
364690afa5deSMel Gorman 
364790afa5deSMel Gorman 	/*
364890afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
364990afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
365090afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
365190afa5deSMel Gorman 	 */
365290afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
365390afa5deSMel Gorman }
365490afa5deSMel Gorman 
365590afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3656d031a157SAlexandru Moise static unsigned long zone_pagecache_reclaimable(struct zone *zone)
365790afa5deSMel Gorman {
3658d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3659d031a157SAlexandru Moise 	unsigned long delta = 0;
366090afa5deSMel Gorman 
366190afa5deSMel Gorman 	/*
366295bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
366390afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
366490afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
366590afa5deSMel Gorman 	 * a better estimate
366690afa5deSMel Gorman 	 */
366795bbc0c7SZhihui Zhang 	if (zone_reclaim_mode & RECLAIM_UNMAP)
366890afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
366990afa5deSMel Gorman 	else
367090afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
367190afa5deSMel Gorman 
367290afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
367390afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
367490afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
367590afa5deSMel Gorman 
367690afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
367790afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
367890afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
367990afa5deSMel Gorman 
368090afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
368190afa5deSMel Gorman }
368290afa5deSMel Gorman 
36830ff38490SChristoph Lameter /*
36849eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
36859eeff239SChristoph Lameter  */
3686179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
36879eeff239SChristoph Lameter {
36887fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
368969e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
36909eeff239SChristoph Lameter 	struct task_struct *p = current;
36919eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3692179e9639SAndrew Morton 	struct scan_control sc = {
369362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
369421caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3695bd2f6199SJohannes Weiner 		.order = order,
36969e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3697ee814fe2SJohannes Weiner 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
369895bbc0c7SZhihui Zhang 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP),
3699ee814fe2SJohannes Weiner 		.may_swap = 1,
3700179e9639SAndrew Morton 	};
37019eeff239SChristoph Lameter 
37029eeff239SChristoph Lameter 	cond_resched();
3703d4f7796eSChristoph Lameter 	/*
370495bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3705d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
370695bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3707d4f7796eSChristoph Lameter 	 */
3708d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
370976ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
37109eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
37119eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3712c84db23cSChristoph Lameter 
371390afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3714a92f7126SChristoph Lameter 		/*
37150ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
37160ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3717a92f7126SChristoph Lameter 		 */
3718a92f7126SChristoph Lameter 		do {
37196b4f7799SJohannes Weiner 			shrink_zone(zone, &sc, true);
37209e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
37210ff38490SChristoph Lameter 	}
3722a92f7126SChristoph Lameter 
37239eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3724d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
372576ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3726a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37279eeff239SChristoph Lameter }
3728179e9639SAndrew Morton 
3729179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3730179e9639SAndrew Morton {
3731179e9639SAndrew Morton 	int node_id;
3732d773ed6bSDavid Rientjes 	int ret;
3733179e9639SAndrew Morton 
3734179e9639SAndrew Morton 	/*
37350ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
37360ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
373734aa1330SChristoph Lameter 	 *
37389614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37399614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
37409614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
37419614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
37429614634fSChristoph Lameter 	 * unmapped file backed pages.
3743179e9639SAndrew Morton 	 */
374490afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
374590afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3746fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3747179e9639SAndrew Morton 
37486e543d57SLisa Du 	if (!zone_reclaimable(zone))
3749fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3750d773ed6bSDavid Rientjes 
3751179e9639SAndrew Morton 	/*
3752d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3753179e9639SAndrew Morton 	 */
3754d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3755fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3756179e9639SAndrew Morton 
3757179e9639SAndrew Morton 	/*
3758179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3759179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3760179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3761179e9639SAndrew Morton 	 * as wide as possible.
3762179e9639SAndrew Morton 	 */
376389fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
376437c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3765fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3766d773ed6bSDavid Rientjes 
376757054651SJohannes Weiner 	if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
3768fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3769fa5e084eSMel Gorman 
3770d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
377157054651SJohannes Weiner 	clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
3772d773ed6bSDavid Rientjes 
377324cf7251SMel Gorman 	if (!ret)
377424cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
377524cf7251SMel Gorman 
3776d773ed6bSDavid Rientjes 	return ret;
3777179e9639SAndrew Morton }
37789eeff239SChristoph Lameter #endif
3779894bc310SLee Schermerhorn 
3780894bc310SLee Schermerhorn /*
3781894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3782894bc310SLee Schermerhorn  * @page: the page to test
3783894bc310SLee Schermerhorn  *
3784894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
378539b5f29aSHugh Dickins  * lists vs unevictable list.
3786894bc310SLee Schermerhorn  *
3787894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3788ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3789b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3790ba9ddf49SLee Schermerhorn  *
3791894bc310SLee Schermerhorn  */
379239b5f29aSHugh Dickins int page_evictable(struct page *page)
3793894bc310SLee Schermerhorn {
379439b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3795894bc310SLee Schermerhorn }
379689e004eaSLee Schermerhorn 
379785046579SHugh Dickins #ifdef CONFIG_SHMEM
379889e004eaSLee Schermerhorn /**
379924513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
380024513264SHugh Dickins  * @pages:	array of pages to check
380124513264SHugh Dickins  * @nr_pages:	number of pages to check
380289e004eaSLee Schermerhorn  *
380324513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
380485046579SHugh Dickins  *
380585046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
380689e004eaSLee Schermerhorn  */
380724513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
380889e004eaSLee Schermerhorn {
3809925b7673SJohannes Weiner 	struct lruvec *lruvec;
381024513264SHugh Dickins 	struct zone *zone = NULL;
381124513264SHugh Dickins 	int pgscanned = 0;
381224513264SHugh Dickins 	int pgrescued = 0;
381389e004eaSLee Schermerhorn 	int i;
381489e004eaSLee Schermerhorn 
381524513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
381624513264SHugh Dickins 		struct page *page = pages[i];
381724513264SHugh Dickins 		struct zone *pagezone;
381889e004eaSLee Schermerhorn 
381924513264SHugh Dickins 		pgscanned++;
382024513264SHugh Dickins 		pagezone = page_zone(page);
382189e004eaSLee Schermerhorn 		if (pagezone != zone) {
382289e004eaSLee Schermerhorn 			if (zone)
382389e004eaSLee Schermerhorn 				spin_unlock_irq(&zone->lru_lock);
382489e004eaSLee Schermerhorn 			zone = pagezone;
382589e004eaSLee Schermerhorn 			spin_lock_irq(&zone->lru_lock);
382689e004eaSLee Schermerhorn 		}
3827fa9add64SHugh Dickins 		lruvec = mem_cgroup_page_lruvec(page, zone);
382889e004eaSLee Schermerhorn 
382924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
383024513264SHugh Dickins 			continue;
383189e004eaSLee Schermerhorn 
383239b5f29aSHugh Dickins 		if (page_evictable(page)) {
383324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
383424513264SHugh Dickins 
3835309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
383624513264SHugh Dickins 			ClearPageUnevictable(page);
3837fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3838fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
383924513264SHugh Dickins 			pgrescued++;
384089e004eaSLee Schermerhorn 		}
384189e004eaSLee Schermerhorn 	}
384224513264SHugh Dickins 
384324513264SHugh Dickins 	if (zone) {
384424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
384524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
384624513264SHugh Dickins 		spin_unlock_irq(&zone->lru_lock);
384724513264SHugh Dickins 	}
384885046579SHugh Dickins }
384985046579SHugh Dickins #endif /* CONFIG_SHMEM */
3850