xref: /openbmc/linux/mm/vmscan.c (revision 89a2848381b5fcd9c4d9c0cd97680e3b28730e31)
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 
87b2e18757SMel Gorman 	/* The highest zone to isolate pages for reclaim from */
88b2e18757SMel Gorman 	enum zone_type reclaim_idx;
89b2e18757SMel Gorman 
90ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
91ee814fe2SJohannes Weiner 
92ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
93ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
94ee814fe2SJohannes Weiner 
95ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
96ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
97ee814fe2SJohannes Weiner 
98241994edSJohannes Weiner 	/* Can cgroups be reclaimed below their normal consumption range? */
99241994edSJohannes Weiner 	unsigned int may_thrash:1;
100241994edSJohannes Weiner 
101ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
102ee814fe2SJohannes Weiner 
103ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
104ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
105ee814fe2SJohannes Weiner 
106ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
107ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
108ee814fe2SJohannes Weiner 
109ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
110ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1111da177e4SLinus Torvalds };
1121da177e4SLinus Torvalds 
1131da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1141da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1151da177e4SLinus Torvalds 	do {								\
1161da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1171da177e4SLinus Torvalds 			struct page *prev;				\
1181da177e4SLinus Torvalds 									\
1191da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1201da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1211da177e4SLinus Torvalds 		}							\
1221da177e4SLinus Torvalds 	} while (0)
1231da177e4SLinus Torvalds #else
1241da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1251da177e4SLinus Torvalds #endif
1261da177e4SLinus Torvalds 
1271da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1281da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1291da177e4SLinus Torvalds 	do {								\
1301da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1311da177e4SLinus Torvalds 			struct page *prev;				\
1321da177e4SLinus Torvalds 									\
1331da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1341da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1351da177e4SLinus Torvalds 		}							\
1361da177e4SLinus Torvalds 	} while (0)
1371da177e4SLinus Torvalds #else
1381da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1391da177e4SLinus Torvalds #endif
1401da177e4SLinus Torvalds 
1411da177e4SLinus Torvalds /*
1421da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1431da177e4SLinus Torvalds  */
1441da177e4SLinus Torvalds int vm_swappiness = 60;
145d0480be4SWang Sheng-Hui /*
146d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
147d0480be4SWang Sheng-Hui  * zones.
148d0480be4SWang Sheng-Hui  */
149d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1501da177e4SLinus Torvalds 
1511da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1521da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1531da177e4SLinus Torvalds 
154c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15589b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15689b5fae5SJohannes Weiner {
157f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
15889b5fae5SJohannes Weiner }
15997c9341fSTejun Heo 
16097c9341fSTejun Heo /**
16197c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
16297c9341fSTejun Heo  * @sc: scan_control in question
16397c9341fSTejun Heo  *
16497c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
16597c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
16697c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
16797c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
16897c9341fSTejun Heo  * allocation and configurability.
16997c9341fSTejun Heo  *
17097c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
17197c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
17297c9341fSTejun Heo  */
17397c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
17497c9341fSTejun Heo {
17597c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
17697c9341fSTejun Heo 
17797c9341fSTejun Heo 	if (!memcg)
17897c9341fSTejun Heo 		return true;
17997c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
18069234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
18197c9341fSTejun Heo 		return true;
18297c9341fSTejun Heo #endif
18397c9341fSTejun Heo 	return false;
18497c9341fSTejun Heo }
18591a45470SKAMEZAWA Hiroyuki #else
18689b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
18789b5fae5SJohannes Weiner {
18889b5fae5SJohannes Weiner 	return true;
18989b5fae5SJohannes Weiner }
19097c9341fSTejun Heo 
19197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19297c9341fSTejun Heo {
19397c9341fSTejun Heo 	return true;
19497c9341fSTejun Heo }
19591a45470SKAMEZAWA Hiroyuki #endif
19691a45470SKAMEZAWA Hiroyuki 
1975a1c84b4SMel Gorman /*
1985a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
1995a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2005a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2015a1c84b4SMel Gorman  */
2025a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2035a1c84b4SMel Gorman {
2045a1c84b4SMel Gorman 	unsigned long nr;
2055a1c84b4SMel Gorman 
2065a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2075a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2085a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2095a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2105a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2115a1c84b4SMel Gorman 
2125a1c84b4SMel Gorman 	return nr;
2135a1c84b4SMel Gorman }
2145a1c84b4SMel Gorman 
215599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2166e543d57SLisa Du {
217599d0c95SMel Gorman 	unsigned long nr;
218599d0c95SMel Gorman 
219599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
220599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
221599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
222599d0c95SMel Gorman 
223599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
224599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
225599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
226599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
227599d0c95SMel Gorman 
228599d0c95SMel Gorman 	return nr;
229599d0c95SMel Gorman }
230599d0c95SMel Gorman 
231599d0c95SMel Gorman bool pgdat_reclaimable(struct pglist_data *pgdat)
232599d0c95SMel Gorman {
233599d0c95SMel Gorman 	return node_page_state_snapshot(pgdat, NR_PAGES_SCANNED) <
234599d0c95SMel Gorman 		pgdat_reclaimable_pages(pgdat) * 6;
2356e543d57SLisa Du }
2366e543d57SLisa Du 
23723047a96SJohannes Weiner unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
238c9f299d9SKOSAKI Motohiro {
239c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2404d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
241a3d8e054SKOSAKI Motohiro 
242599d0c95SMel Gorman 	return node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
243c9f299d9SKOSAKI Motohiro }
244c9f299d9SKOSAKI Motohiro 
2451da177e4SLinus Torvalds /*
2461d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2471da177e4SLinus Torvalds  */
2481d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2491da177e4SLinus Torvalds {
2501d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2511d3d4437SGlauber Costa 
2521d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2531d3d4437SGlauber Costa 		size *= nr_node_ids;
2541d3d4437SGlauber Costa 
2551d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2561d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2571d3d4437SGlauber Costa 		return -ENOMEM;
2581d3d4437SGlauber Costa 
2591da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2601da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2611da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2621d3d4437SGlauber Costa 	return 0;
2631da177e4SLinus Torvalds }
2648e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2651da177e4SLinus Torvalds 
2661da177e4SLinus Torvalds /*
2671da177e4SLinus Torvalds  * Remove one
2681da177e4SLinus Torvalds  */
2698e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2701da177e4SLinus Torvalds {
2711da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2721da177e4SLinus Torvalds 	list_del(&shrinker->list);
2731da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
274ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2751da177e4SLinus Torvalds }
2768e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2771da177e4SLinus Torvalds 
2781da177e4SLinus Torvalds #define SHRINK_BATCH 128
2791d3d4437SGlauber Costa 
280cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2816b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2826b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2836b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2841da177e4SLinus Torvalds {
28524f7c6b9SDave Chinner 	unsigned long freed = 0;
2861da177e4SLinus Torvalds 	unsigned long long delta;
287635697c6SKonstantin Khlebnikov 	long total_scan;
288d5bc5fd3SVladimir Davydov 	long freeable;
289acf92b48SDave Chinner 	long nr;
290acf92b48SDave Chinner 	long new_nr;
2911d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
292e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
293e9299f50SDave Chinner 					  : SHRINK_BATCH;
2941da177e4SLinus Torvalds 
295d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
296d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2971d3d4437SGlauber Costa 		return 0;
298635697c6SKonstantin Khlebnikov 
299acf92b48SDave Chinner 	/*
300acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
301acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
302acf92b48SDave Chinner 	 * don't also do this scanning work.
303acf92b48SDave Chinner 	 */
3041d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
305acf92b48SDave Chinner 
306acf92b48SDave Chinner 	total_scan = nr;
3076b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
308d5bc5fd3SVladimir Davydov 	delta *= freeable;
3096b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
310acf92b48SDave Chinner 	total_scan += delta;
311acf92b48SDave Chinner 	if (total_scan < 0) {
3128612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
313a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
314d5bc5fd3SVladimir Davydov 		total_scan = freeable;
315ea164d73SAndrea Arcangeli 	}
316ea164d73SAndrea Arcangeli 
317ea164d73SAndrea Arcangeli 	/*
3183567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3193567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3203567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3213567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3223567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
323d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3243567b59aSDave Chinner 	 * memory.
3253567b59aSDave Chinner 	 *
3263567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3273567b59aSDave Chinner 	 * a large delta change is calculated directly.
3283567b59aSDave Chinner 	 */
329d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
330d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3313567b59aSDave Chinner 
3323567b59aSDave Chinner 	/*
333ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
334ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
335ea164d73SAndrea Arcangeli 	 * freeable entries.
336ea164d73SAndrea Arcangeli 	 */
337d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
338d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3391da177e4SLinus Torvalds 
34024f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3416b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
342d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
34309576073SDave Chinner 
3440b1fb40aSVladimir Davydov 	/*
3450b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3460b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3470b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3480b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3490b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3500b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3510b1fb40aSVladimir Davydov 	 * batch_size.
3520b1fb40aSVladimir Davydov 	 *
3530b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3540b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
355d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3560b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3570b1fb40aSVladimir Davydov 	 * possible.
3580b1fb40aSVladimir Davydov 	 */
3590b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
360d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
36124f7c6b9SDave Chinner 		unsigned long ret;
3620b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3631da177e4SLinus Torvalds 
3640b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
36524f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
36624f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3671da177e4SLinus Torvalds 			break;
36824f7c6b9SDave Chinner 		freed += ret;
36924f7c6b9SDave Chinner 
3700b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3710b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3721da177e4SLinus Torvalds 
3731da177e4SLinus Torvalds 		cond_resched();
3741da177e4SLinus Torvalds 	}
3751da177e4SLinus Torvalds 
376acf92b48SDave Chinner 	/*
377acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
378acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
379acf92b48SDave Chinner 	 * scan, there is no need to do an update.
380acf92b48SDave Chinner 	 */
38183aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
38283aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3831d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
38483aeeadaSKonstantin Khlebnikov 	else
3851d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
386acf92b48SDave Chinner 
387df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3881d3d4437SGlauber Costa 	return freed;
3891d3d4437SGlauber Costa }
3901d3d4437SGlauber Costa 
3916b4f7799SJohannes Weiner /**
392cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
3936b4f7799SJohannes Weiner  * @gfp_mask: allocation context
3946b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
395cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
3966b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
3976b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
3981d3d4437SGlauber Costa  *
3996b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4001d3d4437SGlauber Costa  *
4016b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4026b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4031d3d4437SGlauber Costa  *
404cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
405cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4060fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4070fc9f58aSVladimir Davydov  * shrinkers are called.
408cb731d6cSVladimir Davydov  *
4096b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4106b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4116b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4126b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4136b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4146b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4156b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4161d3d4437SGlauber Costa  *
4176b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4181d3d4437SGlauber Costa  */
419cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
420cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4216b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4226b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4231d3d4437SGlauber Costa {
4241d3d4437SGlauber Costa 	struct shrinker *shrinker;
4251d3d4437SGlauber Costa 	unsigned long freed = 0;
4261d3d4437SGlauber Costa 
4270fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
428cb731d6cSVladimir Davydov 		return 0;
429cb731d6cSVladimir Davydov 
4306b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4316b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4321d3d4437SGlauber Costa 
4331d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4341d3d4437SGlauber Costa 		/*
4351d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4361d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4371d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4381d3d4437SGlauber Costa 		 * time.
4391d3d4437SGlauber Costa 		 */
4401d3d4437SGlauber Costa 		freed = 1;
4411d3d4437SGlauber Costa 		goto out;
4421d3d4437SGlauber Costa 	}
4431d3d4437SGlauber Costa 
4441d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4456b4f7799SJohannes Weiner 		struct shrink_control sc = {
4466b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4476b4f7799SJohannes Weiner 			.nid = nid,
448cb731d6cSVladimir Davydov 			.memcg = memcg,
4496b4f7799SJohannes Weiner 		};
4506b4f7799SJohannes Weiner 
4510fc9f58aSVladimir Davydov 		/*
4520fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4530fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4540fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4550fc9f58aSVladimir Davydov 		 */
4560fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4570fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
458cb731d6cSVladimir Davydov 			continue;
459cb731d6cSVladimir Davydov 
4606b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4616b4f7799SJohannes Weiner 			sc.nid = 0;
4626b4f7799SJohannes Weiner 
463cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
464ec97097bSVladimir Davydov 	}
4651d3d4437SGlauber Costa 
4661da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
467f06590bdSMinchan Kim out:
468f06590bdSMinchan Kim 	cond_resched();
46924f7c6b9SDave Chinner 	return freed;
4701da177e4SLinus Torvalds }
4711da177e4SLinus Torvalds 
472cb731d6cSVladimir Davydov void drop_slab_node(int nid)
473cb731d6cSVladimir Davydov {
474cb731d6cSVladimir Davydov 	unsigned long freed;
475cb731d6cSVladimir Davydov 
476cb731d6cSVladimir Davydov 	do {
477cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
478cb731d6cSVladimir Davydov 
479cb731d6cSVladimir Davydov 		freed = 0;
480cb731d6cSVladimir Davydov 		do {
481cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
482cb731d6cSVladimir Davydov 					     1000, 1000);
483cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
484cb731d6cSVladimir Davydov 	} while (freed > 10);
485cb731d6cSVladimir Davydov }
486cb731d6cSVladimir Davydov 
487cb731d6cSVladimir Davydov void drop_slab(void)
488cb731d6cSVladimir Davydov {
489cb731d6cSVladimir Davydov 	int nid;
490cb731d6cSVladimir Davydov 
491cb731d6cSVladimir Davydov 	for_each_online_node(nid)
492cb731d6cSVladimir Davydov 		drop_slab_node(nid);
493cb731d6cSVladimir Davydov }
494cb731d6cSVladimir Davydov 
4951da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4961da177e4SLinus Torvalds {
497ceddc3a5SJohannes Weiner 	/*
498ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
499ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
500ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
501ceddc3a5SJohannes Weiner 	 */
502edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5031da177e4SLinus Torvalds }
5041da177e4SLinus Torvalds 
505703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5061da177e4SLinus Torvalds {
507930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5081da177e4SLinus Torvalds 		return 1;
509703c2708STejun Heo 	if (!inode_write_congested(inode))
5101da177e4SLinus Torvalds 		return 1;
511703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5121da177e4SLinus Torvalds 		return 1;
5131da177e4SLinus Torvalds 	return 0;
5141da177e4SLinus Torvalds }
5151da177e4SLinus Torvalds 
5161da177e4SLinus Torvalds /*
5171da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5181da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5191da177e4SLinus Torvalds  * fsync(), msync() or close().
5201da177e4SLinus Torvalds  *
5211da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5221da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5231da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5241da177e4SLinus Torvalds  *
5251da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5261da177e4SLinus Torvalds  * __GFP_FS.
5271da177e4SLinus Torvalds  */
5281da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5291da177e4SLinus Torvalds 				struct page *page, int error)
5301da177e4SLinus Torvalds {
5317eaceaccSJens Axboe 	lock_page(page);
5323e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5333e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5341da177e4SLinus Torvalds 	unlock_page(page);
5351da177e4SLinus Torvalds }
5361da177e4SLinus Torvalds 
53704e62a29SChristoph Lameter /* possible outcome of pageout() */
53804e62a29SChristoph Lameter typedef enum {
53904e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
54004e62a29SChristoph Lameter 	PAGE_KEEP,
54104e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
54204e62a29SChristoph Lameter 	PAGE_ACTIVATE,
54304e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
54404e62a29SChristoph Lameter 	PAGE_SUCCESS,
54504e62a29SChristoph Lameter 	/* page is clean and locked */
54604e62a29SChristoph Lameter 	PAGE_CLEAN,
54704e62a29SChristoph Lameter } pageout_t;
54804e62a29SChristoph Lameter 
5491da177e4SLinus Torvalds /*
5501742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5511742f19fSAndrew Morton  * Calls ->writepage().
5521da177e4SLinus Torvalds  */
553c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5547d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5551da177e4SLinus Torvalds {
5561da177e4SLinus Torvalds 	/*
5571da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5581da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5591da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5601da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5611da177e4SLinus Torvalds 	 * PagePrivate for that.
5621da177e4SLinus Torvalds 	 *
5638174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5641da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5651da177e4SLinus Torvalds 	 * will block.
5661da177e4SLinus Torvalds 	 *
5671da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5681da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5691da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5701da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5711da177e4SLinus Torvalds 	 */
5721da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5731da177e4SLinus Torvalds 		return PAGE_KEEP;
5741da177e4SLinus Torvalds 	if (!mapping) {
5751da177e4SLinus Torvalds 		/*
5761da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5771da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5781da177e4SLinus Torvalds 		 */
579266cf658SDavid Howells 		if (page_has_private(page)) {
5801da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5811da177e4SLinus Torvalds 				ClearPageDirty(page);
582b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5831da177e4SLinus Torvalds 				return PAGE_CLEAN;
5841da177e4SLinus Torvalds 			}
5851da177e4SLinus Torvalds 		}
5861da177e4SLinus Torvalds 		return PAGE_KEEP;
5871da177e4SLinus Torvalds 	}
5881da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
5891da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
590703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
5911da177e4SLinus Torvalds 		return PAGE_KEEP;
5921da177e4SLinus Torvalds 
5931da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5941da177e4SLinus Torvalds 		int res;
5951da177e4SLinus Torvalds 		struct writeback_control wbc = {
5961da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5971da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
598111ebb6eSOGAWA Hirofumi 			.range_start = 0,
599111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6001da177e4SLinus Torvalds 			.for_reclaim = 1,
6011da177e4SLinus Torvalds 		};
6021da177e4SLinus Torvalds 
6031da177e4SLinus Torvalds 		SetPageReclaim(page);
6041da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6051da177e4SLinus Torvalds 		if (res < 0)
6061da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
607994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6081da177e4SLinus Torvalds 			ClearPageReclaim(page);
6091da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6101da177e4SLinus Torvalds 		}
611c661b078SAndy Whitcroft 
6121da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6131da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6141da177e4SLinus Torvalds 			ClearPageReclaim(page);
6151da177e4SLinus Torvalds 		}
6163aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
617c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6181da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6191da177e4SLinus Torvalds 	}
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds 	return PAGE_CLEAN;
6221da177e4SLinus Torvalds }
6231da177e4SLinus Torvalds 
624a649fd92SAndrew Morton /*
625e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
626e286781dSNick Piggin  * gets returned with a refcount of 0.
627a649fd92SAndrew Morton  */
628a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
629a528910eSJohannes Weiner 			    bool reclaimed)
63049d2e9ccSChristoph Lameter {
631c4843a75SGreg Thelen 	unsigned long flags;
632c4843a75SGreg Thelen 
63328e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
63428e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
63549d2e9ccSChristoph Lameter 
636c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
63749d2e9ccSChristoph Lameter 	/*
6380fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6390fd0e6b0SNick Piggin 	 *
6400fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6410fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6420fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6430fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6440fd0e6b0SNick Piggin 	 *
6450fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6460fd0e6b0SNick Piggin 	 * [user mapping goes away]
6470fd0e6b0SNick Piggin 	 * write_to(page);
6480fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6490fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6500fd0e6b0SNick Piggin 	 * put_page(page);
6510fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6520fd0e6b0SNick Piggin 	 *
6530fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6540fd0e6b0SNick Piggin 	 *
6550fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6560fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6570139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6580fd0e6b0SNick Piggin 	 *
6590fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6600fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
66149d2e9ccSChristoph Lameter 	 */
662fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
66349d2e9ccSChristoph Lameter 		goto cannot_free;
664e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
665e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
666fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
66749d2e9ccSChristoph Lameter 		goto cannot_free;
668e286781dSNick Piggin 	}
66949d2e9ccSChristoph Lameter 
67049d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
67149d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6720a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
67349d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
674c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6750a31bc97SJohannes Weiner 		swapcache_free(swap);
676e286781dSNick Piggin 	} else {
6776072d13cSLinus Torvalds 		void (*freepage)(struct page *);
678a528910eSJohannes Weiner 		void *shadow = NULL;
6796072d13cSLinus Torvalds 
6806072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
681a528910eSJohannes Weiner 		/*
682a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
683a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
684a528910eSJohannes Weiner 		 *
685a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
686a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
687a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
688a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
689a528910eSJohannes Weiner 		 * back.
690f9fe48beSRoss Zwisler 		 *
691f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
692f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
693f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
694f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
695f9fe48beSRoss Zwisler 		 * same page_tree.
696a528910eSJohannes Weiner 		 */
697a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
698f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
699a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
70062cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
701c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7026072d13cSLinus Torvalds 
7036072d13cSLinus Torvalds 		if (freepage != NULL)
7046072d13cSLinus Torvalds 			freepage(page);
705e286781dSNick Piggin 	}
706e286781dSNick Piggin 
70749d2e9ccSChristoph Lameter 	return 1;
70849d2e9ccSChristoph Lameter 
70949d2e9ccSChristoph Lameter cannot_free:
710c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
71149d2e9ccSChristoph Lameter 	return 0;
71249d2e9ccSChristoph Lameter }
71349d2e9ccSChristoph Lameter 
7141da177e4SLinus Torvalds /*
715e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
716e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
717e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
718e286781dSNick Piggin  * this page.
719e286781dSNick Piggin  */
720e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
721e286781dSNick Piggin {
722a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
723e286781dSNick Piggin 		/*
724e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
725e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
726e286781dSNick Piggin 		 * atomic operation.
727e286781dSNick Piggin 		 */
728fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
729e286781dSNick Piggin 		return 1;
730e286781dSNick Piggin 	}
731e286781dSNick Piggin 	return 0;
732e286781dSNick Piggin }
733e286781dSNick Piggin 
734894bc310SLee Schermerhorn /**
735894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
736894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
737894bc310SLee Schermerhorn  *
738894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
739894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
740894bc310SLee Schermerhorn  *
741894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
742894bc310SLee Schermerhorn  */
743894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
744894bc310SLee Schermerhorn {
7450ec3b74cSVlastimil Babka 	bool is_unevictable;
746bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
747894bc310SLee Schermerhorn 
748309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
749894bc310SLee Schermerhorn 
750894bc310SLee Schermerhorn redo:
751894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
752894bc310SLee Schermerhorn 
75339b5f29aSHugh Dickins 	if (page_evictable(page)) {
754894bc310SLee Schermerhorn 		/*
755894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
756894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
757894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
758894bc310SLee Schermerhorn 		 * We know how to handle that.
759894bc310SLee Schermerhorn 		 */
7600ec3b74cSVlastimil Babka 		is_unevictable = false;
761c53954a0SMel Gorman 		lru_cache_add(page);
762894bc310SLee Schermerhorn 	} else {
763894bc310SLee Schermerhorn 		/*
764894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
765894bc310SLee Schermerhorn 		 * list.
766894bc310SLee Schermerhorn 		 */
7670ec3b74cSVlastimil Babka 		is_unevictable = true;
768894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7696a7b9548SJohannes Weiner 		/*
77021ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
77121ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
77221ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
77324513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
77421ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7756a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7766a7b9548SJohannes Weiner 		 *
77721ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7786a7b9548SJohannes Weiner 		 */
7796a7b9548SJohannes Weiner 		smp_mb();
780894bc310SLee Schermerhorn 	}
781894bc310SLee Schermerhorn 
782894bc310SLee Schermerhorn 	/*
783894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
784894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
785894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
786894bc310SLee Schermerhorn 	 */
7870ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
788894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
789894bc310SLee Schermerhorn 			put_page(page);
790894bc310SLee Schermerhorn 			goto redo;
791894bc310SLee Schermerhorn 		}
792894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
793894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
794894bc310SLee Schermerhorn 		 * nothing to do here.
795894bc310SLee Schermerhorn 		 */
796894bc310SLee Schermerhorn 	}
797894bc310SLee Schermerhorn 
7980ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
799bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8000ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
801bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
802bbfd28eeSLee Schermerhorn 
803894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
804894bc310SLee Schermerhorn }
805894bc310SLee Schermerhorn 
806dfc8d636SJohannes Weiner enum page_references {
807dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
808dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
80964574746SJohannes Weiner 	PAGEREF_KEEP,
810dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
811dfc8d636SJohannes Weiner };
812dfc8d636SJohannes Weiner 
813dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
814dfc8d636SJohannes Weiner 						  struct scan_control *sc)
815dfc8d636SJohannes Weiner {
81664574746SJohannes Weiner 	int referenced_ptes, referenced_page;
817dfc8d636SJohannes Weiner 	unsigned long vm_flags;
818dfc8d636SJohannes Weiner 
819c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
820c3ac9a8aSJohannes Weiner 					  &vm_flags);
82164574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
822dfc8d636SJohannes Weiner 
823dfc8d636SJohannes Weiner 	/*
824dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
825dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
826dfc8d636SJohannes Weiner 	 */
827dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
828dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
829dfc8d636SJohannes Weiner 
83064574746SJohannes Weiner 	if (referenced_ptes) {
831e4898273SMichal Hocko 		if (PageSwapBacked(page))
83264574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
83364574746SJohannes Weiner 		/*
83464574746SJohannes Weiner 		 * All mapped pages start out with page table
83564574746SJohannes Weiner 		 * references from the instantiating fault, so we need
83664574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
83764574746SJohannes Weiner 		 * than once.
83864574746SJohannes Weiner 		 *
83964574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
84064574746SJohannes Weiner 		 * inactive list.  Another page table reference will
84164574746SJohannes Weiner 		 * lead to its activation.
84264574746SJohannes Weiner 		 *
84364574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
84464574746SJohannes Weiner 		 * so that recently deactivated but used pages are
84564574746SJohannes Weiner 		 * quickly recovered.
84664574746SJohannes Weiner 		 */
84764574746SJohannes Weiner 		SetPageReferenced(page);
84864574746SJohannes Weiner 
84934dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
850dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
851dfc8d636SJohannes Weiner 
852c909e993SKonstantin Khlebnikov 		/*
853c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
854c909e993SKonstantin Khlebnikov 		 */
855c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
856c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
857c909e993SKonstantin Khlebnikov 
85864574746SJohannes Weiner 		return PAGEREF_KEEP;
85964574746SJohannes Weiner 	}
86064574746SJohannes Weiner 
861dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8622e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
863dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
86464574746SJohannes Weiner 
86564574746SJohannes Weiner 	return PAGEREF_RECLAIM;
866dfc8d636SJohannes Weiner }
867dfc8d636SJohannes Weiner 
868e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
869e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
870e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
871e2be15f6SMel Gorman {
872b4597226SMel Gorman 	struct address_space *mapping;
873b4597226SMel Gorman 
874e2be15f6SMel Gorman 	/*
875e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
876e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
877e2be15f6SMel Gorman 	 */
878e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
879e2be15f6SMel Gorman 		*dirty = false;
880e2be15f6SMel Gorman 		*writeback = false;
881e2be15f6SMel Gorman 		return;
882e2be15f6SMel Gorman 	}
883e2be15f6SMel Gorman 
884e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
885e2be15f6SMel Gorman 	*dirty = PageDirty(page);
886e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
887b4597226SMel Gorman 
888b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
889b4597226SMel Gorman 	if (!page_has_private(page))
890b4597226SMel Gorman 		return;
891b4597226SMel Gorman 
892b4597226SMel Gorman 	mapping = page_mapping(page);
893b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
894b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
895e2be15f6SMel Gorman }
896e2be15f6SMel Gorman 
897e286781dSNick Piggin /*
8981742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8991da177e4SLinus Torvalds  */
9001742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
901599d0c95SMel Gorman 				      struct pglist_data *pgdat,
902f84f6e2bSMel Gorman 				      struct scan_control *sc,
90302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9048e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
905d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
9068e950282SMel Gorman 				      unsigned long *ret_nr_congested,
90702c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
908b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
90902c6de8dSMinchan Kim 				      bool force_reclaim)
9101da177e4SLinus Torvalds {
9111da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
912abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9131da177e4SLinus Torvalds 	int pgactivate = 0;
914d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
9150e093d99SMel Gorman 	unsigned long nr_dirty = 0;
9160e093d99SMel Gorman 	unsigned long nr_congested = 0;
91705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
91892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
919b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds 	cond_resched();
9221da177e4SLinus Torvalds 
9231da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9241da177e4SLinus Torvalds 		struct address_space *mapping;
9251da177e4SLinus Torvalds 		struct page *page;
9261da177e4SLinus Torvalds 		int may_enter_fs;
92702c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
928e2be15f6SMel Gorman 		bool dirty, writeback;
929854e9ed0SMinchan Kim 		bool lazyfree = false;
930854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9311da177e4SLinus Torvalds 
9321da177e4SLinus Torvalds 		cond_resched();
9331da177e4SLinus Torvalds 
9341da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9351da177e4SLinus Torvalds 		list_del(&page->lru);
9361da177e4SLinus Torvalds 
937529ae9aaSNick Piggin 		if (!trylock_page(page))
9381da177e4SLinus Torvalds 			goto keep;
9391da177e4SLinus Torvalds 
940309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9411da177e4SLinus Torvalds 
9421da177e4SLinus Torvalds 		sc->nr_scanned++;
94380e43426SChristoph Lameter 
94439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
945b291f000SNick Piggin 			goto cull_mlocked;
946894bc310SLee Schermerhorn 
947a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
94880e43426SChristoph Lameter 			goto keep_locked;
94980e43426SChristoph Lameter 
9501da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9511da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9521da177e4SLinus Torvalds 			sc->nr_scanned++;
9531da177e4SLinus Torvalds 
954c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
955c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
956c661b078SAndy Whitcroft 
957e62e384eSMichal Hocko 		/*
958e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
959e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
960e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
961e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
962e2be15f6SMel Gorman 		 */
963e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
964e2be15f6SMel Gorman 		if (dirty || writeback)
965e2be15f6SMel Gorman 			nr_dirty++;
966e2be15f6SMel Gorman 
967e2be15f6SMel Gorman 		if (dirty && !writeback)
968e2be15f6SMel Gorman 			nr_unqueued_dirty++;
969e2be15f6SMel Gorman 
970d04e8acdSMel Gorman 		/*
971d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
972d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
973d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
974d04e8acdSMel Gorman 		 * end of the LRU a second time.
975d04e8acdSMel Gorman 		 */
976e2be15f6SMel Gorman 		mapping = page_mapping(page);
9771da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
978703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
979d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
980e2be15f6SMel Gorman 			nr_congested++;
981e2be15f6SMel Gorman 
982e2be15f6SMel Gorman 		/*
983283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
984283aba9fSMel Gorman 		 * are three cases to consider.
985e62e384eSMichal Hocko 		 *
986283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
987283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
988283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
989283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
990283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
991283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
992283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
993b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
994b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
995c3b94f44SHugh Dickins 		 *
99697c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
997ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
998ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
999ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
100097c9341fSTejun Heo 		 *    reclaim and continue scanning.
1001283aba9fSMel Gorman 		 *
1002ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1003ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1004283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1005283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1006283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1007283aba9fSMel Gorman 		 *    would probably show more reasons.
1008283aba9fSMel Gorman 		 *
10097fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1010283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1011283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1012283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1013283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1014e62e384eSMichal Hocko 		 */
1015283aba9fSMel Gorman 		if (PageWriteback(page)) {
1016283aba9fSMel Gorman 			/* Case 1 above */
1017283aba9fSMel Gorman 			if (current_is_kswapd() &&
1018283aba9fSMel Gorman 			    PageReclaim(page) &&
1019599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1020b1a6f21eSMel Gorman 				nr_immediate++;
1021b1a6f21eSMel Gorman 				goto keep_locked;
1022283aba9fSMel Gorman 
1023283aba9fSMel Gorman 			/* Case 2 above */
102497c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1025ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1026c3b94f44SHugh Dickins 				/*
1027c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1028c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1029c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1030c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1031c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1032c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1033c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1034c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1035c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1036c3b94f44SHugh Dickins 				 */
1037c3b94f44SHugh Dickins 				SetPageReclaim(page);
103892df3a72SMel Gorman 				nr_writeback++;
1039c3b94f44SHugh Dickins 				goto keep_locked;
1040283aba9fSMel Gorman 
1041283aba9fSMel Gorman 			/* Case 3 above */
1042283aba9fSMel Gorman 			} else {
10437fadc820SHugh Dickins 				unlock_page(page);
1044c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10457fadc820SHugh Dickins 				/* then go back and try same page again */
10467fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10477fadc820SHugh Dickins 				continue;
1048e62e384eSMichal Hocko 			}
1049283aba9fSMel Gorman 		}
10501da177e4SLinus Torvalds 
105102c6de8dSMinchan Kim 		if (!force_reclaim)
10526a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
105302c6de8dSMinchan Kim 
1054dfc8d636SJohannes Weiner 		switch (references) {
1055dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10561da177e4SLinus Torvalds 			goto activate_locked;
105764574746SJohannes Weiner 		case PAGEREF_KEEP:
105864574746SJohannes Weiner 			goto keep_locked;
1059dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1060dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1061dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1062dfc8d636SJohannes Weiner 		}
10631da177e4SLinus Torvalds 
10641da177e4SLinus Torvalds 		/*
10651da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10661da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10671da177e4SLinus Torvalds 		 */
1068b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
106963eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
107063eb6b93SHugh Dickins 				goto keep_locked;
10715bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10721da177e4SLinus Torvalds 				goto activate_locked;
1073854e9ed0SMinchan Kim 			lazyfree = true;
107463eb6b93SHugh Dickins 			may_enter_fs = 1;
10751da177e4SLinus Torvalds 
1076e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10771da177e4SLinus Torvalds 			mapping = page_mapping(page);
10787751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
10797751b2daSKirill A. Shutemov 			/* Split file THP */
10807751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
10817751b2daSKirill A. Shutemov 				goto keep_locked;
1082e2be15f6SMel Gorman 		}
10831da177e4SLinus Torvalds 
10847751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
10857751b2daSKirill A. Shutemov 
10861da177e4SLinus Torvalds 		/*
10871da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10881da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10891da177e4SLinus Torvalds 		 */
10901da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1091854e9ed0SMinchan Kim 			switch (ret = try_to_unmap(page, lazyfree ?
1092854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
1093854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH))) {
10941da177e4SLinus Torvalds 			case SWAP_FAIL:
10951da177e4SLinus Torvalds 				goto activate_locked;
10961da177e4SLinus Torvalds 			case SWAP_AGAIN:
10971da177e4SLinus Torvalds 				goto keep_locked;
1098b291f000SNick Piggin 			case SWAP_MLOCK:
1099b291f000SNick Piggin 				goto cull_mlocked;
1100854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1101854e9ed0SMinchan Kim 				goto lazyfree;
11021da177e4SLinus Torvalds 			case SWAP_SUCCESS:
11031da177e4SLinus Torvalds 				; /* try to free the page below */
11041da177e4SLinus Torvalds 			}
11051da177e4SLinus Torvalds 		}
11061da177e4SLinus Torvalds 
11071da177e4SLinus Torvalds 		if (PageDirty(page)) {
1108ee72886dSMel Gorman 			/*
1109ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1110d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1111d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1112ee72886dSMel Gorman 			 */
1113f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11149e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
1115599d0c95SMel Gorman 					 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
111649ea7eb6SMel Gorman 				/*
111749ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
111849ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
111949ea7eb6SMel Gorman 				 * except we already have the page isolated
112049ea7eb6SMel Gorman 				 * and know it's dirty
112149ea7eb6SMel Gorman 				 */
1122c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
112349ea7eb6SMel Gorman 				SetPageReclaim(page);
112449ea7eb6SMel Gorman 
1125ee72886dSMel Gorman 				goto keep_locked;
1126ee72886dSMel Gorman 			}
1127ee72886dSMel Gorman 
1128dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11291da177e4SLinus Torvalds 				goto keep_locked;
11304dd4b920SAndrew Morton 			if (!may_enter_fs)
11311da177e4SLinus Torvalds 				goto keep_locked;
113252a8363eSChristoph Lameter 			if (!sc->may_writepage)
11331da177e4SLinus Torvalds 				goto keep_locked;
11341da177e4SLinus Torvalds 
1135d950c947SMel Gorman 			/*
1136d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1137d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1138d950c947SMel Gorman 			 * starts and then write it out here.
1139d950c947SMel Gorman 			 */
1140d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11417d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11421da177e4SLinus Torvalds 			case PAGE_KEEP:
11431da177e4SLinus Torvalds 				goto keep_locked;
11441da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11451da177e4SLinus Torvalds 				goto activate_locked;
11461da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11477d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
114841ac1999SMel Gorman 					goto keep;
11497d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11501da177e4SLinus Torvalds 					goto keep;
11517d3579e8SKOSAKI Motohiro 
11521da177e4SLinus Torvalds 				/*
11531da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11541da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11551da177e4SLinus Torvalds 				 */
1156529ae9aaSNick Piggin 				if (!trylock_page(page))
11571da177e4SLinus Torvalds 					goto keep;
11581da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11591da177e4SLinus Torvalds 					goto keep_locked;
11601da177e4SLinus Torvalds 				mapping = page_mapping(page);
11611da177e4SLinus Torvalds 			case PAGE_CLEAN:
11621da177e4SLinus Torvalds 				; /* try to free the page below */
11631da177e4SLinus Torvalds 			}
11641da177e4SLinus Torvalds 		}
11651da177e4SLinus Torvalds 
11661da177e4SLinus Torvalds 		/*
11671da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11681da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11691da177e4SLinus Torvalds 		 * the page as well.
11701da177e4SLinus Torvalds 		 *
11711da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11721da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11731da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11741da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11751da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11761da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11771da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11781da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11791da177e4SLinus Torvalds 		 *
11801da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11811da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11821da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11831da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11841da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11851da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11861da177e4SLinus Torvalds 		 */
1187266cf658SDavid Howells 		if (page_has_private(page)) {
11881da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11891da177e4SLinus Torvalds 				goto activate_locked;
1190e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1191e286781dSNick Piggin 				unlock_page(page);
1192e286781dSNick Piggin 				if (put_page_testzero(page))
11931da177e4SLinus Torvalds 					goto free_it;
1194e286781dSNick Piggin 				else {
1195e286781dSNick Piggin 					/*
1196e286781dSNick Piggin 					 * rare race with speculative reference.
1197e286781dSNick Piggin 					 * the speculative reference will free
1198e286781dSNick Piggin 					 * this page shortly, so we may
1199e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1200e286781dSNick Piggin 					 * leave it off the LRU).
1201e286781dSNick Piggin 					 */
1202e286781dSNick Piggin 					nr_reclaimed++;
1203e286781dSNick Piggin 					continue;
1204e286781dSNick Piggin 				}
1205e286781dSNick Piggin 			}
12061da177e4SLinus Torvalds 		}
12071da177e4SLinus Torvalds 
1208854e9ed0SMinchan Kim lazyfree:
1209a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
121049d2e9ccSChristoph Lameter 			goto keep_locked;
12111da177e4SLinus Torvalds 
1212a978d6f5SNick Piggin 		/*
1213a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1214a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1215a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1216a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1217a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1218a978d6f5SNick Piggin 		 */
121948c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1220e286781dSNick Piggin free_it:
1221854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1222854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1223854e9ed0SMinchan Kim 
122405ff5137SAndrew Morton 		nr_reclaimed++;
1225abe4c3b5SMel Gorman 
1226abe4c3b5SMel Gorman 		/*
1227abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1228abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1229abe4c3b5SMel Gorman 		 */
1230abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12311da177e4SLinus Torvalds 		continue;
12321da177e4SLinus Torvalds 
1233b291f000SNick Piggin cull_mlocked:
123463d6c5adSHugh Dickins 		if (PageSwapCache(page))
123563d6c5adSHugh Dickins 			try_to_free_swap(page);
1236b291f000SNick Piggin 		unlock_page(page);
1237c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1238b291f000SNick Piggin 		continue;
1239b291f000SNick Piggin 
12401da177e4SLinus Torvalds activate_locked:
124168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12425ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1243a2c43eedSHugh Dickins 			try_to_free_swap(page);
1244309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12451da177e4SLinus Torvalds 		SetPageActive(page);
12461da177e4SLinus Torvalds 		pgactivate++;
12471da177e4SLinus Torvalds keep_locked:
12481da177e4SLinus Torvalds 		unlock_page(page);
12491da177e4SLinus Torvalds keep:
12501da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1251309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12521da177e4SLinus Torvalds 	}
1253abe4c3b5SMel Gorman 
1254747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
125572b252aeSMel Gorman 	try_to_unmap_flush();
1256b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1257abe4c3b5SMel Gorman 
12581da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1259f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12600a31bc97SJohannes Weiner 
12618e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12628e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1263d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
126492df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1265b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
126605ff5137SAndrew Morton 	return nr_reclaimed;
12671da177e4SLinus Torvalds }
12681da177e4SLinus Torvalds 
126902c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
127002c6de8dSMinchan Kim 					    struct list_head *page_list)
127102c6de8dSMinchan Kim {
127202c6de8dSMinchan Kim 	struct scan_control sc = {
127302c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
127402c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
127502c6de8dSMinchan Kim 		.may_unmap = 1,
127602c6de8dSMinchan Kim 	};
12778e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
127802c6de8dSMinchan Kim 	struct page *page, *next;
127902c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
128002c6de8dSMinchan Kim 
128102c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1282117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1283b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
128402c6de8dSMinchan Kim 			ClearPageActive(page);
128502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
128602c6de8dSMinchan Kim 		}
128702c6de8dSMinchan Kim 	}
128802c6de8dSMinchan Kim 
1289599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
129002c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
12918e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
129202c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1293599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
129402c6de8dSMinchan Kim 	return ret;
129502c6de8dSMinchan Kim }
129602c6de8dSMinchan Kim 
12975ad333ebSAndy Whitcroft /*
12985ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
12995ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13005ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13015ad333ebSAndy Whitcroft  *
13025ad333ebSAndy Whitcroft  * page:	page to consider
13035ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13045ad333ebSAndy Whitcroft  *
13055ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13065ad333ebSAndy Whitcroft  */
1307f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13085ad333ebSAndy Whitcroft {
13095ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13105ad333ebSAndy Whitcroft 
13115ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13125ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13135ad333ebSAndy Whitcroft 		return ret;
13145ad333ebSAndy Whitcroft 
1315e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1316e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1317894bc310SLee Schermerhorn 		return ret;
1318894bc310SLee Schermerhorn 
13195ad333ebSAndy Whitcroft 	ret = -EBUSY;
132008e552c6SKAMEZAWA Hiroyuki 
1321c8244935SMel Gorman 	/*
1322c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1323c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1324c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1325c8244935SMel Gorman 	 *
1326c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1327c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1328c8244935SMel Gorman 	 *
1329c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1330c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1331c8244935SMel Gorman 	 */
1332c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1333c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1334c8244935SMel Gorman 		if (PageWriteback(page))
133539deaf85SMinchan Kim 			return ret;
133639deaf85SMinchan Kim 
1337c8244935SMel Gorman 		if (PageDirty(page)) {
1338c8244935SMel Gorman 			struct address_space *mapping;
1339c8244935SMel Gorman 
1340c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1341c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1342c8244935SMel Gorman 				return ret;
1343c8244935SMel Gorman 
1344c8244935SMel Gorman 			/*
1345c8244935SMel Gorman 			 * Only pages without mappings or that have a
1346c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1347c8244935SMel Gorman 			 * without blocking
1348c8244935SMel Gorman 			 */
1349c8244935SMel Gorman 			mapping = page_mapping(page);
1350c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1351c8244935SMel Gorman 				return ret;
1352c8244935SMel Gorman 		}
1353c8244935SMel Gorman 	}
1354c8244935SMel Gorman 
1355f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1356f80c0673SMinchan Kim 		return ret;
1357f80c0673SMinchan Kim 
13585ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13595ad333ebSAndy Whitcroft 		/*
13605ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13615ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13625ad333ebSAndy Whitcroft 		 * page release code relies on it.
13635ad333ebSAndy Whitcroft 		 */
13645ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13655ad333ebSAndy Whitcroft 		ret = 0;
13665ad333ebSAndy Whitcroft 	}
13675ad333ebSAndy Whitcroft 
13685ad333ebSAndy Whitcroft 	return ret;
13695ad333ebSAndy Whitcroft }
13705ad333ebSAndy Whitcroft 
13717ee36a14SMel Gorman 
13727ee36a14SMel Gorman /*
13737ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
13747ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
13757ee36a14SMel Gorman  */
13767ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
13777ee36a14SMel Gorman 			enum lru_list lru, unsigned long *nr_zone_taken,
13787ee36a14SMel Gorman 			unsigned long nr_taken)
13797ee36a14SMel Gorman {
13807ee36a14SMel Gorman 	int zid;
13817ee36a14SMel Gorman 
13827ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
13837ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
13847ee36a14SMel Gorman 			continue;
13857ee36a14SMel Gorman 
13867ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
13877ee36a14SMel Gorman 	}
13887ee36a14SMel Gorman 
13897ee36a14SMel Gorman #ifdef CONFIG_MEMCG
13907ee36a14SMel Gorman 	mem_cgroup_update_lru_size(lruvec, lru, -nr_taken);
13917ee36a14SMel Gorman #endif
13927ee36a14SMel Gorman }
13937ee36a14SMel Gorman 
139449d2e9ccSChristoph Lameter /*
1395a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
13961da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
13971da177e4SLinus Torvalds  * and working on them outside the LRU lock.
13981da177e4SLinus Torvalds  *
13991da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14001da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14011da177e4SLinus Torvalds  *
14021da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14031da177e4SLinus Torvalds  *
14041da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
14055dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14061da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1407f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1408fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14095ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14103cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14111da177e4SLinus Torvalds  *
14121da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14131da177e4SLinus Torvalds  */
141469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14155dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1416fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14173cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14181da177e4SLinus Torvalds {
141975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
142069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1421599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14227cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1423599d0c95SMel Gorman 	unsigned long scan, nr_pages;
1424b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14251da177e4SLinus Torvalds 
14260b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
1427d7f05528SMel Gorman 					!list_empty(src);) {
14285ad333ebSAndy Whitcroft 		struct page *page;
14295ad333ebSAndy Whitcroft 
14301da177e4SLinus Torvalds 		page = lru_to_page(src);
14311da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14321da177e4SLinus Torvalds 
1433309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14348d438f96SNick Piggin 
1435b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1436b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
14377cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1438b2e18757SMel Gorman 			continue;
1439b2e18757SMel Gorman 		}
1440b2e18757SMel Gorman 
1441d7f05528SMel Gorman 		/*
1442d7f05528SMel Gorman 		 * Account for scanned and skipped separetly to avoid the pgdat
1443d7f05528SMel Gorman 		 * being prematurely marked unreclaimable by pgdat_reclaimable.
1444d7f05528SMel Gorman 		 */
1445d7f05528SMel Gorman 		scan++;
1446d7f05528SMel Gorman 
1447f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14485ad333ebSAndy Whitcroft 		case 0:
1449599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1450599d0c95SMel Gorman 			nr_taken += nr_pages;
1451599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14525ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14535ad333ebSAndy Whitcroft 			break;
14547c8ee9a8SNick Piggin 
14555ad333ebSAndy Whitcroft 		case -EBUSY:
14565ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
14575ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
14585ad333ebSAndy Whitcroft 			continue;
14595ad333ebSAndy Whitcroft 
14605ad333ebSAndy Whitcroft 		default:
14615ad333ebSAndy Whitcroft 			BUG();
14625ad333ebSAndy Whitcroft 		}
14635ad333ebSAndy Whitcroft 	}
14641da177e4SLinus Torvalds 
1465b2e18757SMel Gorman 	/*
1466b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1467b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1468b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1469b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1470b2e18757SMel Gorman 	 * system at risk of premature OOM.
1471b2e18757SMel Gorman 	 */
14727cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
14737cc30fcfSMel Gorman 		int zid;
1474d7f05528SMel Gorman 		unsigned long total_skipped = 0;
14757cc30fcfSMel Gorman 
14767cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14777cc30fcfSMel Gorman 			if (!nr_skipped[zid])
14787cc30fcfSMel Gorman 				continue;
14797cc30fcfSMel Gorman 
14807cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1481d7f05528SMel Gorman 			total_skipped += nr_skipped[zid];
14827cc30fcfSMel Gorman 		}
1483d7f05528SMel Gorman 
1484d7f05528SMel Gorman 		/*
1485d7f05528SMel Gorman 		 * Account skipped pages as a partial scan as the pgdat may be
1486d7f05528SMel Gorman 		 * close to unreclaimable. If the LRU list is empty, account
1487d7f05528SMel Gorman 		 * skipped pages as a full scan.
1488d7f05528SMel Gorman 		 */
1489d7f05528SMel Gorman 		scan += list_empty(src) ? total_skipped : total_skipped >> 2;
1490d7f05528SMel Gorman 
1491d7f05528SMel Gorman 		list_splice(&pages_skipped, src);
14927cc30fcfSMel Gorman 	}
1493f626012dSHugh Dickins 	*nr_scanned = scan;
1494e5146b12SMel Gorman 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, scan,
149575b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
14967ee36a14SMel Gorman 	update_lru_sizes(lruvec, lru, nr_zone_taken, nr_taken);
14971da177e4SLinus Torvalds 	return nr_taken;
14981da177e4SLinus Torvalds }
14991da177e4SLinus Torvalds 
150062695a84SNick Piggin /**
150162695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
150262695a84SNick Piggin  * @page: page to isolate from its LRU list
150362695a84SNick Piggin  *
150462695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
150562695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
150662695a84SNick Piggin  *
150762695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
150862695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
150962695a84SNick Piggin  *
151062695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1511894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1512894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1513894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
151462695a84SNick Piggin  *
151562695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
151662695a84SNick Piggin  * found will be decremented.
151762695a84SNick Piggin  *
151862695a84SNick Piggin  * Restrictions:
151962695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
152062695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
152162695a84SNick Piggin  *     without a stable reference).
152262695a84SNick Piggin  * (2) the lru_lock must not be held.
152362695a84SNick Piggin  * (3) interrupts must be enabled.
152462695a84SNick Piggin  */
152562695a84SNick Piggin int isolate_lru_page(struct page *page)
152662695a84SNick Piggin {
152762695a84SNick Piggin 	int ret = -EBUSY;
152862695a84SNick Piggin 
1529309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1530cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15310c917313SKonstantin Khlebnikov 
153262695a84SNick Piggin 	if (PageLRU(page)) {
153362695a84SNick Piggin 		struct zone *zone = page_zone(page);
1534fa9add64SHugh Dickins 		struct lruvec *lruvec;
153562695a84SNick Piggin 
1536a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1537599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
15380c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1539894bc310SLee Schermerhorn 			int lru = page_lru(page);
15400c917313SKonstantin Khlebnikov 			get_page(page);
154162695a84SNick Piggin 			ClearPageLRU(page);
1542fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1543fa9add64SHugh Dickins 			ret = 0;
154462695a84SNick Piggin 		}
1545a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
154662695a84SNick Piggin 	}
154762695a84SNick Piggin 	return ret;
154862695a84SNick Piggin }
154962695a84SNick Piggin 
15505ad333ebSAndy Whitcroft /*
1551d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1552d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1553d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1554d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1555d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
155635cd7815SRik van Riel  */
1557599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
155835cd7815SRik van Riel 		struct scan_control *sc)
155935cd7815SRik van Riel {
156035cd7815SRik van Riel 	unsigned long inactive, isolated;
156135cd7815SRik van Riel 
156235cd7815SRik van Riel 	if (current_is_kswapd())
156335cd7815SRik van Riel 		return 0;
156435cd7815SRik van Riel 
156597c9341fSTejun Heo 	if (!sane_reclaim(sc))
156635cd7815SRik van Riel 		return 0;
156735cd7815SRik van Riel 
156835cd7815SRik van Riel 	if (file) {
1569599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1570599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
157135cd7815SRik van Riel 	} else {
1572599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1573599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
157435cd7815SRik van Riel 	}
157535cd7815SRik van Riel 
15763cf23841SFengguang Wu 	/*
15773cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
15783cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
15793cf23841SFengguang Wu 	 * deadlock.
15803cf23841SFengguang Wu 	 */
1581d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
15823cf23841SFengguang Wu 		inactive >>= 3;
15833cf23841SFengguang Wu 
158435cd7815SRik van Riel 	return isolated > inactive;
158535cd7815SRik van Riel }
158635cd7815SRik van Riel 
158766635629SMel Gorman static noinline_for_stack void
158875b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
158966635629SMel Gorman {
159027ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1591599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
15923f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
159366635629SMel Gorman 
159466635629SMel Gorman 	/*
159566635629SMel Gorman 	 * Put back any unfreeable pages.
159666635629SMel Gorman 	 */
159766635629SMel Gorman 	while (!list_empty(page_list)) {
15983f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
159966635629SMel Gorman 		int lru;
16003f79768fSHugh Dickins 
1601309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
160266635629SMel Gorman 		list_del(&page->lru);
160339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1604599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
160566635629SMel Gorman 			putback_lru_page(page);
1606599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
160766635629SMel Gorman 			continue;
160866635629SMel Gorman 		}
1609fa9add64SHugh Dickins 
1610599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1611fa9add64SHugh Dickins 
16127a608572SLinus Torvalds 		SetPageLRU(page);
161366635629SMel Gorman 		lru = page_lru(page);
1614fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1615fa9add64SHugh Dickins 
161666635629SMel Gorman 		if (is_active_lru(lru)) {
161766635629SMel Gorman 			int file = is_file_lru(lru);
16189992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16199992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
162066635629SMel Gorman 		}
16212bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16222bcf8879SHugh Dickins 			__ClearPageLRU(page);
16232bcf8879SHugh Dickins 			__ClearPageActive(page);
1624fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16252bcf8879SHugh Dickins 
16262bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1627599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1628747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16292bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1630599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16312bcf8879SHugh Dickins 			} else
16322bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
163366635629SMel Gorman 		}
163466635629SMel Gorman 	}
163566635629SMel Gorman 
16363f79768fSHugh Dickins 	/*
16373f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
16383f79768fSHugh Dickins 	 */
16393f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
164066635629SMel Gorman }
164166635629SMel Gorman 
164266635629SMel Gorman /*
1643399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1644399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1645399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1646399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1647399ba0b9SNeilBrown  */
1648399ba0b9SNeilBrown static int current_may_throttle(void)
1649399ba0b9SNeilBrown {
1650399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1651399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1652399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1653399ba0b9SNeilBrown }
1654399ba0b9SNeilBrown 
165591dcade4SMinchan Kim static bool inactive_reclaimable_pages(struct lruvec *lruvec,
165691dcade4SMinchan Kim 				struct scan_control *sc, enum lru_list lru)
165791dcade4SMinchan Kim {
165891dcade4SMinchan Kim 	int zid;
165991dcade4SMinchan Kim 	struct zone *zone;
166091dcade4SMinchan Kim 	int file = is_file_lru(lru);
166191dcade4SMinchan Kim 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
166291dcade4SMinchan Kim 
166391dcade4SMinchan Kim 	if (!global_reclaim(sc))
166491dcade4SMinchan Kim 		return true;
166591dcade4SMinchan Kim 
166691dcade4SMinchan Kim 	for (zid = sc->reclaim_idx; zid >= 0; zid--) {
166791dcade4SMinchan Kim 		zone = &pgdat->node_zones[zid];
16686aa303deSMel Gorman 		if (!managed_zone(zone))
166991dcade4SMinchan Kim 			continue;
167091dcade4SMinchan Kim 
167191dcade4SMinchan Kim 		if (zone_page_state_snapshot(zone, NR_ZONE_LRU_BASE +
167291dcade4SMinchan Kim 				LRU_FILE * file) >= SWAP_CLUSTER_MAX)
167391dcade4SMinchan Kim 			return true;
167491dcade4SMinchan Kim 	}
167591dcade4SMinchan Kim 
167691dcade4SMinchan Kim 	return false;
167791dcade4SMinchan Kim }
167891dcade4SMinchan Kim 
1679399ba0b9SNeilBrown /*
1680b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16811742f19fSAndrew Morton  * of reclaimed pages
16821da177e4SLinus Torvalds  */
168366635629SMel Gorman static noinline_for_stack unsigned long
16841a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
16859e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
16861da177e4SLinus Torvalds {
16871da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1688e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
168905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1690e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
16918e950282SMel Gorman 	unsigned long nr_dirty = 0;
16928e950282SMel Gorman 	unsigned long nr_congested = 0;
1693e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
169492df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1695b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1696f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16973cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1698599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16991a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
170078dc583dSKOSAKI Motohiro 
170191dcade4SMinchan Kim 	if (!inactive_reclaimable_pages(lruvec, sc, lru))
170291dcade4SMinchan Kim 		return 0;
170391dcade4SMinchan Kim 
1704599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
170558355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
170635cd7815SRik van Riel 
170735cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
170835cd7815SRik van Riel 		if (fatal_signal_pending(current))
170935cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
171035cd7815SRik van Riel 	}
171135cd7815SRik van Riel 
17121da177e4SLinus Torvalds 	lru_add_drain();
1713f80c0673SMinchan Kim 
1714f80c0673SMinchan Kim 	if (!sc->may_unmap)
171561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1716f80c0673SMinchan Kim 	if (!sc->may_writepage)
171761317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1718f80c0673SMinchan Kim 
1719599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17201da177e4SLinus Torvalds 
17215dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17225dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
172395d918fcSKonstantin Khlebnikov 
1724599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17259d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
172695d918fcSKonstantin Khlebnikov 
172789b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1728599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1729b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1730599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
1731b35ea17bSKOSAKI Motohiro 		else
1732599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
1733b35ea17bSKOSAKI Motohiro 	}
1734599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1735d563c050SHillf Danton 
1736d563c050SHillf Danton 	if (nr_taken == 0)
173766635629SMel Gorman 		return 0;
1738b35ea17bSKOSAKI Motohiro 
1739599d0c95SMel Gorman 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, TTU_UNMAP,
17408e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
17418e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1742b1a6f21eSMel Gorman 				false);
1743c661b078SAndy Whitcroft 
1744599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17453f79768fSHugh Dickins 
1746904249aaSYing Han 	if (global_reclaim(sc)) {
1747b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1748599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
1749904249aaSYing Han 		else
1750599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
1751904249aaSYing Han 	}
1752a74609faSNick Piggin 
175327ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
17543f79768fSHugh Dickins 
1755599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
17563f79768fSHugh Dickins 
1757599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
17583f79768fSHugh Dickins 
1759747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1760b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1761e11da5b4SMel Gorman 
176292df3a72SMel Gorman 	/*
176392df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
176492df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
176592df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
176692df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
176792df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
176892df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
176992df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
177092df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
177192df3a72SMel Gorman 	 *
17728e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
17738e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17748e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
177592df3a72SMel Gorman 	 */
1776918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1777599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
177892df3a72SMel Gorman 
1779d43006d5SMel Gorman 	/*
178097c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
178197c9341fSTejun Heo 	 * stalling here.
1782d43006d5SMel Gorman 	 */
178397c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1784b1a6f21eSMel Gorman 		/*
17858e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
17868e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
17878e950282SMel Gorman 		 */
17888e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
1789599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
17908e950282SMel Gorman 
17918e950282SMel Gorman 		/*
1792b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1793b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1794599d0c95SMel Gorman 		 * the pgdat PGDAT_DIRTY and kswapd will start writing pages from
179557054651SJohannes Weiner 		 * reclaim context.
1796b1a6f21eSMel Gorman 		 */
1797b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1798599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1799b1a6f21eSMel Gorman 
1800b1a6f21eSMel Gorman 		/*
1801b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1802b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1803b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1804b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1805b1a6f21eSMel Gorman 		 */
1806b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1807b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1808e2be15f6SMel Gorman 	}
1809d43006d5SMel Gorman 
18108e950282SMel Gorman 	/*
18118e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
18128e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18138e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18148e950282SMel Gorman 	 */
1815399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1816399ba0b9SNeilBrown 	    current_may_throttle())
1817599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18188e950282SMel Gorman 
1819599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1820599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
1821ba5e9579Syalin wang 			sc->priority, file);
182205ff5137SAndrew Morton 	return nr_reclaimed;
18231da177e4SLinus Torvalds }
18241da177e4SLinus Torvalds 
18253bb1a852SMartin Bligh /*
18261cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18271cfb419bSKAMEZAWA Hiroyuki  *
18281cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18291cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18301cfb419bSKAMEZAWA Hiroyuki  *
18311cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1832a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18331cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1834a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18351cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18361cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18371cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18381cfb419bSKAMEZAWA Hiroyuki  *
18390139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18401cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
18411cfb419bSKAMEZAWA Hiroyuki  */
18421cfb419bSKAMEZAWA Hiroyuki 
1843fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
18443eb4140fSWu Fengguang 				     struct list_head *list,
18452bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18463eb4140fSWu Fengguang 				     enum lru_list lru)
18473eb4140fSWu Fengguang {
1848599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18493eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
18503eb4140fSWu Fengguang 	struct page *page;
1851fa9add64SHugh Dickins 	int nr_pages;
18523eb4140fSWu Fengguang 
18533eb4140fSWu Fengguang 	while (!list_empty(list)) {
18543eb4140fSWu Fengguang 		page = lru_to_page(list);
1855599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18563eb4140fSWu Fengguang 
1857309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18583eb4140fSWu Fengguang 		SetPageLRU(page);
18593eb4140fSWu Fengguang 
1860fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1861599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1862925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1863fa9add64SHugh Dickins 		pgmoved += nr_pages;
18643eb4140fSWu Fengguang 
18652bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18662bcf8879SHugh Dickins 			__ClearPageLRU(page);
18672bcf8879SHugh Dickins 			__ClearPageActive(page);
1868fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18692bcf8879SHugh Dickins 
18702bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1871599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1872747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18732bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1874599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18752bcf8879SHugh Dickins 			} else
18762bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18773eb4140fSWu Fengguang 		}
18783eb4140fSWu Fengguang 	}
18799d5e6a9fSHugh Dickins 
18803eb4140fSWu Fengguang 	if (!is_active_lru(lru))
18813eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
18823eb4140fSWu Fengguang }
18831cfb419bSKAMEZAWA Hiroyuki 
1884f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
18851a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1886f16015fbSJohannes Weiner 			       struct scan_control *sc,
18879e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
18881cfb419bSKAMEZAWA Hiroyuki {
188944c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1890f626012dSHugh Dickins 	unsigned long nr_scanned;
18916fe6b7e3SWu Fengguang 	unsigned long vm_flags;
18921cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
18938cab4754SWu Fengguang 	LIST_HEAD(l_active);
1894b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
18951cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
18961a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
189744c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1898f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
18993cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1900599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19011cfb419bSKAMEZAWA Hiroyuki 
19021da177e4SLinus Torvalds 	lru_add_drain();
1903f80c0673SMinchan Kim 
1904f80c0673SMinchan Kim 	if (!sc->may_unmap)
190561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1906f80c0673SMinchan Kim 	if (!sc->may_writepage)
190761317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1908f80c0673SMinchan Kim 
1909599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1910925b7673SJohannes Weiner 
19115dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19125dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
191389b5fae5SJohannes Weiner 
1914599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1915b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19161cfb419bSKAMEZAWA Hiroyuki 
19179d5e6a9fSHugh Dickins 	if (global_reclaim(sc))
1918599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1919599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19209d5e6a9fSHugh Dickins 
1921599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19221da177e4SLinus Torvalds 
19231da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19241da177e4SLinus Torvalds 		cond_resched();
19251da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19261da177e4SLinus Torvalds 		list_del(&page->lru);
19277e9cd484SRik van Riel 
192839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1929894bc310SLee Schermerhorn 			putback_lru_page(page);
1930894bc310SLee Schermerhorn 			continue;
1931894bc310SLee Schermerhorn 		}
1932894bc310SLee Schermerhorn 
1933cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1934cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1935cc715d99SMel Gorman 				if (page_has_private(page))
1936cc715d99SMel Gorman 					try_to_release_page(page, 0);
1937cc715d99SMel Gorman 				unlock_page(page);
1938cc715d99SMel Gorman 			}
1939cc715d99SMel Gorman 		}
1940cc715d99SMel Gorman 
1941c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1942c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19439992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19448cab4754SWu Fengguang 			/*
19458cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19468cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19478cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19488cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19498cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19508cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19518cab4754SWu Fengguang 			 * so we ignore them here.
19528cab4754SWu Fengguang 			 */
195341e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19548cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19558cab4754SWu Fengguang 				continue;
19568cab4754SWu Fengguang 			}
19578cab4754SWu Fengguang 		}
19587e9cd484SRik van Riel 
19595205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19601da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19611da177e4SLinus Torvalds 	}
19621da177e4SLinus Torvalds 
1963b555749aSAndrew Morton 	/*
19648cab4754SWu Fengguang 	 * Move pages back to the lru list.
1965b555749aSAndrew Morton 	 */
1966599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19674f98a2feSRik van Riel 	/*
19688cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19698cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19708cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19717c0db9e9SJerome Marchand 	 * get_scan_count.
1972556adecbSRik van Riel 	 */
1973b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1974556adecbSRik van Riel 
1975fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1976fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1977599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1978599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19792bcf8879SHugh Dickins 
1980747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1981b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
19821da177e4SLinus Torvalds }
19831da177e4SLinus Torvalds 
198459dc76b0SRik van Riel /*
198559dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
198659dc76b0SRik van Riel  * to do too much work.
198714797e23SKOSAKI Motohiro  *
198859dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
198959dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
199059dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
199159dc76b0SRik van Riel  *
199259dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
199359dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
199459dc76b0SRik van Riel  *
199559dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
199659dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
199759dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
199859dc76b0SRik van Riel  *
199959dc76b0SRik van Riel  * total     target    max
200059dc76b0SRik van Riel  * memory    ratio     inactive
200159dc76b0SRik van Riel  * -------------------------------------
200259dc76b0SRik van Riel  *   10MB       1         5MB
200359dc76b0SRik van Riel  *  100MB       1        50MB
200459dc76b0SRik van Riel  *    1GB       3       250MB
200559dc76b0SRik van Riel  *   10GB      10       0.9GB
200659dc76b0SRik van Riel  *  100GB      31         3GB
200759dc76b0SRik van Riel  *    1TB     101        10GB
200859dc76b0SRik van Riel  *   10TB     320        32GB
200914797e23SKOSAKI Motohiro  */
2010f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
2011f8d1a311SMel Gorman 						struct scan_control *sc)
201214797e23SKOSAKI Motohiro {
201359dc76b0SRik van Riel 	unsigned long inactive_ratio;
201459dc76b0SRik van Riel 	unsigned long inactive;
201559dc76b0SRik van Riel 	unsigned long active;
201659dc76b0SRik van Riel 	unsigned long gb;
2017f8d1a311SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2018f8d1a311SMel Gorman 	int zid;
201959dc76b0SRik van Riel 
202074e3f3c3SMinchan Kim 	/*
202174e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
202274e3f3c3SMinchan Kim 	 * is pointless.
202374e3f3c3SMinchan Kim 	 */
202459dc76b0SRik van Riel 	if (!file && !total_swap_pages)
202542e2e457SYaowei Bai 		return false;
202674e3f3c3SMinchan Kim 
202759dc76b0SRik van Riel 	inactive = lruvec_lru_size(lruvec, file * LRU_FILE);
202859dc76b0SRik van Riel 	active = lruvec_lru_size(lruvec, file * LRU_FILE + LRU_ACTIVE);
2029f16015fbSJohannes Weiner 
2030f8d1a311SMel Gorman 	/*
2031f8d1a311SMel Gorman 	 * For zone-constrained allocations, it is necessary to check if
2032f8d1a311SMel Gorman 	 * deactivations are required for lowmem to be reclaimed. This
2033f8d1a311SMel Gorman 	 * calculates the inactive/active pages available in eligible zones.
2034f8d1a311SMel Gorman 	 */
2035f8d1a311SMel Gorman 	for (zid = sc->reclaim_idx + 1; zid < MAX_NR_ZONES; zid++) {
2036f8d1a311SMel Gorman 		struct zone *zone = &pgdat->node_zones[zid];
2037f8d1a311SMel Gorman 		unsigned long inactive_zone, active_zone;
2038f8d1a311SMel Gorman 
20396aa303deSMel Gorman 		if (!managed_zone(zone))
2040f8d1a311SMel Gorman 			continue;
2041f8d1a311SMel Gorman 
2042f8d1a311SMel Gorman 		inactive_zone = zone_page_state(zone,
2043f8d1a311SMel Gorman 				NR_ZONE_LRU_BASE + (file * LRU_FILE));
2044f8d1a311SMel Gorman 		active_zone = zone_page_state(zone,
2045f8d1a311SMel Gorman 				NR_ZONE_LRU_BASE + (file * LRU_FILE) + LRU_ACTIVE);
2046f8d1a311SMel Gorman 
2047f8d1a311SMel Gorman 		inactive -= min(inactive, inactive_zone);
2048f8d1a311SMel Gorman 		active -= min(active, active_zone);
2049f8d1a311SMel Gorman 	}
2050f8d1a311SMel Gorman 
205159dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
205259dc76b0SRik van Riel 	if (gb)
205359dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2054b39415b2SRik van Riel 	else
205559dc76b0SRik van Riel 		inactive_ratio = 1;
205659dc76b0SRik van Riel 
205759dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2058b39415b2SRik van Riel }
2059b39415b2SRik van Riel 
20604f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
20611a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
2062b69408e8SChristoph Lameter {
2063b39415b2SRik van Riel 	if (is_active_lru(lru)) {
2064f8d1a311SMel Gorman 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc))
20651a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2066556adecbSRik van Riel 		return 0;
2067556adecbSRik van Riel 	}
2068556adecbSRik van Riel 
20691a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2070b69408e8SChristoph Lameter }
2071b69408e8SChristoph Lameter 
20729a265114SJohannes Weiner enum scan_balance {
20739a265114SJohannes Weiner 	SCAN_EQUAL,
20749a265114SJohannes Weiner 	SCAN_FRACT,
20759a265114SJohannes Weiner 	SCAN_ANON,
20769a265114SJohannes Weiner 	SCAN_FILE,
20779a265114SJohannes Weiner };
20789a265114SJohannes Weiner 
20791da177e4SLinus Torvalds /*
20804f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
20814f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
20824f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
20834f98a2feSRik van Riel  * onto the active list instead of evict.
20844f98a2feSRik van Riel  *
2085be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2086be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
20874f98a2feSRik van Riel  */
208833377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
20896b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
20906b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
20914f98a2feSRik van Riel {
209233377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
209390126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20949a265114SJohannes Weiner 	u64 fraction[2];
20959a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2096599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20979a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
20989a265114SJohannes Weiner 	enum scan_balance scan_balance;
20990bf1457fSJohannes Weiner 	unsigned long anon, file;
21009a265114SJohannes Weiner 	bool force_scan = false;
21019a265114SJohannes Weiner 	unsigned long ap, fp;
21029a265114SJohannes Weiner 	enum lru_list lru;
21036f04f48dSSuleiman Souhlal 	bool some_scanned;
21046f04f48dSSuleiman Souhlal 	int pass;
2105246e87a9SKAMEZAWA Hiroyuki 
2106f11c0ca5SJohannes Weiner 	/*
2107f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
2108f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
2109f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
2110f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
2111f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
2112f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
2113f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
2114f11c0ca5SJohannes Weiner 	 * well.
2115f11c0ca5SJohannes Weiner 	 */
211690cbc250SVladimir Davydov 	if (current_is_kswapd()) {
2117599d0c95SMel Gorman 		if (!pgdat_reclaimable(pgdat))
2118a4d3e9e7SJohannes Weiner 			force_scan = true;
2119eb01aaabSVladimir Davydov 		if (!mem_cgroup_online(memcg))
212090cbc250SVladimir Davydov 			force_scan = true;
212190cbc250SVladimir Davydov 	}
212289b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
2123a4d3e9e7SJohannes Weiner 		force_scan = true;
212476a33fc3SShaohua Li 
212576a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2126d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21279a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
212876a33fc3SShaohua Li 		goto out;
212976a33fc3SShaohua Li 	}
21304f98a2feSRik van Riel 
213110316b31SJohannes Weiner 	/*
213210316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
213310316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
213410316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
213510316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
213610316b31SJohannes Weiner 	 * too expensive.
213710316b31SJohannes Weiner 	 */
213802695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21399a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
214010316b31SJohannes Weiner 		goto out;
214110316b31SJohannes Weiner 	}
214210316b31SJohannes Weiner 
214310316b31SJohannes Weiner 	/*
214410316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
214510316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
214610316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
214710316b31SJohannes Weiner 	 */
214802695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21499a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
215010316b31SJohannes Weiner 		goto out;
215110316b31SJohannes Weiner 	}
215210316b31SJohannes Weiner 
215311d16c25SJohannes Weiner 	/*
215462376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
215562376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
215662376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
215762376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
215862376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
215962376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
216062376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
216162376251SJohannes Weiner 	 */
216262376251SJohannes Weiner 	if (global_reclaim(sc)) {
2163599d0c95SMel Gorman 		unsigned long pgdatfile;
2164599d0c95SMel Gorman 		unsigned long pgdatfree;
2165599d0c95SMel Gorman 		int z;
2166599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
216762376251SJohannes Weiner 
2168599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2169599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2170599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21712ab051e1SJerome Marchand 
2172599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2173599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
21746aa303deSMel Gorman 			if (!managed_zone(zone))
2175599d0c95SMel Gorman 				continue;
2176599d0c95SMel Gorman 
2177599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2178599d0c95SMel Gorman 		}
2179599d0c95SMel Gorman 
2180599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
218162376251SJohannes Weiner 			scan_balance = SCAN_ANON;
218262376251SJohannes Weiner 			goto out;
218362376251SJohannes Weiner 		}
218462376251SJohannes Weiner 	}
218562376251SJohannes Weiner 
218662376251SJohannes Weiner 	/*
2187316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2188316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2189316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2190316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2191316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2192316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2193316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2194e9868505SRik van Riel 	 */
2195f8d1a311SMel Gorman 	if (!inactive_list_is_low(lruvec, true, sc) &&
219623047a96SJohannes Weiner 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
21979a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2198e9868505SRik van Riel 		goto out;
21994f98a2feSRik van Riel 	}
22004f98a2feSRik van Riel 
22019a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22029a265114SJohannes Weiner 
22034f98a2feSRik van Riel 	/*
220458c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
220558c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
220658c37f6eSKOSAKI Motohiro 	 */
220702695175SJohannes Weiner 	anon_prio = swappiness;
220875b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
220958c37f6eSKOSAKI Motohiro 
221058c37f6eSKOSAKI Motohiro 	/*
22114f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22124f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22134f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22144f98a2feSRik van Riel 	 *
22154f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22164f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22174f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22184f98a2feSRik van Riel 	 *
22194f98a2feSRik van Riel 	 * anon in [0], file in [1]
22204f98a2feSRik van Riel 	 */
22212ab051e1SJerome Marchand 
222223047a96SJohannes Weiner 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
222323047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
222423047a96SJohannes Weiner 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
222523047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
22262ab051e1SJerome Marchand 
2227599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
222858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22296e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22306e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22314f98a2feSRik van Riel 	}
22324f98a2feSRik van Riel 
22336e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22346e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22356e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22364f98a2feSRik van Riel 	}
22374f98a2feSRik van Riel 
22384f98a2feSRik van Riel 	/*
223900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
224000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
224100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22424f98a2feSRik van Riel 	 */
2243fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22446e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22454f98a2feSRik van Riel 
2246fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22476e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2248599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22494f98a2feSRik van Riel 
225076a33fc3SShaohua Li 	fraction[0] = ap;
225176a33fc3SShaohua Li 	fraction[1] = fp;
225276a33fc3SShaohua Li 	denominator = ap + fp + 1;
225376a33fc3SShaohua Li out:
22546f04f48dSSuleiman Souhlal 	some_scanned = false;
22556f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
22566f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
22576b4f7799SJohannes Weiner 		*lru_pages = 0;
22584111304dSHugh Dickins 		for_each_evictable_lru(lru) {
22594111304dSHugh Dickins 			int file = is_file_lru(lru);
2260d778df51SJohannes Weiner 			unsigned long size;
226176a33fc3SShaohua Li 			unsigned long scan;
226276a33fc3SShaohua Li 
226323047a96SJohannes Weiner 			size = lruvec_lru_size(lruvec, lru);
2264d778df51SJohannes Weiner 			scan = size >> sc->priority;
22659a265114SJohannes Weiner 
22666f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2267d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
22689a265114SJohannes Weiner 
22699a265114SJohannes Weiner 			switch (scan_balance) {
22709a265114SJohannes Weiner 			case SCAN_EQUAL:
22719a265114SJohannes Weiner 				/* Scan lists relative to size */
22729a265114SJohannes Weiner 				break;
22739a265114SJohannes Weiner 			case SCAN_FRACT:
22749a265114SJohannes Weiner 				/*
22759a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
22769a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
22779a265114SJohannes Weiner 				 */
22786f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
22796f04f48dSSuleiman Souhlal 							denominator);
22809a265114SJohannes Weiner 				break;
22819a265114SJohannes Weiner 			case SCAN_FILE:
22829a265114SJohannes Weiner 			case SCAN_ANON:
22839a265114SJohannes Weiner 				/* Scan one type exclusively */
22846b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
22856b4f7799SJohannes Weiner 					size = 0;
22869a265114SJohannes Weiner 					scan = 0;
22876b4f7799SJohannes Weiner 				}
22889a265114SJohannes Weiner 				break;
22899a265114SJohannes Weiner 			default:
22909a265114SJohannes Weiner 				/* Look ma, no brain */
22919a265114SJohannes Weiner 				BUG();
22929a265114SJohannes Weiner 			}
22936b4f7799SJohannes Weiner 
22946b4f7799SJohannes Weiner 			*lru_pages += size;
22954111304dSHugh Dickins 			nr[lru] = scan;
22966b4f7799SJohannes Weiner 
22976f04f48dSSuleiman Souhlal 			/*
22986f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
22996f04f48dSSuleiman Souhlal 			 * if we found something to scan.
23006f04f48dSSuleiman Souhlal 			 */
23016f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
23026f04f48dSSuleiman Souhlal 		}
230376a33fc3SShaohua Li 	}
23046e08a369SWu Fengguang }
23054f98a2feSRik van Riel 
23069b4f98cdSJohannes Weiner /*
2307a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23089b4f98cdSJohannes Weiner  */
2309a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23106b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23119b4f98cdSJohannes Weiner {
2312ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23139b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2314e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23159b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23169b4f98cdSJohannes Weiner 	enum lru_list lru;
23179b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23189b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23199b4f98cdSJohannes Weiner 	struct blk_plug plug;
23201a501907SMel Gorman 	bool scan_adjusted;
23219b4f98cdSJohannes Weiner 
232233377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23239b4f98cdSJohannes Weiner 
2324e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2325e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2326e82e0561SMel Gorman 
23271a501907SMel Gorman 	/*
23281a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23291a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23301a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23311a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23321a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23331a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23341a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23351a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23361a501907SMel Gorman 	 * dropped to zero at the first pass.
23371a501907SMel Gorman 	 */
23381a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23391a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23401a501907SMel Gorman 
23419b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23429b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23439b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2344e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2345e82e0561SMel Gorman 		unsigned long nr_scanned;
2346e82e0561SMel Gorman 
23479b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23489b4f98cdSJohannes Weiner 			if (nr[lru]) {
23499b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23509b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23519b4f98cdSJohannes Weiner 
23529b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23539b4f98cdSJohannes Weiner 							    lruvec, sc);
23549b4f98cdSJohannes Weiner 			}
23559b4f98cdSJohannes Weiner 		}
2356e82e0561SMel Gorman 
2357e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2358e82e0561SMel Gorman 			continue;
2359e82e0561SMel Gorman 
23609b4f98cdSJohannes Weiner 		/*
2361e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23621a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2363e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2364e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2365e82e0561SMel Gorman 		 * proportional to the original scan target.
2366e82e0561SMel Gorman 		 */
2367e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2368e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2369e82e0561SMel Gorman 
23701a501907SMel Gorman 		/*
23711a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23721a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23731a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23741a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23751a501907SMel Gorman 		 */
23761a501907SMel Gorman 		if (!nr_file || !nr_anon)
23771a501907SMel Gorman 			break;
23781a501907SMel Gorman 
2379e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2380e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2381e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2382e82e0561SMel Gorman 			lru = LRU_BASE;
2383e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2384e82e0561SMel Gorman 		} else {
2385e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2386e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2387e82e0561SMel Gorman 			lru = LRU_FILE;
2388e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2389e82e0561SMel Gorman 		}
2390e82e0561SMel Gorman 
2391e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2392e82e0561SMel Gorman 		nr[lru] = 0;
2393e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2394e82e0561SMel Gorman 
2395e82e0561SMel Gorman 		/*
2396e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2397e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2398e82e0561SMel Gorman 		 */
2399e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2400e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2401e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2402e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2403e82e0561SMel Gorman 
2404e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2405e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2406e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2407e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2408e82e0561SMel Gorman 
2409e82e0561SMel Gorman 		scan_adjusted = true;
24109b4f98cdSJohannes Weiner 	}
24119b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24129b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24139b4f98cdSJohannes Weiner 
24149b4f98cdSJohannes Weiner 	/*
24159b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24169b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24179b4f98cdSJohannes Weiner 	 */
2418f8d1a311SMel Gorman 	if (inactive_list_is_low(lruvec, false, sc))
24199b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24209b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24219b4f98cdSJohannes Weiner }
24229b4f98cdSJohannes Weiner 
242323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24249e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
242523b9da55SMel Gorman {
2426d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
242723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24289e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
242923b9da55SMel Gorman 		return true;
243023b9da55SMel Gorman 
243123b9da55SMel Gorman 	return false;
243223b9da55SMel Gorman }
243323b9da55SMel Gorman 
24344f98a2feSRik van Riel /*
243523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
243623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
243723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
243823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
243923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24403e7d3449SMel Gorman  */
2441a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24423e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24433e7d3449SMel Gorman 					unsigned long nr_scanned,
24443e7d3449SMel Gorman 					struct scan_control *sc)
24453e7d3449SMel Gorman {
24463e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24473e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2448a9dd0a83SMel Gorman 	int z;
24493e7d3449SMel Gorman 
24503e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24519e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24523e7d3449SMel Gorman 		return false;
24533e7d3449SMel Gorman 
24542876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
24552876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
24563e7d3449SMel Gorman 		/*
24572876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
24582876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24592876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
24602876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
24613e7d3449SMel Gorman 		 */
24623e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24633e7d3449SMel Gorman 			return false;
24642876592fSMel Gorman 	} else {
24652876592fSMel Gorman 		/*
24662876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
24672876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24682876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24692876592fSMel Gorman 		 * pages that were scanned. This will return to the
24702876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24712876592fSMel Gorman 		 * the resulting allocation attempt fails
24722876592fSMel Gorman 		 */
24732876592fSMel Gorman 		if (!nr_reclaimed)
24742876592fSMel Gorman 			return false;
24752876592fSMel Gorman 	}
24763e7d3449SMel Gorman 
24773e7d3449SMel Gorman 	/*
24783e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24793e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24803e7d3449SMel Gorman 	 */
24819861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2482a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2483ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2484a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
24853e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24863e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24873e7d3449SMel Gorman 		return true;
24883e7d3449SMel Gorman 
24893e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2490a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2491a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
24926aa303deSMel Gorman 		if (!managed_zone(zone))
2493a9dd0a83SMel Gorman 			continue;
2494a9dd0a83SMel Gorman 
2495a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2496cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
24973e7d3449SMel Gorman 		case COMPACT_CONTINUE:
24983e7d3449SMel Gorman 			return false;
24993e7d3449SMel Gorman 		default:
2500a9dd0a83SMel Gorman 			/* check next zone */
2501a9dd0a83SMel Gorman 			;
25023e7d3449SMel Gorman 		}
25033e7d3449SMel Gorman 	}
2504a9dd0a83SMel Gorman 	return true;
2505a9dd0a83SMel Gorman }
25063e7d3449SMel Gorman 
2507970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2508f16015fbSJohannes Weiner {
2509cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25109b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25112344d7e4SJohannes Weiner 	bool reclaimable = false;
25129b4f98cdSJohannes Weiner 
25139b4f98cdSJohannes Weiner 	do {
25145660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25155660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2516ef8f2327SMel Gorman 			.pgdat = pgdat,
25179e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25185660048cSJohannes Weiner 		};
2519a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2520694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25215660048cSJohannes Weiner 
25229b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25239b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25249b4f98cdSJohannes Weiner 
2525694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2526694fbc0fSAndrew Morton 		do {
25276b4f7799SJohannes Weiner 			unsigned long lru_pages;
25288e8ae645SJohannes Weiner 			unsigned long reclaimed;
2529cb731d6cSVladimir Davydov 			unsigned long scanned;
25309b4f98cdSJohannes Weiner 
2531241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2532241994edSJohannes Weiner 				if (!sc->may_thrash)
2533241994edSJohannes Weiner 					continue;
2534241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2535241994edSJohannes Weiner 			}
2536241994edSJohannes Weiner 
25378e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2538cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
25395660048cSJohannes Weiner 
2540a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2541a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2542f9be23d6SKonstantin Khlebnikov 
2543b5afba29SVladimir Davydov 			if (memcg)
2544a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
2545cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2546cb731d6cSVladimir Davydov 					    lru_pages);
2547cb731d6cSVladimir Davydov 
25488e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25498e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25508e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25518e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25528e8ae645SJohannes Weiner 
25535660048cSJohannes Weiner 			/*
2554a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2555a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2556a9dd0a83SMel Gorman 			 * node.
2557a394cb8eSMichal Hocko 			 *
2558a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2559a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2560a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2561a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25625660048cSJohannes Weiner 			 */
2563a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2564a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25655660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25665660048cSJohannes Weiner 				break;
25675660048cSJohannes Weiner 			}
2568241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
256970ddf637SAnton Vorontsov 
25706b4f7799SJohannes Weiner 		/*
25716b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
25726b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
25736b4f7799SJohannes Weiner 		 */
2574b2e18757SMel Gorman 		if (global_reclaim(sc))
2575a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25766b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
2577a9dd0a83SMel Gorman 				    node_lru_pages);
25786b4f7799SJohannes Weiner 
25796b4f7799SJohannes Weiner 		if (reclaim_state) {
2580cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25816b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25826b4f7799SJohannes Weiner 		}
25836b4f7799SJohannes Weiner 
25848e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25858e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
258670ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
258770ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
258870ddf637SAnton Vorontsov 
25892344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
25902344d7e4SJohannes Weiner 			reclaimable = true;
25912344d7e4SJohannes Weiner 
2592a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
25939b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
25942344d7e4SJohannes Weiner 
25952344d7e4SJohannes Weiner 	return reclaimable;
2596f16015fbSJohannes Weiner }
2597f16015fbSJohannes Weiner 
259853853e2dSVlastimil Babka /*
2599fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2600fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2601fdd4c614SVlastimil Babka  * should reclaim first.
260253853e2dSVlastimil Babka  */
26034f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2604fe4b1b24SMel Gorman {
260531483b6aSMel Gorman 	unsigned long watermark;
2606fdd4c614SVlastimil Babka 	enum compact_result suitable;
2607fe4b1b24SMel Gorman 
2608fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2609fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2610fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2611fdd4c614SVlastimil Babka 		return true;
2612fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2613fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2614fe4b1b24SMel Gorman 		return false;
2615fe4b1b24SMel Gorman 
2616fdd4c614SVlastimil Babka 	/*
2617fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2618fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2619fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2620fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2621fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2622fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2623fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2624fdd4c614SVlastimil Babka 	 */
2625fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2626fdd4c614SVlastimil Babka 
2627fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2628fe4b1b24SMel Gorman }
2629fe4b1b24SMel Gorman 
26301da177e4SLinus Torvalds /*
26311da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
26321da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
26331da177e4SLinus Torvalds  * request.
26341da177e4SLinus Torvalds  *
26351da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
26361da177e4SLinus Torvalds  * scan then give up on it.
26371da177e4SLinus Torvalds  */
26380a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
26391da177e4SLinus Torvalds {
2640dd1a239fSMel Gorman 	struct zoneref *z;
264154a6eb5cSMel Gorman 	struct zone *zone;
26420608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26430608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2644619d0d76SWeijie Yang 	gfp_t orig_mask;
264579dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
26461cfb419bSKAMEZAWA Hiroyuki 
2647cc715d99SMel Gorman 	/*
2648cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2649cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2650cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2651cc715d99SMel Gorman 	 */
2652619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2653b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2654cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
26554f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2656b2e18757SMel Gorman 	}
2657cc715d99SMel Gorman 
2658d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2659b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2660b2e18757SMel Gorman 		/*
26611cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26621cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26631cfb419bSKAMEZAWA Hiroyuki 		 */
266489b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2665344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2666344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26671da177e4SLinus Torvalds 				continue;
266865ec02cbSVladimir Davydov 
26696e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
2670599d0c95SMel Gorman 			    !pgdat_reclaimable(zone->zone_pgdat))
26711da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
26720b06496aSJohannes Weiner 
2673e0887c19SRik van Riel 			/*
2674e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2675e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2676e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2677e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2678e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2679c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2680c7cfa37bSCopot Alexandru 			 * page allocations.
2681e0887c19SRik van Riel 			 */
26820b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
26830b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
26844f588331SMel Gorman 			    compaction_ready(zone, sc)) {
26850b06496aSJohannes Weiner 				sc->compaction_ready = true;
2686e0887c19SRik van Riel 				continue;
2687e0887c19SRik van Riel 			}
26880b06496aSJohannes Weiner 
26890608f43dSAndrew Morton 			/*
269079dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
269179dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
269279dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
269379dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
269479dafcdcSMel Gorman 			 */
269579dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
269679dafcdcSMel Gorman 				continue;
269779dafcdcSMel Gorman 
269879dafcdcSMel Gorman 			/*
26990608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27000608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27010608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27020608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27030608f43dSAndrew Morton 			 */
27040608f43dSAndrew Morton 			nr_soft_scanned = 0;
2705ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27060608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27070608f43dSAndrew Morton 						&nr_soft_scanned);
27080608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27090608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2710ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2711ac34a1a3SKAMEZAWA Hiroyuki 		}
2712d149e3b2SYing Han 
271379dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
271479dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
271579dafcdcSMel Gorman 			continue;
271679dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2717970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27181da177e4SLinus Torvalds 	}
2719e0c23279SMel Gorman 
272065ec02cbSVladimir Davydov 	/*
2721619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2722619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2723619d0d76SWeijie Yang 	 */
2724619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27251da177e4SLinus Torvalds }
27261da177e4SLinus Torvalds 
27271da177e4SLinus Torvalds /*
27281da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
27291da177e4SLinus Torvalds  *
27301da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
27311da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
27321da177e4SLinus Torvalds  *
27331da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
27341da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
27355b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
27365b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
27375b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
27385b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2739a41f24eaSNishanth Aravamudan  *
2740a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2741a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
27421da177e4SLinus Torvalds  */
2743dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
27443115cd91SVladimir Davydov 					  struct scan_control *sc)
27451da177e4SLinus Torvalds {
2746241994edSJohannes Weiner 	int initial_priority = sc->priority;
274769e05944SAndrew Morton 	unsigned long total_scanned = 0;
274822fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
2749241994edSJohannes Weiner retry:
2750873b4771SKeika Kobayashi 	delayacct_freepages_start();
2751873b4771SKeika Kobayashi 
275289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
27537cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
27541da177e4SLinus Torvalds 
27559e3b2f8cSKonstantin Khlebnikov 	do {
275670ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
275770ddf637SAnton Vorontsov 				sc->priority);
275866e1707bSBalbir Singh 		sc->nr_scanned = 0;
27590a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2760e0c23279SMel Gorman 
276166e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2762bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
27630b06496aSJohannes Weiner 			break;
27640b06496aSJohannes Weiner 
27650b06496aSJohannes Weiner 		if (sc->compaction_ready)
27660b06496aSJohannes Weiner 			break;
27671da177e4SLinus Torvalds 
27681da177e4SLinus Torvalds 		/*
27690e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27700e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27710e50ce3bSMinchan Kim 		 */
27720e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27730e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27740e50ce3bSMinchan Kim 
27750e50ce3bSMinchan Kim 		/*
27761da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
27771da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
27781da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
27791da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
27801da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
27811da177e4SLinus Torvalds 		 */
278222fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
278322fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
27840e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
27850e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
278666e1707bSBalbir Singh 			sc->may_writepage = 1;
27871da177e4SLinus Torvalds 		}
27880b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2789bb21c7ceSKOSAKI Motohiro 
2790873b4771SKeika Kobayashi 	delayacct_freepages_end();
2791873b4771SKeika Kobayashi 
2792bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2793bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2794bb21c7ceSKOSAKI Motohiro 
27950cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
27960b06496aSJohannes Weiner 	if (sc->compaction_ready)
27977335084dSMel Gorman 		return 1;
27987335084dSMel Gorman 
2799241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2800241994edSJohannes Weiner 	if (!sc->may_thrash) {
2801241994edSJohannes Weiner 		sc->priority = initial_priority;
2802241994edSJohannes Weiner 		sc->may_thrash = 1;
2803241994edSJohannes Weiner 		goto retry;
2804241994edSJohannes Weiner 	}
2805241994edSJohannes Weiner 
2806bb21c7ceSKOSAKI Motohiro 	return 0;
28071da177e4SLinus Torvalds }
28081da177e4SLinus Torvalds 
28095515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
28105515061dSMel Gorman {
28115515061dSMel Gorman 	struct zone *zone;
28125515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
28135515061dSMel Gorman 	unsigned long free_pages = 0;
28145515061dSMel Gorman 	int i;
28155515061dSMel Gorman 	bool wmark_ok;
28165515061dSMel Gorman 
28175515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
28185515061dSMel Gorman 		zone = &pgdat->node_zones[i];
28196aa303deSMel Gorman 		if (!managed_zone(zone) ||
2820599d0c95SMel Gorman 		    pgdat_reclaimable_pages(pgdat) == 0)
2821675becceSMel Gorman 			continue;
2822675becceSMel Gorman 
28235515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
28245515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
28255515061dSMel Gorman 	}
28265515061dSMel Gorman 
2827675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2828675becceSMel Gorman 	if (!pfmemalloc_reserve)
2829675becceSMel Gorman 		return true;
2830675becceSMel Gorman 
28315515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
28325515061dSMel Gorman 
28335515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
28345515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
283538087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
28365515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
28375515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
28385515061dSMel Gorman 	}
28395515061dSMel Gorman 
28405515061dSMel Gorman 	return wmark_ok;
28415515061dSMel Gorman }
28425515061dSMel Gorman 
28435515061dSMel Gorman /*
28445515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
28455515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
28465515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
284750694c28SMel Gorman  * when the low watermark is reached.
284850694c28SMel Gorman  *
284950694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
285050694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
28515515061dSMel Gorman  */
285250694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
28535515061dSMel Gorman 					nodemask_t *nodemask)
28545515061dSMel Gorman {
2855675becceSMel Gorman 	struct zoneref *z;
28565515061dSMel Gorman 	struct zone *zone;
2857675becceSMel Gorman 	pg_data_t *pgdat = NULL;
28585515061dSMel Gorman 
28595515061dSMel Gorman 	/*
28605515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
28615515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
28625515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
28635515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
28645515061dSMel Gorman 	 * processes to block on log_wait_commit().
28655515061dSMel Gorman 	 */
28665515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
286750694c28SMel Gorman 		goto out;
286850694c28SMel Gorman 
286950694c28SMel Gorman 	/*
287050694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
287150694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
287250694c28SMel Gorman 	 */
287350694c28SMel Gorman 	if (fatal_signal_pending(current))
287450694c28SMel Gorman 		goto out;
28755515061dSMel Gorman 
2876675becceSMel Gorman 	/*
2877675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2878675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2879675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2880675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2881675becceSMel Gorman 	 *
2882675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2883675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2884675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2885675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2886675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2887675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2888675becceSMel Gorman 	 * should make reasonable progress.
2889675becceSMel Gorman 	 */
2890675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
289117636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2892675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2893675becceSMel Gorman 			continue;
2894675becceSMel Gorman 
2895675becceSMel Gorman 		/* Throttle based on the first usable node */
28965515061dSMel Gorman 		pgdat = zone->zone_pgdat;
28975515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
289850694c28SMel Gorman 			goto out;
2899675becceSMel Gorman 		break;
2900675becceSMel Gorman 	}
2901675becceSMel Gorman 
2902675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2903675becceSMel Gorman 	if (!pgdat)
2904675becceSMel Gorman 		goto out;
29055515061dSMel Gorman 
290668243e76SMel Gorman 	/* Account for the throttling */
290768243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
290868243e76SMel Gorman 
29095515061dSMel Gorman 	/*
29105515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
29115515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
29125515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
29135515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
29145515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
29155515061dSMel Gorman 	 * second before continuing.
29165515061dSMel Gorman 	 */
29175515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
29185515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
29195515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
292050694c28SMel Gorman 
292150694c28SMel Gorman 		goto check_pending;
29225515061dSMel Gorman 	}
29235515061dSMel Gorman 
29245515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
29255515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
29265515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
292750694c28SMel Gorman 
292850694c28SMel Gorman check_pending:
292950694c28SMel Gorman 	if (fatal_signal_pending(current))
293050694c28SMel Gorman 		return true;
293150694c28SMel Gorman 
293250694c28SMel Gorman out:
293350694c28SMel Gorman 	return false;
29345515061dSMel Gorman }
29355515061dSMel Gorman 
2936dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2937327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
293866e1707bSBalbir Singh {
293933906bc5SMel Gorman 	unsigned long nr_reclaimed;
294066e1707bSBalbir Singh 	struct scan_control sc = {
294122fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2942ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2943b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2944ee814fe2SJohannes Weiner 		.order = order,
2945ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2946ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2947ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2948a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29492e2e4259SKOSAKI Motohiro 		.may_swap = 1,
295066e1707bSBalbir Singh 	};
295166e1707bSBalbir Singh 
29525515061dSMel Gorman 	/*
295350694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
295450694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
295550694c28SMel Gorman 	 * point.
29565515061dSMel Gorman 	 */
295750694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
29585515061dSMel Gorman 		return 1;
29595515061dSMel Gorman 
296033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
296133906bc5SMel Gorman 				sc.may_writepage,
2962e5146b12SMel Gorman 				gfp_mask,
2963e5146b12SMel Gorman 				sc.reclaim_idx);
296433906bc5SMel Gorman 
29653115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
296633906bc5SMel Gorman 
296733906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
296833906bc5SMel Gorman 
296933906bc5SMel Gorman 	return nr_reclaimed;
297066e1707bSBalbir Singh }
297166e1707bSBalbir Singh 
2972c255a458SAndrew Morton #ifdef CONFIG_MEMCG
297366e1707bSBalbir Singh 
2974a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
29754e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
2976ef8f2327SMel Gorman 						pg_data_t *pgdat,
29770ae5e89cSYing Han 						unsigned long *nr_scanned)
29784e416953SBalbir Singh {
29794e416953SBalbir Singh 	struct scan_control sc = {
2980b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2981ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
29824e416953SBalbir Singh 		.may_writepage = !laptop_mode,
29834e416953SBalbir Singh 		.may_unmap = 1,
2984b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
29854e416953SBalbir Singh 		.may_swap = !noswap,
29864e416953SBalbir Singh 	};
29876b4f7799SJohannes Weiner 	unsigned long lru_pages;
29880ae5e89cSYing Han 
29894e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
29904e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2991bdce6d9eSKOSAKI Motohiro 
29929e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2993bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2994e5146b12SMel Gorman 						      sc.gfp_mask,
2995e5146b12SMel Gorman 						      sc.reclaim_idx);
2996bdce6d9eSKOSAKI Motohiro 
29974e416953SBalbir Singh 	/*
29984e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
29994e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3000a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30014e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
30024e416953SBalbir Singh 	 * the priority and make it zero.
30034e416953SBalbir Singh 	 */
3004ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3005bdce6d9eSKOSAKI Motohiro 
3006bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3007bdce6d9eSKOSAKI Motohiro 
30080ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
30094e416953SBalbir Singh 	return sc.nr_reclaimed;
30104e416953SBalbir Singh }
30114e416953SBalbir Singh 
301272835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3013b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
30148c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3015b70a2a21SJohannes Weiner 					   bool may_swap)
301666e1707bSBalbir Singh {
30174e416953SBalbir Singh 	struct zonelist *zonelist;
3018bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3019889976dbSYing Han 	int nid;
302066e1707bSBalbir Singh 	struct scan_control sc = {
3021b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3022ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3023ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3024b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3025ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3026ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
302766e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3028a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3029b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3030a09ed5e0SYing Han 	};
303166e1707bSBalbir Singh 
3032889976dbSYing Han 	/*
3033889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3034889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3035889976dbSYing Han 	 * scan does not need to be the current node.
3036889976dbSYing Han 	 */
303772835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3038889976dbSYing Han 
3039c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3040bdce6d9eSKOSAKI Motohiro 
3041bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3042bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3043e5146b12SMel Gorman 					    sc.gfp_mask,
3044e5146b12SMel Gorman 					    sc.reclaim_idx);
3045bdce6d9eSKOSAKI Motohiro 
3046*89a28483SJohannes Weiner 	current->flags |= PF_MEMALLOC;
30473115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3048*89a28483SJohannes Weiner 	current->flags &= ~PF_MEMALLOC;
3049bdce6d9eSKOSAKI Motohiro 
3050bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3051bdce6d9eSKOSAKI Motohiro 
3052bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
305366e1707bSBalbir Singh }
305466e1707bSBalbir Singh #endif
305566e1707bSBalbir Singh 
30561d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3057ef8f2327SMel Gorman 				struct scan_control *sc)
3058f16015fbSJohannes Weiner {
3059b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3060b95a2f2dSJohannes Weiner 
3061b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3062b95a2f2dSJohannes Weiner 		return;
3063b95a2f2dSJohannes Weiner 
3064b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3065b95a2f2dSJohannes Weiner 	do {
3066ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3067f16015fbSJohannes Weiner 
3068f8d1a311SMel Gorman 		if (inactive_list_is_low(lruvec, false, sc))
30691a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30709e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3071b95a2f2dSJohannes Weiner 
3072b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3073b95a2f2dSJohannes Weiner 	} while (memcg);
3074f16015fbSJohannes Weiner }
3075f16015fbSJohannes Weiner 
307631483b6aSMel Gorman static bool zone_balanced(struct zone *zone, int order, int classzone_idx)
307760cefed4SJohannes Weiner {
307831483b6aSMel Gorman 	unsigned long mark = high_wmark_pages(zone);
307960cefed4SJohannes Weiner 
30806256c6b4SMel Gorman 	if (!zone_watermark_ok_safe(zone, order, mark, classzone_idx))
30816256c6b4SMel Gorman 		return false;
30826256c6b4SMel Gorman 
30836256c6b4SMel Gorman 	/*
30846256c6b4SMel Gorman 	 * If any eligible zone is balanced then the node is not considered
30856256c6b4SMel Gorman 	 * to be congested or dirty
30866256c6b4SMel Gorman 	 */
30876256c6b4SMel Gorman 	clear_bit(PGDAT_CONGESTED, &zone->zone_pgdat->flags);
30886256c6b4SMel Gorman 	clear_bit(PGDAT_DIRTY, &zone->zone_pgdat->flags);
30896256c6b4SMel Gorman 
30906256c6b4SMel Gorman 	return true;
309160cefed4SJohannes Weiner }
309260cefed4SJohannes Weiner 
30931741c877SMel Gorman /*
30945515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30955515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30965515061dSMel Gorman  *
30975515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30985515061dSMel Gorman  */
3099d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3100f50de2d3SMel Gorman {
31011d82de61SMel Gorman 	int i;
31021d82de61SMel Gorman 
31035515061dSMel Gorman 	/*
31049e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
31059e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
31069e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
31079e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
31089e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
31099e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
31109e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
31119e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
31129e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
31139e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
31149e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
31155515061dSMel Gorman 	 */
31169e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
31179e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3118f50de2d3SMel Gorman 
31191d82de61SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
31201d82de61SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
31211d82de61SMel Gorman 
31226aa303deSMel Gorman 		if (!managed_zone(zone))
31231d82de61SMel Gorman 			continue;
31241d82de61SMel Gorman 
312538087d9bSMel Gorman 		if (!zone_balanced(zone, order, classzone_idx))
312638087d9bSMel Gorman 			return false;
31271d82de61SMel Gorman 	}
31281d82de61SMel Gorman 
312938087d9bSMel Gorman 	return true;
3130f50de2d3SMel Gorman }
3131f50de2d3SMel Gorman 
31321da177e4SLinus Torvalds /*
31331d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
31341d82de61SMel Gorman  * zone that is currently unbalanced.
3135b8e83b94SMel Gorman  *
3136b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3137283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3138283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
313975485363SMel Gorman  */
31401d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3141accf6242SVlastimil Babka 			       struct scan_control *sc)
314275485363SMel Gorman {
31431d82de61SMel Gorman 	struct zone *zone;
31441d82de61SMel Gorman 	int z;
314575485363SMel Gorman 
31461d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
31471d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3148970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
31491d82de61SMel Gorman 		zone = pgdat->node_zones + z;
31506aa303deSMel Gorman 		if (!managed_zone(zone))
31511d82de61SMel Gorman 			continue;
31527c954f6dSMel Gorman 
31531d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
31547c954f6dSMel Gorman 	}
31557c954f6dSMel Gorman 
31561d82de61SMel Gorman 	/*
31571d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
31581d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
31591d82de61SMel Gorman 	 */
3160970a39a3SMel Gorman 	shrink_node(pgdat, sc);
31611d82de61SMel Gorman 
31621d82de61SMel Gorman 	/*
31631d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
31641d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
31651d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
31661d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
31671d82de61SMel Gorman 	 * can direct reclaim/compact.
31681d82de61SMel Gorman 	 */
31699861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
31701d82de61SMel Gorman 		sc->order = 0;
31711d82de61SMel Gorman 
3172b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
317375485363SMel Gorman }
317475485363SMel Gorman 
317575485363SMel Gorman /*
31761d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
31771d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
31781d82de61SMel Gorman  * balanced.
31791da177e4SLinus Torvalds  *
31801d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
31811da177e4SLinus Torvalds  *
31821da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
318341858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
31841d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
31851d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
31861d82de61SMel Gorman  * balanced.
31871da177e4SLinus Torvalds  */
3188accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
31891da177e4SLinus Torvalds {
31901da177e4SLinus Torvalds 	int i;
31910608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31920608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
31931d82de61SMel Gorman 	struct zone *zone;
3194179e9639SAndrew Morton 	struct scan_control sc = {
3195179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3196ee814fe2SJohannes Weiner 		.order = order,
3197b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3198ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3199a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32002e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3201179e9639SAndrew Morton 	};
3202f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
32031da177e4SLinus Torvalds 
32049e3b2f8cSKonstantin Khlebnikov 	do {
3205b8e83b94SMel Gorman 		bool raise_priority = true;
3206b8e83b94SMel Gorman 
3207b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
320884c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
32091da177e4SLinus Torvalds 
321086c79f6bSMel Gorman 		/*
321184c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
321284c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
321384c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
321484c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
321584c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
321684c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
321784c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
321884c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
321986c79f6bSMel Gorman 		 */
322086c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
322186c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
322286c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
32236aa303deSMel Gorman 				if (!managed_zone(zone))
322486c79f6bSMel Gorman 					continue;
322586c79f6bSMel Gorman 
3226970a39a3SMel Gorman 				sc.reclaim_idx = i;
322786c79f6bSMel Gorman 				break;
322886c79f6bSMel Gorman 			}
322986c79f6bSMel Gorman 		}
323086c79f6bSMel Gorman 
323186c79f6bSMel Gorman 		/*
323286c79f6bSMel Gorman 		 * Only reclaim if there are no eligible zones. Check from
323386c79f6bSMel Gorman 		 * high to low zone as allocations prefer higher zones.
323486c79f6bSMel Gorman 		 * Scanning from low to high zone would allow congestion to be
323586c79f6bSMel Gorman 		 * cleared during a very small window when a small low
323686c79f6bSMel Gorman 		 * zone was balanced even under extreme pressure when the
323784c7a777SMel Gorman 		 * overall node may be congested. Note that sc.reclaim_idx
323884c7a777SMel Gorman 		 * is not used as buffer_heads_over_limit may have adjusted
323984c7a777SMel Gorman 		 * it.
324086c79f6bSMel Gorman 		 */
324184c7a777SMel Gorman 		for (i = classzone_idx; i >= 0; i--) {
32421d82de61SMel Gorman 			zone = pgdat->node_zones + i;
32436aa303deSMel Gorman 			if (!managed_zone(zone))
32441da177e4SLinus Torvalds 				continue;
32451da177e4SLinus Torvalds 
324684c7a777SMel Gorman 			if (zone_balanced(zone, sc.order, classzone_idx))
32471da177e4SLinus Torvalds 				goto out;
324886c79f6bSMel Gorman 		}
3249e1dbeda6SAndrew Morton 
32501da177e4SLinus Torvalds 		/*
32511d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
32521d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
32531d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
32541d82de61SMel Gorman 		 * about consistent aging.
32551d82de61SMel Gorman 		 */
3256ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
32571d82de61SMel Gorman 
32581d82de61SMel Gorman 		/*
3259b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3260b7ea3c41SMel Gorman 		 * even in laptop mode.
3261b7ea3c41SMel Gorman 		 */
32621d82de61SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2 || !pgdat_reclaimable(pgdat))
3263b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3264b7ea3c41SMel Gorman 
32651d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
32661da177e4SLinus Torvalds 		sc.nr_scanned = 0;
32670608f43dSAndrew Morton 		nr_soft_scanned = 0;
3268ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
32691d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
32700608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
32710608f43dSAndrew Morton 
327232a4330dSRik van Riel 		/*
32731d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
32741d82de61SMel Gorman 		 * enough pages are already being scanned that that high
32751d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
327632a4330dSRik van Riel 		 */
3277970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3278b8e83b94SMel Gorman 			raise_priority = false;
3279d7868daeSMel Gorman 
32805515061dSMel Gorman 		/*
32815515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32825515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32835515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32845515061dSMel Gorman 		 */
32855515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
32865515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3287cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32885515061dSMel Gorman 
3289b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3290b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3291b8e83b94SMel Gorman 			break;
3292b8e83b94SMel Gorman 
3293b8e83b94SMel Gorman 		/*
3294b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3295b8e83b94SMel Gorman 		 * progress in reclaiming pages
3296b8e83b94SMel Gorman 		 */
3297b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3298b8e83b94SMel Gorman 			sc.priority--;
32991d82de61SMel Gorman 	} while (sc.priority >= 1);
33001da177e4SLinus Torvalds 
3301b8e83b94SMel Gorman out:
33020abdee2bSMel Gorman 	/*
33031d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
33041d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
33051d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
33061d82de61SMel Gorman 	 * remain at the higher level.
33070abdee2bSMel Gorman 	 */
33081d82de61SMel Gorman 	return sc.order;
33091da177e4SLinus Torvalds }
33101da177e4SLinus Torvalds 
331138087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
331238087d9bSMel Gorman 				unsigned int classzone_idx)
3313f0bc0a60SKOSAKI Motohiro {
3314f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3315f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3316f0bc0a60SKOSAKI Motohiro 
3317f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3318f0bc0a60SKOSAKI Motohiro 		return;
3319f0bc0a60SKOSAKI Motohiro 
3320f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3321f0bc0a60SKOSAKI Motohiro 
3322f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3323d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3324fd901c95SVlastimil Babka 		/*
3325fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3326fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3327fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3328fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3329fd901c95SVlastimil Babka 		 */
3330fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3331fd901c95SVlastimil Babka 
3332fd901c95SVlastimil Babka 		/*
3333fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3334fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3335fd901c95SVlastimil Babka 		 */
333638087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3337fd901c95SVlastimil Babka 
3338f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
333938087d9bSMel Gorman 
334038087d9bSMel Gorman 		/*
334138087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
334238087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
334338087d9bSMel Gorman 		 * the previous request that slept prematurely.
334438087d9bSMel Gorman 		 */
334538087d9bSMel Gorman 		if (remaining) {
334638087d9bSMel Gorman 			pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
334738087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
334838087d9bSMel Gorman 		}
334938087d9bSMel Gorman 
3350f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3351f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3352f0bc0a60SKOSAKI Motohiro 	}
3353f0bc0a60SKOSAKI Motohiro 
3354f0bc0a60SKOSAKI Motohiro 	/*
3355f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3356f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3357f0bc0a60SKOSAKI Motohiro 	 */
3358d9f21d42SMel Gorman 	if (!remaining &&
3359d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3360f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3361f0bc0a60SKOSAKI Motohiro 
3362f0bc0a60SKOSAKI Motohiro 		/*
3363f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3364f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3365f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3366f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3367f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3368f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3369f0bc0a60SKOSAKI Motohiro 		 */
3370f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33711c7e7f6cSAaditya Kumar 
33721c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3373f0bc0a60SKOSAKI Motohiro 			schedule();
33741c7e7f6cSAaditya Kumar 
3375f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3376f0bc0a60SKOSAKI Motohiro 	} else {
3377f0bc0a60SKOSAKI Motohiro 		if (remaining)
3378f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3379f0bc0a60SKOSAKI Motohiro 		else
3380f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3381f0bc0a60SKOSAKI Motohiro 	}
3382f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3383f0bc0a60SKOSAKI Motohiro }
3384f0bc0a60SKOSAKI Motohiro 
33851da177e4SLinus Torvalds /*
33861da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33871da177e4SLinus Torvalds  * from the init process.
33881da177e4SLinus Torvalds  *
33891da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33901da177e4SLinus Torvalds  * free memory available even if there is no other activity
33911da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33921da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33931da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33941da177e4SLinus Torvalds  *
33951da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33961da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33971da177e4SLinus Torvalds  */
33981da177e4SLinus Torvalds static int kswapd(void *p)
33991da177e4SLinus Torvalds {
340038087d9bSMel Gorman 	unsigned int alloc_order, reclaim_order, classzone_idx;
34011da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
34021da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3403f0bc0a60SKOSAKI Motohiro 
34041da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
34051da177e4SLinus Torvalds 		.reclaimed_slab = 0,
34061da177e4SLinus Torvalds 	};
3407a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
34081da177e4SLinus Torvalds 
3409cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3410cf40bd16SNick Piggin 
3411174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3412c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
34131da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
34141da177e4SLinus Torvalds 
34151da177e4SLinus Torvalds 	/*
34161da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
34171da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
34181da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
34191da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
34201da177e4SLinus Torvalds 	 *
34211da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
34221da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
34231da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
34241da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34251da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34261da177e4SLinus Torvalds 	 */
3427930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
342883144186SRafael J. Wysocki 	set_freezable();
34291da177e4SLinus Torvalds 
343038087d9bSMel Gorman 	pgdat->kswapd_order = alloc_order = reclaim_order = 0;
343138087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = classzone_idx = 0;
34321da177e4SLinus Torvalds 	for ( ; ; ) {
34336f6313d4SJeff Liu 		bool ret;
34343e1d1d28SChristoph Lameter 
343538087d9bSMel Gorman kswapd_try_sleep:
343638087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
343738087d9bSMel Gorman 					classzone_idx);
3438215ddd66SMel Gorman 
343938087d9bSMel Gorman 		/* Read the new order and classzone_idx */
344038087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
344138087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
344238087d9bSMel Gorman 		pgdat->kswapd_order = 0;
344338087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = 0;
34441da177e4SLinus Torvalds 
34458fe23e05SDavid Rientjes 		ret = try_to_freeze();
34468fe23e05SDavid Rientjes 		if (kthread_should_stop())
34478fe23e05SDavid Rientjes 			break;
34488fe23e05SDavid Rientjes 
34498fe23e05SDavid Rientjes 		/*
34508fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34518fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3452b1296cc4SRafael J. Wysocki 		 */
345338087d9bSMel Gorman 		if (ret)
345438087d9bSMel Gorman 			continue;
34551d82de61SMel Gorman 
345638087d9bSMel Gorman 		/*
345738087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
345838087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
345938087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
346038087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
346138087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
346238087d9bSMel Gorman 		 * request (alloc_order).
346338087d9bSMel Gorman 		 */
3464e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3465e5146b12SMel Gorman 						alloc_order);
346638087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
346738087d9bSMel Gorman 		if (reclaim_order < alloc_order)
346838087d9bSMel Gorman 			goto kswapd_try_sleep;
346938087d9bSMel Gorman 
347038087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
347138087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
347233906bc5SMel Gorman 	}
3473b0a8cc58STakamori Yamaguchi 
347471abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3475b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
347671abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
347771abdc15SJohannes Weiner 
34781da177e4SLinus Torvalds 	return 0;
34791da177e4SLinus Torvalds }
34801da177e4SLinus Torvalds 
34811da177e4SLinus Torvalds /*
34821da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34831da177e4SLinus Torvalds  */
348499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34851da177e4SLinus Torvalds {
34861da177e4SLinus Torvalds 	pg_data_t *pgdat;
3487e1a55637SMel Gorman 	int z;
34881da177e4SLinus Torvalds 
34896aa303deSMel Gorman 	if (!managed_zone(zone))
34901da177e4SLinus Torvalds 		return;
34911da177e4SLinus Torvalds 
3492344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34931da177e4SLinus Torvalds 		return;
349488f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
349538087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
349638087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
34978d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34981da177e4SLinus Torvalds 		return;
3499e1a55637SMel Gorman 
3500e1a55637SMel Gorman 	/* Only wake kswapd if all zones are unbalanced */
3501e1a55637SMel Gorman 	for (z = 0; z <= classzone_idx; z++) {
3502e1a55637SMel Gorman 		zone = pgdat->node_zones + z;
35036aa303deSMel Gorman 		if (!managed_zone(zone))
3504e1a55637SMel Gorman 			continue;
3505e1a55637SMel Gorman 
3506e1a55637SMel Gorman 		if (zone_balanced(zone, order, classzone_idx))
350788f5acf8SMel Gorman 			return;
3508e1a55637SMel Gorman 	}
350988f5acf8SMel Gorman 
351088f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
35118d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
35121da177e4SLinus Torvalds }
35131da177e4SLinus Torvalds 
3514c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
35151da177e4SLinus Torvalds /*
35167b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3517d6277db4SRafael J. Wysocki  * freed pages.
3518d6277db4SRafael J. Wysocki  *
3519d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3520d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3521d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35221da177e4SLinus Torvalds  */
35237b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35241da177e4SLinus Torvalds {
3525d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3526d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35277b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3528ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3529b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
35309e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3531ee814fe2SJohannes Weiner 		.may_writepage = 1,
3532ee814fe2SJohannes Weiner 		.may_unmap = 1,
3533ee814fe2SJohannes Weiner 		.may_swap = 1,
3534ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
35351da177e4SLinus Torvalds 	};
35367b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
35377b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
35387b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
35391da177e4SLinus Torvalds 
35407b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
35417b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3542d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
35437b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3544d6277db4SRafael J. Wysocki 
35453115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3546d6277db4SRafael J. Wysocki 
35477b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35487b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35497b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3550d6277db4SRafael J. Wysocki 
35517b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35521da177e4SLinus Torvalds }
3553c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35541da177e4SLinus Torvalds 
35551da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35561da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35571da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35581da177e4SLinus Torvalds    restore their cpu bindings. */
3559fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3560fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
35611da177e4SLinus Torvalds {
356258c0a4a7SYasunori Goto 	int nid;
35631da177e4SLinus Torvalds 
35648bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
356548fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3566c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3567a70f7302SRusty Russell 			const struct cpumask *mask;
3568a70f7302SRusty Russell 
3569a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3570c5f59f08SMike Travis 
35713e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35721da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3573c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
35741da177e4SLinus Torvalds 		}
35751da177e4SLinus Torvalds 	}
35761da177e4SLinus Torvalds 	return NOTIFY_OK;
35771da177e4SLinus Torvalds }
35781da177e4SLinus Torvalds 
35793218ae14SYasunori Goto /*
35803218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35813218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35823218ae14SYasunori Goto  */
35833218ae14SYasunori Goto int kswapd_run(int nid)
35843218ae14SYasunori Goto {
35853218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35863218ae14SYasunori Goto 	int ret = 0;
35873218ae14SYasunori Goto 
35883218ae14SYasunori Goto 	if (pgdat->kswapd)
35893218ae14SYasunori Goto 		return 0;
35903218ae14SYasunori Goto 
35913218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35923218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35933218ae14SYasunori Goto 		/* failure at boot is fatal */
35943218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3595d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3596d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3597d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35983218ae14SYasunori Goto 	}
35993218ae14SYasunori Goto 	return ret;
36003218ae14SYasunori Goto }
36013218ae14SYasunori Goto 
36028fe23e05SDavid Rientjes /*
3603d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3604bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
36058fe23e05SDavid Rientjes  */
36068fe23e05SDavid Rientjes void kswapd_stop(int nid)
36078fe23e05SDavid Rientjes {
36088fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
36098fe23e05SDavid Rientjes 
3610d8adde17SJiang Liu 	if (kswapd) {
36118fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3612d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3613d8adde17SJiang Liu 	}
36148fe23e05SDavid Rientjes }
36158fe23e05SDavid Rientjes 
36161da177e4SLinus Torvalds static int __init kswapd_init(void)
36171da177e4SLinus Torvalds {
36183218ae14SYasunori Goto 	int nid;
361969e05944SAndrew Morton 
36201da177e4SLinus Torvalds 	swap_setup();
362148fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
36223218ae14SYasunori Goto  		kswapd_run(nid);
36231da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
36241da177e4SLinus Torvalds 	return 0;
36251da177e4SLinus Torvalds }
36261da177e4SLinus Torvalds 
36271da177e4SLinus Torvalds module_init(kswapd_init)
36289eeff239SChristoph Lameter 
36299eeff239SChristoph Lameter #ifdef CONFIG_NUMA
36309eeff239SChristoph Lameter /*
3631a5f5f91dSMel Gorman  * Node reclaim mode
36329eeff239SChristoph Lameter  *
3633a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
36349eeff239SChristoph Lameter  * the watermarks.
36359eeff239SChristoph Lameter  */
3636a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
36379eeff239SChristoph Lameter 
36381b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
36397d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
36401b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
364195bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
36421b2ffb78SChristoph Lameter 
36439eeff239SChristoph Lameter /*
3644a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3645a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3646a92f7126SChristoph Lameter  * a zone.
3647a92f7126SChristoph Lameter  */
3648a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3649a92f7126SChristoph Lameter 
36509eeff239SChristoph Lameter /*
3651a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
36529614634fSChristoph Lameter  * occur.
36539614634fSChristoph Lameter  */
36549614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36559614634fSChristoph Lameter 
36569614634fSChristoph Lameter /*
36570ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36580ff38490SChristoph Lameter  * slab reclaim needs to occur.
36590ff38490SChristoph Lameter  */
36600ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36610ff38490SChristoph Lameter 
366211fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
366390afa5deSMel Gorman {
366411fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
366511fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
366611fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
366790afa5deSMel Gorman 
366890afa5deSMel Gorman 	/*
366990afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
367090afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
367190afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
367290afa5deSMel Gorman 	 */
367390afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
367490afa5deSMel Gorman }
367590afa5deSMel Gorman 
367690afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3677a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
367890afa5deSMel Gorman {
3679d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3680d031a157SAlexandru Moise 	unsigned long delta = 0;
368190afa5deSMel Gorman 
368290afa5deSMel Gorman 	/*
368395bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
368490afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
368511fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
368690afa5deSMel Gorman 	 * a better estimate
368790afa5deSMel Gorman 	 */
3688a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3689a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
369090afa5deSMel Gorman 	else
3691a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
369290afa5deSMel Gorman 
369390afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3694a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3695a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
369690afa5deSMel Gorman 
369790afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
369890afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
369990afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
370090afa5deSMel Gorman 
370190afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
370290afa5deSMel Gorman }
370390afa5deSMel Gorman 
37040ff38490SChristoph Lameter /*
3705a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
37069eeff239SChristoph Lameter  */
3707a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
37089eeff239SChristoph Lameter {
37097fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
371069e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
37119eeff239SChristoph Lameter 	struct task_struct *p = current;
37129eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3713a5f5f91dSMel Gorman 	int classzone_idx = gfp_zone(gfp_mask);
3714179e9639SAndrew Morton 	struct scan_control sc = {
371562b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
371621caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3717bd2f6199SJohannes Weiner 		.order = order,
3718a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3719a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3720a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3721ee814fe2SJohannes Weiner 		.may_swap = 1,
3722a5f5f91dSMel Gorman 		.reclaim_idx = classzone_idx,
3723179e9639SAndrew Morton 	};
37249eeff239SChristoph Lameter 
37259eeff239SChristoph Lameter 	cond_resched();
3726d4f7796eSChristoph Lameter 	/*
372795bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3728d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
372995bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3730d4f7796eSChristoph Lameter 	 */
3731d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
373276ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
37339eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
37349eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3735c84db23cSChristoph Lameter 
3736a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3737a92f7126SChristoph Lameter 		/*
37380ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
37390ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3740a92f7126SChristoph Lameter 		 */
3741a92f7126SChristoph Lameter 		do {
3742970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
37439e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
37440ff38490SChristoph Lameter 	}
3745a92f7126SChristoph Lameter 
37469eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3747d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
374876ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3749a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37509eeff239SChristoph Lameter }
3751179e9639SAndrew Morton 
3752a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3753179e9639SAndrew Morton {
3754d773ed6bSDavid Rientjes 	int ret;
3755179e9639SAndrew Morton 
3756179e9639SAndrew Morton 	/*
3757a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
37580ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
375934aa1330SChristoph Lameter 	 *
37609614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37619614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3762a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3763a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
37649614634fSChristoph Lameter 	 * unmapped file backed pages.
3765179e9639SAndrew Morton 	 */
3766a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3767a5f5f91dSMel Gorman 	    sum_zone_node_page_state(pgdat->node_id, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3768a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3769179e9639SAndrew Morton 
3770a5f5f91dSMel Gorman 	if (!pgdat_reclaimable(pgdat))
3771a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3772d773ed6bSDavid Rientjes 
3773179e9639SAndrew Morton 	/*
3774d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3775179e9639SAndrew Morton 	 */
3776d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3777a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3778179e9639SAndrew Morton 
3779179e9639SAndrew Morton 	/*
3780a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3781179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3782179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3783179e9639SAndrew Morton 	 * as wide as possible.
3784179e9639SAndrew Morton 	 */
3785a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3786a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3787d773ed6bSDavid Rientjes 
3788a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3789a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3790fa5e084eSMel Gorman 
3791a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3792a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3793d773ed6bSDavid Rientjes 
379424cf7251SMel Gorman 	if (!ret)
379524cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
379624cf7251SMel Gorman 
3797d773ed6bSDavid Rientjes 	return ret;
3798179e9639SAndrew Morton }
37999eeff239SChristoph Lameter #endif
3800894bc310SLee Schermerhorn 
3801894bc310SLee Schermerhorn /*
3802894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3803894bc310SLee Schermerhorn  * @page: the page to test
3804894bc310SLee Schermerhorn  *
3805894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
380639b5f29aSHugh Dickins  * lists vs unevictable list.
3807894bc310SLee Schermerhorn  *
3808894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3809ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3810b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3811ba9ddf49SLee Schermerhorn  *
3812894bc310SLee Schermerhorn  */
381339b5f29aSHugh Dickins int page_evictable(struct page *page)
3814894bc310SLee Schermerhorn {
381539b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3816894bc310SLee Schermerhorn }
381789e004eaSLee Schermerhorn 
381885046579SHugh Dickins #ifdef CONFIG_SHMEM
381989e004eaSLee Schermerhorn /**
382024513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
382124513264SHugh Dickins  * @pages:	array of pages to check
382224513264SHugh Dickins  * @nr_pages:	number of pages to check
382389e004eaSLee Schermerhorn  *
382424513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
382585046579SHugh Dickins  *
382685046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
382789e004eaSLee Schermerhorn  */
382824513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
382989e004eaSLee Schermerhorn {
3830925b7673SJohannes Weiner 	struct lruvec *lruvec;
3831785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
383224513264SHugh Dickins 	int pgscanned = 0;
383324513264SHugh Dickins 	int pgrescued = 0;
383489e004eaSLee Schermerhorn 	int i;
383589e004eaSLee Schermerhorn 
383624513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
383724513264SHugh Dickins 		struct page *page = pages[i];
3838785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
383989e004eaSLee Schermerhorn 
384024513264SHugh Dickins 		pgscanned++;
3841785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3842785b99feSMel Gorman 			if (pgdat)
3843785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3844785b99feSMel Gorman 			pgdat = pagepgdat;
3845785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
384689e004eaSLee Schermerhorn 		}
3847785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
384889e004eaSLee Schermerhorn 
384924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
385024513264SHugh Dickins 			continue;
385189e004eaSLee Schermerhorn 
385239b5f29aSHugh Dickins 		if (page_evictable(page)) {
385324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
385424513264SHugh Dickins 
3855309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
385624513264SHugh Dickins 			ClearPageUnevictable(page);
3857fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3858fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
385924513264SHugh Dickins 			pgrescued++;
386089e004eaSLee Schermerhorn 		}
386189e004eaSLee Schermerhorn 	}
386224513264SHugh Dickins 
3863785b99feSMel Gorman 	if (pgdat) {
386424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
386524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3866785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
386724513264SHugh Dickins 	}
386885046579SHugh Dickins }
386985046579SHugh Dickins #endif /* CONFIG_SHMEM */
3870