xref: /openbmc/linux/mm/vmscan.c (revision 1d82de618ddde0f1164e640f79af152f01994c18)
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 
197599d0c95SMel Gorman /*
198599d0c95SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
199599d0c95SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
200599d0c95SMel Gorman  * not expected that isolated pages will be a dominating factor.
201599d0c95SMel Gorman  */
2020a0337e0SMichal Hocko unsigned long zone_reclaimable_pages(struct zone *zone)
2036e543d57SLisa Du {
204d031a157SAlexandru Moise 	unsigned long nr;
2056e543d57SLisa Du 
206599d0c95SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_LRU_FILE);
2076e543d57SLisa Du 	if (get_nr_swap_pages() > 0)
208599d0c95SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_LRU_ANON);
2096e543d57SLisa Du 
2106e543d57SLisa Du 	return nr;
2116e543d57SLisa Du }
2126e543d57SLisa Du 
213599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2146e543d57SLisa Du {
215599d0c95SMel Gorman 	unsigned long nr;
216599d0c95SMel Gorman 
217599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
218599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
219599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
220599d0c95SMel Gorman 
221599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
222599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
223599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
224599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
225599d0c95SMel Gorman 
226599d0c95SMel Gorman 	return nr;
227599d0c95SMel Gorman }
228599d0c95SMel Gorman 
229599d0c95SMel Gorman bool pgdat_reclaimable(struct pglist_data *pgdat)
230599d0c95SMel Gorman {
231599d0c95SMel Gorman 	return node_page_state_snapshot(pgdat, NR_PAGES_SCANNED) <
232599d0c95SMel Gorman 		pgdat_reclaimable_pages(pgdat) * 6;
2336e543d57SLisa Du }
2346e543d57SLisa Du 
23523047a96SJohannes Weiner unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
236c9f299d9SKOSAKI Motohiro {
237c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2384d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
239a3d8e054SKOSAKI Motohiro 
240599d0c95SMel Gorman 	return node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
241c9f299d9SKOSAKI Motohiro }
242c9f299d9SKOSAKI Motohiro 
2431da177e4SLinus Torvalds /*
2441d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2451da177e4SLinus Torvalds  */
2461d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2471da177e4SLinus Torvalds {
2481d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2491d3d4437SGlauber Costa 
2501d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2511d3d4437SGlauber Costa 		size *= nr_node_ids;
2521d3d4437SGlauber Costa 
2531d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2541d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2551d3d4437SGlauber Costa 		return -ENOMEM;
2561d3d4437SGlauber Costa 
2571da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2581da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2591da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2601d3d4437SGlauber Costa 	return 0;
2611da177e4SLinus Torvalds }
2628e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2631da177e4SLinus Torvalds 
2641da177e4SLinus Torvalds /*
2651da177e4SLinus Torvalds  * Remove one
2661da177e4SLinus Torvalds  */
2678e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2681da177e4SLinus Torvalds {
2691da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2701da177e4SLinus Torvalds 	list_del(&shrinker->list);
2711da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
272ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2731da177e4SLinus Torvalds }
2748e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2751da177e4SLinus Torvalds 
2761da177e4SLinus Torvalds #define SHRINK_BATCH 128
2771d3d4437SGlauber Costa 
278cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2796b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2806b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2816b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2821da177e4SLinus Torvalds {
28324f7c6b9SDave Chinner 	unsigned long freed = 0;
2841da177e4SLinus Torvalds 	unsigned long long delta;
285635697c6SKonstantin Khlebnikov 	long total_scan;
286d5bc5fd3SVladimir Davydov 	long freeable;
287acf92b48SDave Chinner 	long nr;
288acf92b48SDave Chinner 	long new_nr;
2891d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
290e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
291e9299f50SDave Chinner 					  : SHRINK_BATCH;
2921da177e4SLinus Torvalds 
293d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
294d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2951d3d4437SGlauber Costa 		return 0;
296635697c6SKonstantin Khlebnikov 
297acf92b48SDave Chinner 	/*
298acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
299acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
300acf92b48SDave Chinner 	 * don't also do this scanning work.
301acf92b48SDave Chinner 	 */
3021d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
303acf92b48SDave Chinner 
304acf92b48SDave Chinner 	total_scan = nr;
3056b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
306d5bc5fd3SVladimir Davydov 	delta *= freeable;
3076b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
308acf92b48SDave Chinner 	total_scan += delta;
309acf92b48SDave Chinner 	if (total_scan < 0) {
3108612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
311a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
312d5bc5fd3SVladimir Davydov 		total_scan = freeable;
313ea164d73SAndrea Arcangeli 	}
314ea164d73SAndrea Arcangeli 
315ea164d73SAndrea Arcangeli 	/*
3163567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3173567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3183567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3193567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3203567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
321d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3223567b59aSDave Chinner 	 * memory.
3233567b59aSDave Chinner 	 *
3243567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3253567b59aSDave Chinner 	 * a large delta change is calculated directly.
3263567b59aSDave Chinner 	 */
327d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
328d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3293567b59aSDave Chinner 
3303567b59aSDave Chinner 	/*
331ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
332ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
333ea164d73SAndrea Arcangeli 	 * freeable entries.
334ea164d73SAndrea Arcangeli 	 */
335d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
336d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3371da177e4SLinus Torvalds 
33824f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3396b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
340d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
34109576073SDave Chinner 
3420b1fb40aSVladimir Davydov 	/*
3430b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3440b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3450b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3460b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3470b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3480b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3490b1fb40aSVladimir Davydov 	 * batch_size.
3500b1fb40aSVladimir Davydov 	 *
3510b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3520b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
353d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3540b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3550b1fb40aSVladimir Davydov 	 * possible.
3560b1fb40aSVladimir Davydov 	 */
3570b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
358d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
35924f7c6b9SDave Chinner 		unsigned long ret;
3600b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3611da177e4SLinus Torvalds 
3620b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
36324f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
36424f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3651da177e4SLinus Torvalds 			break;
36624f7c6b9SDave Chinner 		freed += ret;
36724f7c6b9SDave Chinner 
3680b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3690b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3701da177e4SLinus Torvalds 
3711da177e4SLinus Torvalds 		cond_resched();
3721da177e4SLinus Torvalds 	}
3731da177e4SLinus Torvalds 
374acf92b48SDave Chinner 	/*
375acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
376acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
377acf92b48SDave Chinner 	 * scan, there is no need to do an update.
378acf92b48SDave Chinner 	 */
37983aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
38083aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3811d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
38283aeeadaSKonstantin Khlebnikov 	else
3831d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
384acf92b48SDave Chinner 
385df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3861d3d4437SGlauber Costa 	return freed;
3871d3d4437SGlauber Costa }
3881d3d4437SGlauber Costa 
3896b4f7799SJohannes Weiner /**
390cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
3916b4f7799SJohannes Weiner  * @gfp_mask: allocation context
3926b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
393cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
3946b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
3956b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
3961d3d4437SGlauber Costa  *
3976b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
3981d3d4437SGlauber Costa  *
3996b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4006b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4011d3d4437SGlauber Costa  *
402cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
403cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4040fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4050fc9f58aSVladimir Davydov  * shrinkers are called.
406cb731d6cSVladimir Davydov  *
4076b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4086b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4096b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4106b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4116b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4126b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4136b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4141d3d4437SGlauber Costa  *
4156b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4161d3d4437SGlauber Costa  */
417cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
418cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4196b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4206b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4211d3d4437SGlauber Costa {
4221d3d4437SGlauber Costa 	struct shrinker *shrinker;
4231d3d4437SGlauber Costa 	unsigned long freed = 0;
4241d3d4437SGlauber Costa 
4250fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
426cb731d6cSVladimir Davydov 		return 0;
427cb731d6cSVladimir Davydov 
4286b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4296b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4301d3d4437SGlauber Costa 
4311d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4321d3d4437SGlauber Costa 		/*
4331d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4341d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4351d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4361d3d4437SGlauber Costa 		 * time.
4371d3d4437SGlauber Costa 		 */
4381d3d4437SGlauber Costa 		freed = 1;
4391d3d4437SGlauber Costa 		goto out;
4401d3d4437SGlauber Costa 	}
4411d3d4437SGlauber Costa 
4421d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4436b4f7799SJohannes Weiner 		struct shrink_control sc = {
4446b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4456b4f7799SJohannes Weiner 			.nid = nid,
446cb731d6cSVladimir Davydov 			.memcg = memcg,
4476b4f7799SJohannes Weiner 		};
4486b4f7799SJohannes Weiner 
4490fc9f58aSVladimir Davydov 		/*
4500fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4510fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4520fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4530fc9f58aSVladimir Davydov 		 */
4540fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4550fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
456cb731d6cSVladimir Davydov 			continue;
457cb731d6cSVladimir Davydov 
4586b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4596b4f7799SJohannes Weiner 			sc.nid = 0;
4606b4f7799SJohannes Weiner 
461cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
462ec97097bSVladimir Davydov 	}
4631d3d4437SGlauber Costa 
4641da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
465f06590bdSMinchan Kim out:
466f06590bdSMinchan Kim 	cond_resched();
46724f7c6b9SDave Chinner 	return freed;
4681da177e4SLinus Torvalds }
4691da177e4SLinus Torvalds 
470cb731d6cSVladimir Davydov void drop_slab_node(int nid)
471cb731d6cSVladimir Davydov {
472cb731d6cSVladimir Davydov 	unsigned long freed;
473cb731d6cSVladimir Davydov 
474cb731d6cSVladimir Davydov 	do {
475cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
476cb731d6cSVladimir Davydov 
477cb731d6cSVladimir Davydov 		freed = 0;
478cb731d6cSVladimir Davydov 		do {
479cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
480cb731d6cSVladimir Davydov 					     1000, 1000);
481cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
482cb731d6cSVladimir Davydov 	} while (freed > 10);
483cb731d6cSVladimir Davydov }
484cb731d6cSVladimir Davydov 
485cb731d6cSVladimir Davydov void drop_slab(void)
486cb731d6cSVladimir Davydov {
487cb731d6cSVladimir Davydov 	int nid;
488cb731d6cSVladimir Davydov 
489cb731d6cSVladimir Davydov 	for_each_online_node(nid)
490cb731d6cSVladimir Davydov 		drop_slab_node(nid);
491cb731d6cSVladimir Davydov }
492cb731d6cSVladimir Davydov 
4931da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4941da177e4SLinus Torvalds {
495ceddc3a5SJohannes Weiner 	/*
496ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
497ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
498ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
499ceddc3a5SJohannes Weiner 	 */
500edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5011da177e4SLinus Torvalds }
5021da177e4SLinus Torvalds 
503703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5041da177e4SLinus Torvalds {
505930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5061da177e4SLinus Torvalds 		return 1;
507703c2708STejun Heo 	if (!inode_write_congested(inode))
5081da177e4SLinus Torvalds 		return 1;
509703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5101da177e4SLinus Torvalds 		return 1;
5111da177e4SLinus Torvalds 	return 0;
5121da177e4SLinus Torvalds }
5131da177e4SLinus Torvalds 
5141da177e4SLinus Torvalds /*
5151da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5161da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5171da177e4SLinus Torvalds  * fsync(), msync() or close().
5181da177e4SLinus Torvalds  *
5191da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5201da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5211da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5221da177e4SLinus Torvalds  *
5231da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5241da177e4SLinus Torvalds  * __GFP_FS.
5251da177e4SLinus Torvalds  */
5261da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5271da177e4SLinus Torvalds 				struct page *page, int error)
5281da177e4SLinus Torvalds {
5297eaceaccSJens Axboe 	lock_page(page);
5303e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5313e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5321da177e4SLinus Torvalds 	unlock_page(page);
5331da177e4SLinus Torvalds }
5341da177e4SLinus Torvalds 
53504e62a29SChristoph Lameter /* possible outcome of pageout() */
53604e62a29SChristoph Lameter typedef enum {
53704e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
53804e62a29SChristoph Lameter 	PAGE_KEEP,
53904e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
54004e62a29SChristoph Lameter 	PAGE_ACTIVATE,
54104e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
54204e62a29SChristoph Lameter 	PAGE_SUCCESS,
54304e62a29SChristoph Lameter 	/* page is clean and locked */
54404e62a29SChristoph Lameter 	PAGE_CLEAN,
54504e62a29SChristoph Lameter } pageout_t;
54604e62a29SChristoph Lameter 
5471da177e4SLinus Torvalds /*
5481742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5491742f19fSAndrew Morton  * Calls ->writepage().
5501da177e4SLinus Torvalds  */
551c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5527d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5531da177e4SLinus Torvalds {
5541da177e4SLinus Torvalds 	/*
5551da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5561da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5571da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5581da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5591da177e4SLinus Torvalds 	 * PagePrivate for that.
5601da177e4SLinus Torvalds 	 *
5618174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5621da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5631da177e4SLinus Torvalds 	 * will block.
5641da177e4SLinus Torvalds 	 *
5651da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5661da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5671da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5681da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5691da177e4SLinus Torvalds 	 */
5701da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5711da177e4SLinus Torvalds 		return PAGE_KEEP;
5721da177e4SLinus Torvalds 	if (!mapping) {
5731da177e4SLinus Torvalds 		/*
5741da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5751da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5761da177e4SLinus Torvalds 		 */
577266cf658SDavid Howells 		if (page_has_private(page)) {
5781da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5791da177e4SLinus Torvalds 				ClearPageDirty(page);
580b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5811da177e4SLinus Torvalds 				return PAGE_CLEAN;
5821da177e4SLinus Torvalds 			}
5831da177e4SLinus Torvalds 		}
5841da177e4SLinus Torvalds 		return PAGE_KEEP;
5851da177e4SLinus Torvalds 	}
5861da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
5871da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
588703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
5891da177e4SLinus Torvalds 		return PAGE_KEEP;
5901da177e4SLinus Torvalds 
5911da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5921da177e4SLinus Torvalds 		int res;
5931da177e4SLinus Torvalds 		struct writeback_control wbc = {
5941da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5951da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
596111ebb6eSOGAWA Hirofumi 			.range_start = 0,
597111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
5981da177e4SLinus Torvalds 			.for_reclaim = 1,
5991da177e4SLinus Torvalds 		};
6001da177e4SLinus Torvalds 
6011da177e4SLinus Torvalds 		SetPageReclaim(page);
6021da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6031da177e4SLinus Torvalds 		if (res < 0)
6041da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
605994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6061da177e4SLinus Torvalds 			ClearPageReclaim(page);
6071da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6081da177e4SLinus Torvalds 		}
609c661b078SAndy Whitcroft 
6101da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6111da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6121da177e4SLinus Torvalds 			ClearPageReclaim(page);
6131da177e4SLinus Torvalds 		}
6143aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
615e129b5c2SAndrew Morton 		inc_zone_page_state(page, NR_VMSCAN_WRITE);
6161da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6171da177e4SLinus Torvalds 	}
6181da177e4SLinus Torvalds 
6191da177e4SLinus Torvalds 	return PAGE_CLEAN;
6201da177e4SLinus Torvalds }
6211da177e4SLinus Torvalds 
622a649fd92SAndrew Morton /*
623e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
624e286781dSNick Piggin  * gets returned with a refcount of 0.
625a649fd92SAndrew Morton  */
626a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
627a528910eSJohannes Weiner 			    bool reclaimed)
62849d2e9ccSChristoph Lameter {
629c4843a75SGreg Thelen 	unsigned long flags;
630c4843a75SGreg Thelen 
63128e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
63228e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
63349d2e9ccSChristoph Lameter 
634c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
63549d2e9ccSChristoph Lameter 	/*
6360fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6370fd0e6b0SNick Piggin 	 *
6380fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6390fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6400fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6410fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6420fd0e6b0SNick Piggin 	 *
6430fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6440fd0e6b0SNick Piggin 	 * [user mapping goes away]
6450fd0e6b0SNick Piggin 	 * write_to(page);
6460fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6470fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6480fd0e6b0SNick Piggin 	 * put_page(page);
6490fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6500fd0e6b0SNick Piggin 	 *
6510fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6520fd0e6b0SNick Piggin 	 *
6530fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6540fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6550139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6560fd0e6b0SNick Piggin 	 *
6570fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6580fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
65949d2e9ccSChristoph Lameter 	 */
660fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
66149d2e9ccSChristoph Lameter 		goto cannot_free;
662e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
663e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
664fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
66549d2e9ccSChristoph Lameter 		goto cannot_free;
666e286781dSNick Piggin 	}
66749d2e9ccSChristoph Lameter 
66849d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
66949d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6700a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
67149d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
672c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6730a31bc97SJohannes Weiner 		swapcache_free(swap);
674e286781dSNick Piggin 	} else {
6756072d13cSLinus Torvalds 		void (*freepage)(struct page *);
676a528910eSJohannes Weiner 		void *shadow = NULL;
6776072d13cSLinus Torvalds 
6786072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
679a528910eSJohannes Weiner 		/*
680a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
681a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
682a528910eSJohannes Weiner 		 *
683a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
684a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
685a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
686a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
687a528910eSJohannes Weiner 		 * back.
688f9fe48beSRoss Zwisler 		 *
689f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
690f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
691f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
692f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
693f9fe48beSRoss Zwisler 		 * same page_tree.
694a528910eSJohannes Weiner 		 */
695a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
696f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
697a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
69862cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
699c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7006072d13cSLinus Torvalds 
7016072d13cSLinus Torvalds 		if (freepage != NULL)
7026072d13cSLinus Torvalds 			freepage(page);
703e286781dSNick Piggin 	}
704e286781dSNick Piggin 
70549d2e9ccSChristoph Lameter 	return 1;
70649d2e9ccSChristoph Lameter 
70749d2e9ccSChristoph Lameter cannot_free:
708c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
70949d2e9ccSChristoph Lameter 	return 0;
71049d2e9ccSChristoph Lameter }
71149d2e9ccSChristoph Lameter 
7121da177e4SLinus Torvalds /*
713e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
714e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
715e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
716e286781dSNick Piggin  * this page.
717e286781dSNick Piggin  */
718e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
719e286781dSNick Piggin {
720a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
721e286781dSNick Piggin 		/*
722e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
723e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
724e286781dSNick Piggin 		 * atomic operation.
725e286781dSNick Piggin 		 */
726fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
727e286781dSNick Piggin 		return 1;
728e286781dSNick Piggin 	}
729e286781dSNick Piggin 	return 0;
730e286781dSNick Piggin }
731e286781dSNick Piggin 
732894bc310SLee Schermerhorn /**
733894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
734894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
735894bc310SLee Schermerhorn  *
736894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
737894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
738894bc310SLee Schermerhorn  *
739894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
740894bc310SLee Schermerhorn  */
741894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
742894bc310SLee Schermerhorn {
7430ec3b74cSVlastimil Babka 	bool is_unevictable;
744bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
745894bc310SLee Schermerhorn 
746309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
747894bc310SLee Schermerhorn 
748894bc310SLee Schermerhorn redo:
749894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
750894bc310SLee Schermerhorn 
75139b5f29aSHugh Dickins 	if (page_evictable(page)) {
752894bc310SLee Schermerhorn 		/*
753894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
754894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
755894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
756894bc310SLee Schermerhorn 		 * We know how to handle that.
757894bc310SLee Schermerhorn 		 */
7580ec3b74cSVlastimil Babka 		is_unevictable = false;
759c53954a0SMel Gorman 		lru_cache_add(page);
760894bc310SLee Schermerhorn 	} else {
761894bc310SLee Schermerhorn 		/*
762894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
763894bc310SLee Schermerhorn 		 * list.
764894bc310SLee Schermerhorn 		 */
7650ec3b74cSVlastimil Babka 		is_unevictable = true;
766894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7676a7b9548SJohannes Weiner 		/*
76821ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
76921ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
77021ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
77124513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
77221ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7736a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7746a7b9548SJohannes Weiner 		 *
77521ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7766a7b9548SJohannes Weiner 		 */
7776a7b9548SJohannes Weiner 		smp_mb();
778894bc310SLee Schermerhorn 	}
779894bc310SLee Schermerhorn 
780894bc310SLee Schermerhorn 	/*
781894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
782894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
783894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
784894bc310SLee Schermerhorn 	 */
7850ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
786894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
787894bc310SLee Schermerhorn 			put_page(page);
788894bc310SLee Schermerhorn 			goto redo;
789894bc310SLee Schermerhorn 		}
790894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
791894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
792894bc310SLee Schermerhorn 		 * nothing to do here.
793894bc310SLee Schermerhorn 		 */
794894bc310SLee Schermerhorn 	}
795894bc310SLee Schermerhorn 
7960ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
797bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
7980ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
799bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
800bbfd28eeSLee Schermerhorn 
801894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
802894bc310SLee Schermerhorn }
803894bc310SLee Schermerhorn 
804dfc8d636SJohannes Weiner enum page_references {
805dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
806dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
80764574746SJohannes Weiner 	PAGEREF_KEEP,
808dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
809dfc8d636SJohannes Weiner };
810dfc8d636SJohannes Weiner 
811dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
812dfc8d636SJohannes Weiner 						  struct scan_control *sc)
813dfc8d636SJohannes Weiner {
81464574746SJohannes Weiner 	int referenced_ptes, referenced_page;
815dfc8d636SJohannes Weiner 	unsigned long vm_flags;
816dfc8d636SJohannes Weiner 
817c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
818c3ac9a8aSJohannes Weiner 					  &vm_flags);
81964574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
820dfc8d636SJohannes Weiner 
821dfc8d636SJohannes Weiner 	/*
822dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
823dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
824dfc8d636SJohannes Weiner 	 */
825dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
826dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
827dfc8d636SJohannes Weiner 
82864574746SJohannes Weiner 	if (referenced_ptes) {
829e4898273SMichal Hocko 		if (PageSwapBacked(page))
83064574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
83164574746SJohannes Weiner 		/*
83264574746SJohannes Weiner 		 * All mapped pages start out with page table
83364574746SJohannes Weiner 		 * references from the instantiating fault, so we need
83464574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
83564574746SJohannes Weiner 		 * than once.
83664574746SJohannes Weiner 		 *
83764574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
83864574746SJohannes Weiner 		 * inactive list.  Another page table reference will
83964574746SJohannes Weiner 		 * lead to its activation.
84064574746SJohannes Weiner 		 *
84164574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
84264574746SJohannes Weiner 		 * so that recently deactivated but used pages are
84364574746SJohannes Weiner 		 * quickly recovered.
84464574746SJohannes Weiner 		 */
84564574746SJohannes Weiner 		SetPageReferenced(page);
84664574746SJohannes Weiner 
84734dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
848dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
849dfc8d636SJohannes Weiner 
850c909e993SKonstantin Khlebnikov 		/*
851c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
852c909e993SKonstantin Khlebnikov 		 */
853c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
854c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
855c909e993SKonstantin Khlebnikov 
85664574746SJohannes Weiner 		return PAGEREF_KEEP;
85764574746SJohannes Weiner 	}
85864574746SJohannes Weiner 
859dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8602e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
861dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
86264574746SJohannes Weiner 
86364574746SJohannes Weiner 	return PAGEREF_RECLAIM;
864dfc8d636SJohannes Weiner }
865dfc8d636SJohannes Weiner 
866e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
867e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
868e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
869e2be15f6SMel Gorman {
870b4597226SMel Gorman 	struct address_space *mapping;
871b4597226SMel Gorman 
872e2be15f6SMel Gorman 	/*
873e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
874e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
875e2be15f6SMel Gorman 	 */
876e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
877e2be15f6SMel Gorman 		*dirty = false;
878e2be15f6SMel Gorman 		*writeback = false;
879e2be15f6SMel Gorman 		return;
880e2be15f6SMel Gorman 	}
881e2be15f6SMel Gorman 
882e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
883e2be15f6SMel Gorman 	*dirty = PageDirty(page);
884e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
885b4597226SMel Gorman 
886b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
887b4597226SMel Gorman 	if (!page_has_private(page))
888b4597226SMel Gorman 		return;
889b4597226SMel Gorman 
890b4597226SMel Gorman 	mapping = page_mapping(page);
891b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
892b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
893e2be15f6SMel Gorman }
894e2be15f6SMel Gorman 
895e286781dSNick Piggin /*
8961742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8971da177e4SLinus Torvalds  */
8981742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
899599d0c95SMel Gorman 				      struct pglist_data *pgdat,
900f84f6e2bSMel Gorman 				      struct scan_control *sc,
90102c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9028e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
903d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
9048e950282SMel Gorman 				      unsigned long *ret_nr_congested,
90502c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
906b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
90702c6de8dSMinchan Kim 				      bool force_reclaim)
9081da177e4SLinus Torvalds {
9091da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
910abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9111da177e4SLinus Torvalds 	int pgactivate = 0;
912d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
9130e093d99SMel Gorman 	unsigned long nr_dirty = 0;
9140e093d99SMel Gorman 	unsigned long nr_congested = 0;
91505ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
91692df3a72SMel Gorman 	unsigned long nr_writeback = 0;
917b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
9181da177e4SLinus Torvalds 
9191da177e4SLinus Torvalds 	cond_resched();
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9221da177e4SLinus Torvalds 		struct address_space *mapping;
9231da177e4SLinus Torvalds 		struct page *page;
9241da177e4SLinus Torvalds 		int may_enter_fs;
92502c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
926e2be15f6SMel Gorman 		bool dirty, writeback;
927854e9ed0SMinchan Kim 		bool lazyfree = false;
928854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9291da177e4SLinus Torvalds 
9301da177e4SLinus Torvalds 		cond_resched();
9311da177e4SLinus Torvalds 
9321da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9331da177e4SLinus Torvalds 		list_del(&page->lru);
9341da177e4SLinus Torvalds 
935529ae9aaSNick Piggin 		if (!trylock_page(page))
9361da177e4SLinus Torvalds 			goto keep;
9371da177e4SLinus Torvalds 
938309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9391da177e4SLinus Torvalds 
9401da177e4SLinus Torvalds 		sc->nr_scanned++;
94180e43426SChristoph Lameter 
94239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
943b291f000SNick Piggin 			goto cull_mlocked;
944894bc310SLee Schermerhorn 
945a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
94680e43426SChristoph Lameter 			goto keep_locked;
94780e43426SChristoph Lameter 
9481da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9491da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9501da177e4SLinus Torvalds 			sc->nr_scanned++;
9511da177e4SLinus Torvalds 
952c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
953c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
954c661b078SAndy Whitcroft 
955e62e384eSMichal Hocko 		/*
956e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
957e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
958e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
959e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
960e2be15f6SMel Gorman 		 */
961e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
962e2be15f6SMel Gorman 		if (dirty || writeback)
963e2be15f6SMel Gorman 			nr_dirty++;
964e2be15f6SMel Gorman 
965e2be15f6SMel Gorman 		if (dirty && !writeback)
966e2be15f6SMel Gorman 			nr_unqueued_dirty++;
967e2be15f6SMel Gorman 
968d04e8acdSMel Gorman 		/*
969d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
970d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
971d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
972d04e8acdSMel Gorman 		 * end of the LRU a second time.
973d04e8acdSMel Gorman 		 */
974e2be15f6SMel Gorman 		mapping = page_mapping(page);
9751da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
976703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
977d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
978e2be15f6SMel Gorman 			nr_congested++;
979e2be15f6SMel Gorman 
980e2be15f6SMel Gorman 		/*
981283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
982283aba9fSMel Gorman 		 * are three cases to consider.
983e62e384eSMichal Hocko 		 *
984283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
985283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
986283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
987283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
988283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
989283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
990283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
991b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
992b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
993c3b94f44SHugh Dickins 		 *
99497c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
995ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
996ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
997ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
99897c9341fSTejun Heo 		 *    reclaim and continue scanning.
999283aba9fSMel Gorman 		 *
1000ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1001ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1002283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1003283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1004283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1005283aba9fSMel Gorman 		 *    would probably show more reasons.
1006283aba9fSMel Gorman 		 *
10077fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1008283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1009283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1010283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1011283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1012e62e384eSMichal Hocko 		 */
1013283aba9fSMel Gorman 		if (PageWriteback(page)) {
1014283aba9fSMel Gorman 			/* Case 1 above */
1015283aba9fSMel Gorman 			if (current_is_kswapd() &&
1016283aba9fSMel Gorman 			    PageReclaim(page) &&
1017599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1018b1a6f21eSMel Gorman 				nr_immediate++;
1019b1a6f21eSMel Gorman 				goto keep_locked;
1020283aba9fSMel Gorman 
1021283aba9fSMel Gorman 			/* Case 2 above */
102297c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1023ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1024c3b94f44SHugh Dickins 				/*
1025c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1026c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1027c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1028c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1029c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1030c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1031c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1032c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1033c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1034c3b94f44SHugh Dickins 				 */
1035c3b94f44SHugh Dickins 				SetPageReclaim(page);
103692df3a72SMel Gorman 				nr_writeback++;
1037c3b94f44SHugh Dickins 				goto keep_locked;
1038283aba9fSMel Gorman 
1039283aba9fSMel Gorman 			/* Case 3 above */
1040283aba9fSMel Gorman 			} else {
10417fadc820SHugh Dickins 				unlock_page(page);
1042c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10437fadc820SHugh Dickins 				/* then go back and try same page again */
10447fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10457fadc820SHugh Dickins 				continue;
1046e62e384eSMichal Hocko 			}
1047283aba9fSMel Gorman 		}
10481da177e4SLinus Torvalds 
104902c6de8dSMinchan Kim 		if (!force_reclaim)
10506a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
105102c6de8dSMinchan Kim 
1052dfc8d636SJohannes Weiner 		switch (references) {
1053dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10541da177e4SLinus Torvalds 			goto activate_locked;
105564574746SJohannes Weiner 		case PAGEREF_KEEP:
105664574746SJohannes Weiner 			goto keep_locked;
1057dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1058dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1059dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1060dfc8d636SJohannes Weiner 		}
10611da177e4SLinus Torvalds 
10621da177e4SLinus Torvalds 		/*
10631da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10641da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10651da177e4SLinus Torvalds 		 */
1066b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
106763eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
106863eb6b93SHugh Dickins 				goto keep_locked;
10695bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10701da177e4SLinus Torvalds 				goto activate_locked;
1071854e9ed0SMinchan Kim 			lazyfree = true;
107263eb6b93SHugh Dickins 			may_enter_fs = 1;
10731da177e4SLinus Torvalds 
1074e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10751da177e4SLinus Torvalds 			mapping = page_mapping(page);
10767751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
10777751b2daSKirill A. Shutemov 			/* Split file THP */
10787751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
10797751b2daSKirill A. Shutemov 				goto keep_locked;
1080e2be15f6SMel Gorman 		}
10811da177e4SLinus Torvalds 
10827751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
10837751b2daSKirill A. Shutemov 
10841da177e4SLinus Torvalds 		/*
10851da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10861da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10871da177e4SLinus Torvalds 		 */
10881da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1089854e9ed0SMinchan Kim 			switch (ret = try_to_unmap(page, lazyfree ?
1090854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
1091854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH))) {
10921da177e4SLinus Torvalds 			case SWAP_FAIL:
10931da177e4SLinus Torvalds 				goto activate_locked;
10941da177e4SLinus Torvalds 			case SWAP_AGAIN:
10951da177e4SLinus Torvalds 				goto keep_locked;
1096b291f000SNick Piggin 			case SWAP_MLOCK:
1097b291f000SNick Piggin 				goto cull_mlocked;
1098854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1099854e9ed0SMinchan Kim 				goto lazyfree;
11001da177e4SLinus Torvalds 			case SWAP_SUCCESS:
11011da177e4SLinus Torvalds 				; /* try to free the page below */
11021da177e4SLinus Torvalds 			}
11031da177e4SLinus Torvalds 		}
11041da177e4SLinus Torvalds 
11051da177e4SLinus Torvalds 		if (PageDirty(page)) {
1106ee72886dSMel Gorman 			/*
1107ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1108d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1109d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1110ee72886dSMel Gorman 			 */
1111f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11129e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
1113599d0c95SMel Gorman 					 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
111449ea7eb6SMel Gorman 				/*
111549ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
111649ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
111749ea7eb6SMel Gorman 				 * except we already have the page isolated
111849ea7eb6SMel Gorman 				 * and know it's dirty
111949ea7eb6SMel Gorman 				 */
112049ea7eb6SMel Gorman 				inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
112149ea7eb6SMel Gorman 				SetPageReclaim(page);
112249ea7eb6SMel Gorman 
1123ee72886dSMel Gorman 				goto keep_locked;
1124ee72886dSMel Gorman 			}
1125ee72886dSMel Gorman 
1126dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11271da177e4SLinus Torvalds 				goto keep_locked;
11284dd4b920SAndrew Morton 			if (!may_enter_fs)
11291da177e4SLinus Torvalds 				goto keep_locked;
113052a8363eSChristoph Lameter 			if (!sc->may_writepage)
11311da177e4SLinus Torvalds 				goto keep_locked;
11321da177e4SLinus Torvalds 
1133d950c947SMel Gorman 			/*
1134d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1135d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1136d950c947SMel Gorman 			 * starts and then write it out here.
1137d950c947SMel Gorman 			 */
1138d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11397d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11401da177e4SLinus Torvalds 			case PAGE_KEEP:
11411da177e4SLinus Torvalds 				goto keep_locked;
11421da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11431da177e4SLinus Torvalds 				goto activate_locked;
11441da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11457d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
114641ac1999SMel Gorman 					goto keep;
11477d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11481da177e4SLinus Torvalds 					goto keep;
11497d3579e8SKOSAKI Motohiro 
11501da177e4SLinus Torvalds 				/*
11511da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11521da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11531da177e4SLinus Torvalds 				 */
1154529ae9aaSNick Piggin 				if (!trylock_page(page))
11551da177e4SLinus Torvalds 					goto keep;
11561da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11571da177e4SLinus Torvalds 					goto keep_locked;
11581da177e4SLinus Torvalds 				mapping = page_mapping(page);
11591da177e4SLinus Torvalds 			case PAGE_CLEAN:
11601da177e4SLinus Torvalds 				; /* try to free the page below */
11611da177e4SLinus Torvalds 			}
11621da177e4SLinus Torvalds 		}
11631da177e4SLinus Torvalds 
11641da177e4SLinus Torvalds 		/*
11651da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11661da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11671da177e4SLinus Torvalds 		 * the page as well.
11681da177e4SLinus Torvalds 		 *
11691da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11701da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11711da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11721da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11731da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11741da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11751da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11761da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11771da177e4SLinus Torvalds 		 *
11781da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11791da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11801da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11811da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11821da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11831da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11841da177e4SLinus Torvalds 		 */
1185266cf658SDavid Howells 		if (page_has_private(page)) {
11861da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11871da177e4SLinus Torvalds 				goto activate_locked;
1188e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1189e286781dSNick Piggin 				unlock_page(page);
1190e286781dSNick Piggin 				if (put_page_testzero(page))
11911da177e4SLinus Torvalds 					goto free_it;
1192e286781dSNick Piggin 				else {
1193e286781dSNick Piggin 					/*
1194e286781dSNick Piggin 					 * rare race with speculative reference.
1195e286781dSNick Piggin 					 * the speculative reference will free
1196e286781dSNick Piggin 					 * this page shortly, so we may
1197e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1198e286781dSNick Piggin 					 * leave it off the LRU).
1199e286781dSNick Piggin 					 */
1200e286781dSNick Piggin 					nr_reclaimed++;
1201e286781dSNick Piggin 					continue;
1202e286781dSNick Piggin 				}
1203e286781dSNick Piggin 			}
12041da177e4SLinus Torvalds 		}
12051da177e4SLinus Torvalds 
1206854e9ed0SMinchan Kim lazyfree:
1207a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
120849d2e9ccSChristoph Lameter 			goto keep_locked;
12091da177e4SLinus Torvalds 
1210a978d6f5SNick Piggin 		/*
1211a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1212a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1213a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1214a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1215a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1216a978d6f5SNick Piggin 		 */
121748c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1218e286781dSNick Piggin free_it:
1219854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1220854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1221854e9ed0SMinchan Kim 
122205ff5137SAndrew Morton 		nr_reclaimed++;
1223abe4c3b5SMel Gorman 
1224abe4c3b5SMel Gorman 		/*
1225abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1226abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1227abe4c3b5SMel Gorman 		 */
1228abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12291da177e4SLinus Torvalds 		continue;
12301da177e4SLinus Torvalds 
1231b291f000SNick Piggin cull_mlocked:
123263d6c5adSHugh Dickins 		if (PageSwapCache(page))
123363d6c5adSHugh Dickins 			try_to_free_swap(page);
1234b291f000SNick Piggin 		unlock_page(page);
1235c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1236b291f000SNick Piggin 		continue;
1237b291f000SNick Piggin 
12381da177e4SLinus Torvalds activate_locked:
123968a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12405ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1241a2c43eedSHugh Dickins 			try_to_free_swap(page);
1242309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12431da177e4SLinus Torvalds 		SetPageActive(page);
12441da177e4SLinus Torvalds 		pgactivate++;
12451da177e4SLinus Torvalds keep_locked:
12461da177e4SLinus Torvalds 		unlock_page(page);
12471da177e4SLinus Torvalds keep:
12481da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1249309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12501da177e4SLinus Torvalds 	}
1251abe4c3b5SMel Gorman 
1252747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
125372b252aeSMel Gorman 	try_to_unmap_flush();
1254b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1255abe4c3b5SMel Gorman 
12561da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1257f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12580a31bc97SJohannes Weiner 
12598e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12608e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1261d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
126292df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1263b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
126405ff5137SAndrew Morton 	return nr_reclaimed;
12651da177e4SLinus Torvalds }
12661da177e4SLinus Torvalds 
126702c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
126802c6de8dSMinchan Kim 					    struct list_head *page_list)
126902c6de8dSMinchan Kim {
127002c6de8dSMinchan Kim 	struct scan_control sc = {
127102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
127202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
127302c6de8dSMinchan Kim 		.may_unmap = 1,
127402c6de8dSMinchan Kim 	};
12758e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
127602c6de8dSMinchan Kim 	struct page *page, *next;
127702c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
127802c6de8dSMinchan Kim 
127902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1280117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1281b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
128202c6de8dSMinchan Kim 			ClearPageActive(page);
128302c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
128402c6de8dSMinchan Kim 		}
128502c6de8dSMinchan Kim 	}
128602c6de8dSMinchan Kim 
1287599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
128802c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
12898e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
129002c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1291599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
129202c6de8dSMinchan Kim 	return ret;
129302c6de8dSMinchan Kim }
129402c6de8dSMinchan Kim 
12955ad333ebSAndy Whitcroft /*
12965ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
12975ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
12985ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
12995ad333ebSAndy Whitcroft  *
13005ad333ebSAndy Whitcroft  * page:	page to consider
13015ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13025ad333ebSAndy Whitcroft  *
13035ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13045ad333ebSAndy Whitcroft  */
1305f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13065ad333ebSAndy Whitcroft {
13075ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13085ad333ebSAndy Whitcroft 
13095ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13105ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13115ad333ebSAndy Whitcroft 		return ret;
13125ad333ebSAndy Whitcroft 
1313e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1314e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1315894bc310SLee Schermerhorn 		return ret;
1316894bc310SLee Schermerhorn 
13175ad333ebSAndy Whitcroft 	ret = -EBUSY;
131808e552c6SKAMEZAWA Hiroyuki 
1319c8244935SMel Gorman 	/*
1320c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1321c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1322c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1323c8244935SMel Gorman 	 *
1324c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1325c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1326c8244935SMel Gorman 	 *
1327c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1328c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1329c8244935SMel Gorman 	 */
1330c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1331c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1332c8244935SMel Gorman 		if (PageWriteback(page))
133339deaf85SMinchan Kim 			return ret;
133439deaf85SMinchan Kim 
1335c8244935SMel Gorman 		if (PageDirty(page)) {
1336c8244935SMel Gorman 			struct address_space *mapping;
1337c8244935SMel Gorman 
1338c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1339c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1340c8244935SMel Gorman 				return ret;
1341c8244935SMel Gorman 
1342c8244935SMel Gorman 			/*
1343c8244935SMel Gorman 			 * Only pages without mappings or that have a
1344c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1345c8244935SMel Gorman 			 * without blocking
1346c8244935SMel Gorman 			 */
1347c8244935SMel Gorman 			mapping = page_mapping(page);
1348c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1349c8244935SMel Gorman 				return ret;
1350c8244935SMel Gorman 		}
1351c8244935SMel Gorman 	}
1352c8244935SMel Gorman 
1353f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1354f80c0673SMinchan Kim 		return ret;
1355f80c0673SMinchan Kim 
13565ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13575ad333ebSAndy Whitcroft 		/*
13585ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13595ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13605ad333ebSAndy Whitcroft 		 * page release code relies on it.
13615ad333ebSAndy Whitcroft 		 */
13625ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13635ad333ebSAndy Whitcroft 		ret = 0;
13645ad333ebSAndy Whitcroft 	}
13655ad333ebSAndy Whitcroft 
13665ad333ebSAndy Whitcroft 	return ret;
13675ad333ebSAndy Whitcroft }
13685ad333ebSAndy Whitcroft 
136949d2e9ccSChristoph Lameter /*
1370a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
13711da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
13721da177e4SLinus Torvalds  * and working on them outside the LRU lock.
13731da177e4SLinus Torvalds  *
13741da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
13751da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
13761da177e4SLinus Torvalds  *
13771da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
13781da177e4SLinus Torvalds  *
13791da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
13805dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
13811da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1382f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1383fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
13845ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
13853cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
13861da177e4SLinus Torvalds  *
13871da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
13881da177e4SLinus Torvalds  */
138969e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
13905dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1391fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
13923cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
13931da177e4SLinus Torvalds {
139475b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
139569e05944SAndrew Morton 	unsigned long nr_taken = 0;
1396599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1397599d0c95SMel Gorman 	unsigned long scan, nr_pages;
1398b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
13991da177e4SLinus Torvalds 
14000b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
14010b802f10SVladimir Davydov 					!list_empty(src); scan++) {
14025ad333ebSAndy Whitcroft 		struct page *page;
14035ad333ebSAndy Whitcroft 
14041da177e4SLinus Torvalds 		page = lru_to_page(src);
14051da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14061da177e4SLinus Torvalds 
1407309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14088d438f96SNick Piggin 
1409b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1410b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
1411b2e18757SMel Gorman 			continue;
1412b2e18757SMel Gorman 		}
1413b2e18757SMel Gorman 
1414f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14155ad333ebSAndy Whitcroft 		case 0:
1416599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1417599d0c95SMel Gorman 			nr_taken += nr_pages;
1418599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14195ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14205ad333ebSAndy Whitcroft 			break;
14217c8ee9a8SNick Piggin 
14225ad333ebSAndy Whitcroft 		case -EBUSY:
14235ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
14245ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
14255ad333ebSAndy Whitcroft 			continue;
14265ad333ebSAndy Whitcroft 
14275ad333ebSAndy Whitcroft 		default:
14285ad333ebSAndy Whitcroft 			BUG();
14295ad333ebSAndy Whitcroft 		}
14305ad333ebSAndy Whitcroft 	}
14311da177e4SLinus Torvalds 
1432b2e18757SMel Gorman 	/*
1433b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1434b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1435b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1436b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1437b2e18757SMel Gorman 	 * system at risk of premature OOM.
1438b2e18757SMel Gorman 	 */
1439b2e18757SMel Gorman 	if (!list_empty(&pages_skipped))
1440b2e18757SMel Gorman 		list_splice(&pages_skipped, src);
1441f626012dSHugh Dickins 	*nr_scanned = scan;
144275b00af7SHugh Dickins 	trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
144375b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
1444599d0c95SMel Gorman 	for (scan = 0; scan < MAX_NR_ZONES; scan++) {
1445599d0c95SMel Gorman 		nr_pages = nr_zone_taken[scan];
1446599d0c95SMel Gorman 		if (!nr_pages)
1447599d0c95SMel Gorman 			continue;
1448599d0c95SMel Gorman 
1449599d0c95SMel Gorman 		update_lru_size(lruvec, lru, scan, -nr_pages);
1450599d0c95SMel Gorman 	}
14511da177e4SLinus Torvalds 	return nr_taken;
14521da177e4SLinus Torvalds }
14531da177e4SLinus Torvalds 
145462695a84SNick Piggin /**
145562695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
145662695a84SNick Piggin  * @page: page to isolate from its LRU list
145762695a84SNick Piggin  *
145862695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
145962695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
146062695a84SNick Piggin  *
146162695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
146262695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
146362695a84SNick Piggin  *
146462695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1465894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1466894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1467894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
146862695a84SNick Piggin  *
146962695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
147062695a84SNick Piggin  * found will be decremented.
147162695a84SNick Piggin  *
147262695a84SNick Piggin  * Restrictions:
147362695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
147462695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
147562695a84SNick Piggin  *     without a stable reference).
147662695a84SNick Piggin  * (2) the lru_lock must not be held.
147762695a84SNick Piggin  * (3) interrupts must be enabled.
147862695a84SNick Piggin  */
147962695a84SNick Piggin int isolate_lru_page(struct page *page)
148062695a84SNick Piggin {
148162695a84SNick Piggin 	int ret = -EBUSY;
148262695a84SNick Piggin 
1483309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1484cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
14850c917313SKonstantin Khlebnikov 
148662695a84SNick Piggin 	if (PageLRU(page)) {
148762695a84SNick Piggin 		struct zone *zone = page_zone(page);
1488fa9add64SHugh Dickins 		struct lruvec *lruvec;
148962695a84SNick Piggin 
1490a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1491599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
14920c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1493894bc310SLee Schermerhorn 			int lru = page_lru(page);
14940c917313SKonstantin Khlebnikov 			get_page(page);
149562695a84SNick Piggin 			ClearPageLRU(page);
1496fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1497fa9add64SHugh Dickins 			ret = 0;
149862695a84SNick Piggin 		}
1499a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
150062695a84SNick Piggin 	}
150162695a84SNick Piggin 	return ret;
150262695a84SNick Piggin }
150362695a84SNick Piggin 
15045ad333ebSAndy Whitcroft /*
1505d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1506d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1507d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1508d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1509d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
151035cd7815SRik van Riel  */
1511599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
151235cd7815SRik van Riel 		struct scan_control *sc)
151335cd7815SRik van Riel {
151435cd7815SRik van Riel 	unsigned long inactive, isolated;
151535cd7815SRik van Riel 
151635cd7815SRik van Riel 	if (current_is_kswapd())
151735cd7815SRik van Riel 		return 0;
151835cd7815SRik van Riel 
151997c9341fSTejun Heo 	if (!sane_reclaim(sc))
152035cd7815SRik van Riel 		return 0;
152135cd7815SRik van Riel 
152235cd7815SRik van Riel 	if (file) {
1523599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1524599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
152535cd7815SRik van Riel 	} else {
1526599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1527599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
152835cd7815SRik van Riel 	}
152935cd7815SRik van Riel 
15303cf23841SFengguang Wu 	/*
15313cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
15323cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
15333cf23841SFengguang Wu 	 * deadlock.
15343cf23841SFengguang Wu 	 */
1535d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
15363cf23841SFengguang Wu 		inactive >>= 3;
15373cf23841SFengguang Wu 
153835cd7815SRik van Riel 	return isolated > inactive;
153935cd7815SRik van Riel }
154035cd7815SRik van Riel 
154166635629SMel Gorman static noinline_for_stack void
154275b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
154366635629SMel Gorman {
154427ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1545599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
15463f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
154766635629SMel Gorman 
154866635629SMel Gorman 	/*
154966635629SMel Gorman 	 * Put back any unfreeable pages.
155066635629SMel Gorman 	 */
155166635629SMel Gorman 	while (!list_empty(page_list)) {
15523f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
155366635629SMel Gorman 		int lru;
15543f79768fSHugh Dickins 
1555309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
155666635629SMel Gorman 		list_del(&page->lru);
155739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1558599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
155966635629SMel Gorman 			putback_lru_page(page);
1560599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
156166635629SMel Gorman 			continue;
156266635629SMel Gorman 		}
1563fa9add64SHugh Dickins 
1564599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1565fa9add64SHugh Dickins 
15667a608572SLinus Torvalds 		SetPageLRU(page);
156766635629SMel Gorman 		lru = page_lru(page);
1568fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1569fa9add64SHugh Dickins 
157066635629SMel Gorman 		if (is_active_lru(lru)) {
157166635629SMel Gorman 			int file = is_file_lru(lru);
15729992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
15739992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
157466635629SMel Gorman 		}
15752bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
15762bcf8879SHugh Dickins 			__ClearPageLRU(page);
15772bcf8879SHugh Dickins 			__ClearPageActive(page);
1578fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
15792bcf8879SHugh Dickins 
15802bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1581599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1582747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
15832bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1584599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
15852bcf8879SHugh Dickins 			} else
15862bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
158766635629SMel Gorman 		}
158866635629SMel Gorman 	}
158966635629SMel Gorman 
15903f79768fSHugh Dickins 	/*
15913f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
15923f79768fSHugh Dickins 	 */
15933f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
159466635629SMel Gorman }
159566635629SMel Gorman 
159666635629SMel Gorman /*
1597399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1598399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1599399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1600399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1601399ba0b9SNeilBrown  */
1602399ba0b9SNeilBrown static int current_may_throttle(void)
1603399ba0b9SNeilBrown {
1604399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1605399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1606399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1607399ba0b9SNeilBrown }
1608399ba0b9SNeilBrown 
1609399ba0b9SNeilBrown /*
1610b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16111742f19fSAndrew Morton  * of reclaimed pages
16121da177e4SLinus Torvalds  */
161366635629SMel Gorman static noinline_for_stack unsigned long
16141a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
16159e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
16161da177e4SLinus Torvalds {
16171da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1618e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
161905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1620e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
16218e950282SMel Gorman 	unsigned long nr_dirty = 0;
16228e950282SMel Gorman 	unsigned long nr_congested = 0;
1623e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
162492df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1625b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1626f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16273cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1628599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16291a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
163078dc583dSKOSAKI Motohiro 
1631599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
163258355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
163335cd7815SRik van Riel 
163435cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
163535cd7815SRik van Riel 		if (fatal_signal_pending(current))
163635cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
163735cd7815SRik van Riel 	}
163835cd7815SRik van Riel 
16391da177e4SLinus Torvalds 	lru_add_drain();
1640f80c0673SMinchan Kim 
1641f80c0673SMinchan Kim 	if (!sc->may_unmap)
164261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1643f80c0673SMinchan Kim 	if (!sc->may_writepage)
164461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1645f80c0673SMinchan Kim 
1646599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
16471da177e4SLinus Torvalds 
16485dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
16495dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
165095d918fcSKonstantin Khlebnikov 
1651599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
16529d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
165395d918fcSKonstantin Khlebnikov 
165489b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1655599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1656b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1657599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
1658b35ea17bSKOSAKI Motohiro 		else
1659599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
1660b35ea17bSKOSAKI Motohiro 	}
1661599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1662d563c050SHillf Danton 
1663d563c050SHillf Danton 	if (nr_taken == 0)
166466635629SMel Gorman 		return 0;
1665b35ea17bSKOSAKI Motohiro 
1666599d0c95SMel Gorman 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, TTU_UNMAP,
16678e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
16688e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1669b1a6f21eSMel Gorman 				false);
1670c661b078SAndy Whitcroft 
1671599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
16723f79768fSHugh Dickins 
1673904249aaSYing Han 	if (global_reclaim(sc)) {
1674b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1675599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
1676904249aaSYing Han 		else
1677599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
1678904249aaSYing Han 	}
1679a74609faSNick Piggin 
168027ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
16813f79768fSHugh Dickins 
1682599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
16833f79768fSHugh Dickins 
1684599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
16853f79768fSHugh Dickins 
1686747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1687b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1688e11da5b4SMel Gorman 
168992df3a72SMel Gorman 	/*
169092df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
169192df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
169292df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
169392df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
169492df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
169592df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
169692df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
169792df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
169892df3a72SMel Gorman 	 *
16998e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
17008e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17018e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
170292df3a72SMel Gorman 	 */
1703918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1704599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
170592df3a72SMel Gorman 
1706d43006d5SMel Gorman 	/*
170797c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
170897c9341fSTejun Heo 	 * stalling here.
1709d43006d5SMel Gorman 	 */
171097c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1711b1a6f21eSMel Gorman 		/*
17128e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
17138e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
17148e950282SMel Gorman 		 */
17158e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
1716599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
17178e950282SMel Gorman 
17188e950282SMel Gorman 		/*
1719b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1720b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1721599d0c95SMel Gorman 		 * the pgdat PGDAT_DIRTY and kswapd will start writing pages from
172257054651SJohannes Weiner 		 * reclaim context.
1723b1a6f21eSMel Gorman 		 */
1724b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1725599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1726b1a6f21eSMel Gorman 
1727b1a6f21eSMel Gorman 		/*
1728b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1729b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1730b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1731b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1732b1a6f21eSMel Gorman 		 */
1733b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1734b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1735e2be15f6SMel Gorman 	}
1736d43006d5SMel Gorman 
17378e950282SMel Gorman 	/*
17388e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
17398e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
17408e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
17418e950282SMel Gorman 	 */
1742399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1743399ba0b9SNeilBrown 	    current_may_throttle())
1744599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
17458e950282SMel Gorman 
1746599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1747599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
1748ba5e9579Syalin wang 			sc->priority, file);
174905ff5137SAndrew Morton 	return nr_reclaimed;
17501da177e4SLinus Torvalds }
17511da177e4SLinus Torvalds 
17523bb1a852SMartin Bligh /*
17531cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
17541cfb419bSKAMEZAWA Hiroyuki  *
17551cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
17561cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
17571cfb419bSKAMEZAWA Hiroyuki  *
17581cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1759a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
17601cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1761a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
17621cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
17631cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
17641cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
17651cfb419bSKAMEZAWA Hiroyuki  *
17660139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
17671cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
17681cfb419bSKAMEZAWA Hiroyuki  */
17691cfb419bSKAMEZAWA Hiroyuki 
1770fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
17713eb4140fSWu Fengguang 				     struct list_head *list,
17722bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
17733eb4140fSWu Fengguang 				     enum lru_list lru)
17743eb4140fSWu Fengguang {
1775599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17763eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
17773eb4140fSWu Fengguang 	struct page *page;
1778fa9add64SHugh Dickins 	int nr_pages;
17793eb4140fSWu Fengguang 
17803eb4140fSWu Fengguang 	while (!list_empty(list)) {
17813eb4140fSWu Fengguang 		page = lru_to_page(list);
1782599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17833eb4140fSWu Fengguang 
1784309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
17853eb4140fSWu Fengguang 		SetPageLRU(page);
17863eb4140fSWu Fengguang 
1787fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1788599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1789925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1790fa9add64SHugh Dickins 		pgmoved += nr_pages;
17913eb4140fSWu Fengguang 
17922bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
17932bcf8879SHugh Dickins 			__ClearPageLRU(page);
17942bcf8879SHugh Dickins 			__ClearPageActive(page);
1795fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
17962bcf8879SHugh Dickins 
17972bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1798599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1799747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18002bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1801599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18022bcf8879SHugh Dickins 			} else
18032bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18043eb4140fSWu Fengguang 		}
18053eb4140fSWu Fengguang 	}
18069d5e6a9fSHugh Dickins 
18073eb4140fSWu Fengguang 	if (!is_active_lru(lru))
18083eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
18093eb4140fSWu Fengguang }
18101cfb419bSKAMEZAWA Hiroyuki 
1811f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
18121a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1813f16015fbSJohannes Weiner 			       struct scan_control *sc,
18149e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
18151cfb419bSKAMEZAWA Hiroyuki {
181644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1817f626012dSHugh Dickins 	unsigned long nr_scanned;
18186fe6b7e3SWu Fengguang 	unsigned long vm_flags;
18191cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
18208cab4754SWu Fengguang 	LIST_HEAD(l_active);
1821b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
18221cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
18231a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
182444c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1825f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
18263cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1827599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18281cfb419bSKAMEZAWA Hiroyuki 
18291da177e4SLinus Torvalds 	lru_add_drain();
1830f80c0673SMinchan Kim 
1831f80c0673SMinchan Kim 	if (!sc->may_unmap)
183261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1833f80c0673SMinchan Kim 	if (!sc->may_writepage)
183461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1835f80c0673SMinchan Kim 
1836599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1837925b7673SJohannes Weiner 
18385dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
18395dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
184089b5fae5SJohannes Weiner 
1841599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1842b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
18431cfb419bSKAMEZAWA Hiroyuki 
18449d5e6a9fSHugh Dickins 	if (global_reclaim(sc))
1845599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1846599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
18479d5e6a9fSHugh Dickins 
1848599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
18491da177e4SLinus Torvalds 
18501da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
18511da177e4SLinus Torvalds 		cond_resched();
18521da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
18531da177e4SLinus Torvalds 		list_del(&page->lru);
18547e9cd484SRik van Riel 
185539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1856894bc310SLee Schermerhorn 			putback_lru_page(page);
1857894bc310SLee Schermerhorn 			continue;
1858894bc310SLee Schermerhorn 		}
1859894bc310SLee Schermerhorn 
1860cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1861cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1862cc715d99SMel Gorman 				if (page_has_private(page))
1863cc715d99SMel Gorman 					try_to_release_page(page, 0);
1864cc715d99SMel Gorman 				unlock_page(page);
1865cc715d99SMel Gorman 			}
1866cc715d99SMel Gorman 		}
1867cc715d99SMel Gorman 
1868c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1869c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
18709992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
18718cab4754SWu Fengguang 			/*
18728cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
18738cab4754SWu Fengguang 			 * give them one more trip around the active list. So
18748cab4754SWu Fengguang 			 * that executable code get better chances to stay in
18758cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
18768cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
18778cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
18788cab4754SWu Fengguang 			 * so we ignore them here.
18798cab4754SWu Fengguang 			 */
188041e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
18818cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
18828cab4754SWu Fengguang 				continue;
18838cab4754SWu Fengguang 			}
18848cab4754SWu Fengguang 		}
18857e9cd484SRik van Riel 
18865205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
18871da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
18881da177e4SLinus Torvalds 	}
18891da177e4SLinus Torvalds 
1890b555749aSAndrew Morton 	/*
18918cab4754SWu Fengguang 	 * Move pages back to the lru list.
1892b555749aSAndrew Morton 	 */
1893599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
18944f98a2feSRik van Riel 	/*
18958cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
18968cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
18978cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
18987c0db9e9SJerome Marchand 	 * get_scan_count.
1899556adecbSRik van Riel 	 */
1900b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1901556adecbSRik van Riel 
1902fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1903fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1904599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1905599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19062bcf8879SHugh Dickins 
1907747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1908b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
19091da177e4SLinus Torvalds }
19101da177e4SLinus Torvalds 
191159dc76b0SRik van Riel /*
191259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
191359dc76b0SRik van Riel  * to do too much work.
191414797e23SKOSAKI Motohiro  *
191559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
191659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
191759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
191859dc76b0SRik van Riel  *
191959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
192059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
192159dc76b0SRik van Riel  *
192259dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
192359dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
192459dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
192559dc76b0SRik van Riel  *
192659dc76b0SRik van Riel  * total     target    max
192759dc76b0SRik van Riel  * memory    ratio     inactive
192859dc76b0SRik van Riel  * -------------------------------------
192959dc76b0SRik van Riel  *   10MB       1         5MB
193059dc76b0SRik van Riel  *  100MB       1        50MB
193159dc76b0SRik van Riel  *    1GB       3       250MB
193259dc76b0SRik van Riel  *   10GB      10       0.9GB
193359dc76b0SRik van Riel  *  100GB      31         3GB
193459dc76b0SRik van Riel  *    1TB     101        10GB
193559dc76b0SRik van Riel  *   10TB     320        32GB
193614797e23SKOSAKI Motohiro  */
193759dc76b0SRik van Riel static bool inactive_list_is_low(struct lruvec *lruvec, bool file)
193814797e23SKOSAKI Motohiro {
193959dc76b0SRik van Riel 	unsigned long inactive_ratio;
194059dc76b0SRik van Riel 	unsigned long inactive;
194159dc76b0SRik van Riel 	unsigned long active;
194259dc76b0SRik van Riel 	unsigned long gb;
194359dc76b0SRik van Riel 
194474e3f3c3SMinchan Kim 	/*
194574e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
194674e3f3c3SMinchan Kim 	 * is pointless.
194774e3f3c3SMinchan Kim 	 */
194859dc76b0SRik van Riel 	if (!file && !total_swap_pages)
194942e2e457SYaowei Bai 		return false;
195074e3f3c3SMinchan Kim 
195159dc76b0SRik van Riel 	inactive = lruvec_lru_size(lruvec, file * LRU_FILE);
195259dc76b0SRik van Riel 	active = lruvec_lru_size(lruvec, file * LRU_FILE + LRU_ACTIVE);
1953f16015fbSJohannes Weiner 
195459dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
195559dc76b0SRik van Riel 	if (gb)
195659dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
1957b39415b2SRik van Riel 	else
195859dc76b0SRik van Riel 		inactive_ratio = 1;
195959dc76b0SRik van Riel 
196059dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
1961b39415b2SRik van Riel }
1962b39415b2SRik van Riel 
19634f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
19641a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1965b69408e8SChristoph Lameter {
1966b39415b2SRik van Riel 	if (is_active_lru(lru)) {
196759dc76b0SRik van Riel 		if (inactive_list_is_low(lruvec, is_file_lru(lru)))
19681a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1969556adecbSRik van Riel 		return 0;
1970556adecbSRik van Riel 	}
1971556adecbSRik van Riel 
19721a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1973b69408e8SChristoph Lameter }
1974b69408e8SChristoph Lameter 
19759a265114SJohannes Weiner enum scan_balance {
19769a265114SJohannes Weiner 	SCAN_EQUAL,
19779a265114SJohannes Weiner 	SCAN_FRACT,
19789a265114SJohannes Weiner 	SCAN_ANON,
19799a265114SJohannes Weiner 	SCAN_FILE,
19809a265114SJohannes Weiner };
19819a265114SJohannes Weiner 
19821da177e4SLinus Torvalds /*
19834f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
19844f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
19854f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
19864f98a2feSRik van Riel  * onto the active list instead of evict.
19874f98a2feSRik van Riel  *
1988be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1989be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
19904f98a2feSRik van Riel  */
199133377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
19926b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
19936b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
19944f98a2feSRik van Riel {
199533377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
199690126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19979a265114SJohannes Weiner 	u64 fraction[2];
19989a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
1999599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20009a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
20019a265114SJohannes Weiner 	enum scan_balance scan_balance;
20020bf1457fSJohannes Weiner 	unsigned long anon, file;
20039a265114SJohannes Weiner 	bool force_scan = false;
20049a265114SJohannes Weiner 	unsigned long ap, fp;
20059a265114SJohannes Weiner 	enum lru_list lru;
20066f04f48dSSuleiman Souhlal 	bool some_scanned;
20076f04f48dSSuleiman Souhlal 	int pass;
2008246e87a9SKAMEZAWA Hiroyuki 
2009f11c0ca5SJohannes Weiner 	/*
2010f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
2011f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
2012f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
2013f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
2014f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
2015f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
2016f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
2017f11c0ca5SJohannes Weiner 	 * well.
2018f11c0ca5SJohannes Weiner 	 */
201990cbc250SVladimir Davydov 	if (current_is_kswapd()) {
2020599d0c95SMel Gorman 		if (!pgdat_reclaimable(pgdat))
2021a4d3e9e7SJohannes Weiner 			force_scan = true;
2022eb01aaabSVladimir Davydov 		if (!mem_cgroup_online(memcg))
202390cbc250SVladimir Davydov 			force_scan = true;
202490cbc250SVladimir Davydov 	}
202589b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
2026a4d3e9e7SJohannes Weiner 		force_scan = true;
202776a33fc3SShaohua Li 
202876a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2029d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
20309a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
203176a33fc3SShaohua Li 		goto out;
203276a33fc3SShaohua Li 	}
20334f98a2feSRik van Riel 
203410316b31SJohannes Weiner 	/*
203510316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
203610316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
203710316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
203810316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
203910316b31SJohannes Weiner 	 * too expensive.
204010316b31SJohannes Weiner 	 */
204102695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
20429a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
204310316b31SJohannes Weiner 		goto out;
204410316b31SJohannes Weiner 	}
204510316b31SJohannes Weiner 
204610316b31SJohannes Weiner 	/*
204710316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
204810316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
204910316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
205010316b31SJohannes Weiner 	 */
205102695175SJohannes Weiner 	if (!sc->priority && swappiness) {
20529a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
205310316b31SJohannes Weiner 		goto out;
205410316b31SJohannes Weiner 	}
205510316b31SJohannes Weiner 
205611d16c25SJohannes Weiner 	/*
205762376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
205862376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
205962376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
206062376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
206162376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
206262376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
206362376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
206462376251SJohannes Weiner 	 */
206562376251SJohannes Weiner 	if (global_reclaim(sc)) {
2066599d0c95SMel Gorman 		unsigned long pgdatfile;
2067599d0c95SMel Gorman 		unsigned long pgdatfree;
2068599d0c95SMel Gorman 		int z;
2069599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
207062376251SJohannes Weiner 
2071599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2072599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2073599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
20742ab051e1SJerome Marchand 
2075599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2076599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
2077599d0c95SMel Gorman 			if (!populated_zone(zone))
2078599d0c95SMel Gorman 				continue;
2079599d0c95SMel Gorman 
2080599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2081599d0c95SMel Gorman 		}
2082599d0c95SMel Gorman 
2083599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
208462376251SJohannes Weiner 			scan_balance = SCAN_ANON;
208562376251SJohannes Weiner 			goto out;
208662376251SJohannes Weiner 		}
208762376251SJohannes Weiner 	}
208862376251SJohannes Weiner 
208962376251SJohannes Weiner 	/*
2090316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2091316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2092316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2093316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2094316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2095316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2096316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2097e9868505SRik van Riel 	 */
209859dc76b0SRik van Riel 	if (!inactive_list_is_low(lruvec, true) &&
209923047a96SJohannes Weiner 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
21009a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2101e9868505SRik van Riel 		goto out;
21024f98a2feSRik van Riel 	}
21034f98a2feSRik van Riel 
21049a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
21059a265114SJohannes Weiner 
21064f98a2feSRik van Riel 	/*
210758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
210858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
210958c37f6eSKOSAKI Motohiro 	 */
211002695175SJohannes Weiner 	anon_prio = swappiness;
211175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
211258c37f6eSKOSAKI Motohiro 
211358c37f6eSKOSAKI Motohiro 	/*
21144f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
21154f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
21164f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
21174f98a2feSRik van Riel 	 *
21184f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
21194f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
21204f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
21214f98a2feSRik van Riel 	 *
21224f98a2feSRik van Riel 	 * anon in [0], file in [1]
21234f98a2feSRik van Riel 	 */
21242ab051e1SJerome Marchand 
212523047a96SJohannes Weiner 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
212623047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
212723047a96SJohannes Weiner 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
212823047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
21292ab051e1SJerome Marchand 
2130599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
213158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
21326e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
21336e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
21344f98a2feSRik van Riel 	}
21354f98a2feSRik van Riel 
21366e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
21376e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
21386e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
21394f98a2feSRik van Riel 	}
21404f98a2feSRik van Riel 
21414f98a2feSRik van Riel 	/*
214200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
214300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
214400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
21454f98a2feSRik van Riel 	 */
2146fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
21476e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
21484f98a2feSRik van Riel 
2149fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
21506e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2151599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21524f98a2feSRik van Riel 
215376a33fc3SShaohua Li 	fraction[0] = ap;
215476a33fc3SShaohua Li 	fraction[1] = fp;
215576a33fc3SShaohua Li 	denominator = ap + fp + 1;
215676a33fc3SShaohua Li out:
21576f04f48dSSuleiman Souhlal 	some_scanned = false;
21586f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
21596f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
21606b4f7799SJohannes Weiner 		*lru_pages = 0;
21614111304dSHugh Dickins 		for_each_evictable_lru(lru) {
21624111304dSHugh Dickins 			int file = is_file_lru(lru);
2163d778df51SJohannes Weiner 			unsigned long size;
216476a33fc3SShaohua Li 			unsigned long scan;
216576a33fc3SShaohua Li 
216623047a96SJohannes Weiner 			size = lruvec_lru_size(lruvec, lru);
2167d778df51SJohannes Weiner 			scan = size >> sc->priority;
21689a265114SJohannes Weiner 
21696f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2170d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
21719a265114SJohannes Weiner 
21729a265114SJohannes Weiner 			switch (scan_balance) {
21739a265114SJohannes Weiner 			case SCAN_EQUAL:
21749a265114SJohannes Weiner 				/* Scan lists relative to size */
21759a265114SJohannes Weiner 				break;
21769a265114SJohannes Weiner 			case SCAN_FRACT:
21779a265114SJohannes Weiner 				/*
21789a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
21799a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
21809a265114SJohannes Weiner 				 */
21816f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
21826f04f48dSSuleiman Souhlal 							denominator);
21839a265114SJohannes Weiner 				break;
21849a265114SJohannes Weiner 			case SCAN_FILE:
21859a265114SJohannes Weiner 			case SCAN_ANON:
21869a265114SJohannes Weiner 				/* Scan one type exclusively */
21876b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
21886b4f7799SJohannes Weiner 					size = 0;
21899a265114SJohannes Weiner 					scan = 0;
21906b4f7799SJohannes Weiner 				}
21919a265114SJohannes Weiner 				break;
21929a265114SJohannes Weiner 			default:
21939a265114SJohannes Weiner 				/* Look ma, no brain */
21949a265114SJohannes Weiner 				BUG();
21959a265114SJohannes Weiner 			}
21966b4f7799SJohannes Weiner 
21976b4f7799SJohannes Weiner 			*lru_pages += size;
21984111304dSHugh Dickins 			nr[lru] = scan;
21996b4f7799SJohannes Weiner 
22006f04f48dSSuleiman Souhlal 			/*
22016f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
22026f04f48dSSuleiman Souhlal 			 * if we found something to scan.
22036f04f48dSSuleiman Souhlal 			 */
22046f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
22056f04f48dSSuleiman Souhlal 		}
220676a33fc3SShaohua Li 	}
22076e08a369SWu Fengguang }
22084f98a2feSRik van Riel 
220972b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
221072b252aeSMel Gorman static void init_tlb_ubc(void)
221172b252aeSMel Gorman {
221272b252aeSMel Gorman 	/*
221372b252aeSMel Gorman 	 * This deliberately does not clear the cpumask as it's expensive
221472b252aeSMel Gorman 	 * and unnecessary. If there happens to be data in there then the
221572b252aeSMel Gorman 	 * first SWAP_CLUSTER_MAX pages will send an unnecessary IPI and
221672b252aeSMel Gorman 	 * then will be cleared.
221772b252aeSMel Gorman 	 */
221872b252aeSMel Gorman 	current->tlb_ubc.flush_required = false;
221972b252aeSMel Gorman }
222072b252aeSMel Gorman #else
222172b252aeSMel Gorman static inline void init_tlb_ubc(void)
222272b252aeSMel Gorman {
222372b252aeSMel Gorman }
222472b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
222572b252aeSMel Gorman 
22269b4f98cdSJohannes Weiner /*
22279b4f98cdSJohannes Weiner  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
22289b4f98cdSJohannes Weiner  */
222933377678SVladimir Davydov static void shrink_zone_memcg(struct zone *zone, struct mem_cgroup *memcg,
22306b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
22319b4f98cdSJohannes Weiner {
223233377678SVladimir Davydov 	struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
22339b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2234e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
22359b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
22369b4f98cdSJohannes Weiner 	enum lru_list lru;
22379b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
22389b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
22399b4f98cdSJohannes Weiner 	struct blk_plug plug;
22401a501907SMel Gorman 	bool scan_adjusted;
22419b4f98cdSJohannes Weiner 
224233377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
22439b4f98cdSJohannes Weiner 
2244e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2245e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2246e82e0561SMel Gorman 
22471a501907SMel Gorman 	/*
22481a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
22491a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
22501a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
22511a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
22521a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
22531a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
22541a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
22551a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
22561a501907SMel Gorman 	 * dropped to zero at the first pass.
22571a501907SMel Gorman 	 */
22581a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
22591a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
22601a501907SMel Gorman 
226172b252aeSMel Gorman 	init_tlb_ubc();
226272b252aeSMel Gorman 
22639b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
22649b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
22659b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2266e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2267e82e0561SMel Gorman 		unsigned long nr_scanned;
2268e82e0561SMel Gorman 
22699b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
22709b4f98cdSJohannes Weiner 			if (nr[lru]) {
22719b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
22729b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
22739b4f98cdSJohannes Weiner 
22749b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
22759b4f98cdSJohannes Weiner 							    lruvec, sc);
22769b4f98cdSJohannes Weiner 			}
22779b4f98cdSJohannes Weiner 		}
2278e82e0561SMel Gorman 
2279e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2280e82e0561SMel Gorman 			continue;
2281e82e0561SMel Gorman 
22829b4f98cdSJohannes Weiner 		/*
2283e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
22841a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2285e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2286e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2287e82e0561SMel Gorman 		 * proportional to the original scan target.
2288e82e0561SMel Gorman 		 */
2289e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2290e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2291e82e0561SMel Gorman 
22921a501907SMel Gorman 		/*
22931a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
22941a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
22951a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
22961a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
22971a501907SMel Gorman 		 */
22981a501907SMel Gorman 		if (!nr_file || !nr_anon)
22991a501907SMel Gorman 			break;
23001a501907SMel Gorman 
2301e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2302e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2303e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2304e82e0561SMel Gorman 			lru = LRU_BASE;
2305e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2306e82e0561SMel Gorman 		} else {
2307e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2308e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2309e82e0561SMel Gorman 			lru = LRU_FILE;
2310e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2311e82e0561SMel Gorman 		}
2312e82e0561SMel Gorman 
2313e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2314e82e0561SMel Gorman 		nr[lru] = 0;
2315e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2316e82e0561SMel Gorman 
2317e82e0561SMel Gorman 		/*
2318e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2319e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2320e82e0561SMel Gorman 		 */
2321e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2322e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2323e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2324e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2325e82e0561SMel Gorman 
2326e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2327e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2328e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2329e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2330e82e0561SMel Gorman 
2331e82e0561SMel Gorman 		scan_adjusted = true;
23329b4f98cdSJohannes Weiner 	}
23339b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
23349b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
23359b4f98cdSJohannes Weiner 
23369b4f98cdSJohannes Weiner 	/*
23379b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
23389b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
23399b4f98cdSJohannes Weiner 	 */
234059dc76b0SRik van Riel 	if (inactive_list_is_low(lruvec, false))
23419b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
23429b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
23439b4f98cdSJohannes Weiner 
23449b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
23459b4f98cdSJohannes Weiner }
23469b4f98cdSJohannes Weiner 
234723b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
23489e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
234923b9da55SMel Gorman {
2350d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
235123b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
23529e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
235323b9da55SMel Gorman 		return true;
235423b9da55SMel Gorman 
235523b9da55SMel Gorman 	return false;
235623b9da55SMel Gorman }
235723b9da55SMel Gorman 
23584f98a2feSRik van Riel /*
235923b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
236023b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
236123b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
236223b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
236323b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
23643e7d3449SMel Gorman  */
23659b4f98cdSJohannes Weiner static inline bool should_continue_reclaim(struct zone *zone,
23663e7d3449SMel Gorman 					unsigned long nr_reclaimed,
23673e7d3449SMel Gorman 					unsigned long nr_scanned,
23683e7d3449SMel Gorman 					struct scan_control *sc)
23693e7d3449SMel Gorman {
23703e7d3449SMel Gorman 	unsigned long pages_for_compaction;
23713e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
23723e7d3449SMel Gorman 
23733e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
23749e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
23753e7d3449SMel Gorman 		return false;
23763e7d3449SMel Gorman 
23772876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
23782876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
23793e7d3449SMel Gorman 		/*
23802876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
23812876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
23822876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
23832876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
23843e7d3449SMel Gorman 		 */
23853e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
23863e7d3449SMel Gorman 			return false;
23872876592fSMel Gorman 	} else {
23882876592fSMel Gorman 		/*
23892876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
23902876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
23912876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
23922876592fSMel Gorman 		 * pages that were scanned. This will return to the
23932876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
23942876592fSMel Gorman 		 * the resulting allocation attempt fails
23952876592fSMel Gorman 		 */
23962876592fSMel Gorman 		if (!nr_reclaimed)
23972876592fSMel Gorman 			return false;
23982876592fSMel Gorman 	}
23993e7d3449SMel Gorman 
24003e7d3449SMel Gorman 	/*
24013e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24023e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24033e7d3449SMel Gorman 	 */
24043e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
2405599d0c95SMel Gorman 	inactive_lru_pages = node_page_state(zone->zone_pgdat, NR_INACTIVE_FILE);
2406ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2407599d0c95SMel Gorman 		inactive_lru_pages += node_page_state(zone->zone_pgdat, NR_INACTIVE_ANON);
24083e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24093e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24103e7d3449SMel Gorman 		return true;
24113e7d3449SMel Gorman 
24123e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2413ebff3980SVlastimil Babka 	switch (compaction_suitable(zone, sc->order, 0, 0)) {
24143e7d3449SMel Gorman 	case COMPACT_PARTIAL:
24153e7d3449SMel Gorman 	case COMPACT_CONTINUE:
24163e7d3449SMel Gorman 		return false;
24173e7d3449SMel Gorman 	default:
24183e7d3449SMel Gorman 		return true;
24193e7d3449SMel Gorman 	}
24203e7d3449SMel Gorman }
24213e7d3449SMel Gorman 
2422b2e18757SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc,
2423b2e18757SMel Gorman 			enum zone_type classzone_idx)
2424f16015fbSJohannes Weiner {
2425cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
24269b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
24272344d7e4SJohannes Weiner 	bool reclaimable = false;
2428b2e18757SMel Gorman 	struct zone *zone = &pgdat->node_zones[classzone_idx];
24299b4f98cdSJohannes Weiner 
24309b4f98cdSJohannes Weiner 	do {
24315660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
24325660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
24335660048cSJohannes Weiner 			.zone = zone,
24349e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
24355660048cSJohannes Weiner 		};
24366b4f7799SJohannes Weiner 		unsigned long zone_lru_pages = 0;
2437694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
24385660048cSJohannes Weiner 
24399b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
24409b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
24419b4f98cdSJohannes Weiner 
2442694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2443694fbc0fSAndrew Morton 		do {
24446b4f7799SJohannes Weiner 			unsigned long lru_pages;
24458e8ae645SJohannes Weiner 			unsigned long reclaimed;
2446cb731d6cSVladimir Davydov 			unsigned long scanned;
24479b4f98cdSJohannes Weiner 
2448241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2449241994edSJohannes Weiner 				if (!sc->may_thrash)
2450241994edSJohannes Weiner 					continue;
2451241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2452241994edSJohannes Weiner 			}
2453241994edSJohannes Weiner 
24548e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2455cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
24565660048cSJohannes Weiner 
245733377678SVladimir Davydov 			shrink_zone_memcg(zone, memcg, sc, &lru_pages);
24586b4f7799SJohannes Weiner 			zone_lru_pages += lru_pages;
2459f9be23d6SKonstantin Khlebnikov 
2460b2e18757SMel Gorman 			if (!global_reclaim(sc))
2461cb731d6cSVladimir Davydov 				shrink_slab(sc->gfp_mask, zone_to_nid(zone),
2462cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2463cb731d6cSVladimir Davydov 					    lru_pages);
2464cb731d6cSVladimir Davydov 
24658e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
24668e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
24678e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
24688e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
24698e8ae645SJohannes Weiner 
24705660048cSJohannes Weiner 			/*
2471a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2472a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
24739b4f98cdSJohannes Weiner 			 * zone.
2474a394cb8eSMichal Hocko 			 *
2475a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2476a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2477a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2478a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
24795660048cSJohannes Weiner 			 */
2480a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2481a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
24825660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
24835660048cSJohannes Weiner 				break;
24845660048cSJohannes Weiner 			}
2485241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
248670ddf637SAnton Vorontsov 
24876b4f7799SJohannes Weiner 		/*
24886b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
24896b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
24906b4f7799SJohannes Weiner 		 */
2491b2e18757SMel Gorman 		if (global_reclaim(sc))
2492cb731d6cSVladimir Davydov 			shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL,
24936b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
24946b4f7799SJohannes Weiner 				    zone_lru_pages);
24956b4f7799SJohannes Weiner 
24966b4f7799SJohannes Weiner 		if (reclaim_state) {
2497cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
24986b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
24996b4f7799SJohannes Weiner 		}
25006b4f7799SJohannes Weiner 
25018e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25028e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
250370ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
250470ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
250570ddf637SAnton Vorontsov 
25062344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
25072344d7e4SJohannes Weiner 			reclaimable = true;
25082344d7e4SJohannes Weiner 
25099b4f98cdSJohannes Weiner 	} while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
25109b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
25112344d7e4SJohannes Weiner 
25122344d7e4SJohannes Weiner 	return reclaimable;
2513f16015fbSJohannes Weiner }
2514f16015fbSJohannes Weiner 
251553853e2dSVlastimil Babka /*
251653853e2dSVlastimil Babka  * Returns true if compaction should go ahead for a high-order request, or
251753853e2dSVlastimil Babka  * the high-order allocation would succeed without compaction.
251853853e2dSVlastimil Babka  */
2519b6459cc1SMichal Hocko static inline bool compaction_ready(struct zone *zone, int order, int classzone_idx)
2520fe4b1b24SMel Gorman {
2521fe4b1b24SMel Gorman 	unsigned long balance_gap, watermark;
2522fe4b1b24SMel Gorman 	bool watermark_ok;
2523fe4b1b24SMel Gorman 
2524fe4b1b24SMel Gorman 	/*
2525fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2526fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2527fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2528fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2529fe4b1b24SMel Gorman 	 */
25304be89a34SJianyu Zhan 	balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
25314be89a34SJianyu Zhan 			zone->managed_pages, KSWAPD_ZONE_BALANCE_GAP_RATIO));
25320b06496aSJohannes Weiner 	watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
2533b6459cc1SMichal Hocko 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, classzone_idx);
2534fe4b1b24SMel Gorman 
2535fe4b1b24SMel Gorman 	/*
2536fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2537fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2538fe4b1b24SMel Gorman 	 */
25390b06496aSJohannes Weiner 	if (compaction_deferred(zone, order))
2540fe4b1b24SMel Gorman 		return watermark_ok;
2541fe4b1b24SMel Gorman 
254253853e2dSVlastimil Babka 	/*
254353853e2dSVlastimil Babka 	 * If compaction is not ready to start and allocation is not likely
254453853e2dSVlastimil Babka 	 * to succeed without it, then keep reclaiming.
254553853e2dSVlastimil Babka 	 */
2546b6459cc1SMichal Hocko 	if (compaction_suitable(zone, order, 0, classzone_idx) == COMPACT_SKIPPED)
2547fe4b1b24SMel Gorman 		return false;
2548fe4b1b24SMel Gorman 
2549fe4b1b24SMel Gorman 	return watermark_ok;
2550fe4b1b24SMel Gorman }
2551fe4b1b24SMel Gorman 
25521da177e4SLinus Torvalds /*
25531da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
25541da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
25551da177e4SLinus Torvalds  * request.
25561da177e4SLinus Torvalds  *
255741858966SMel Gorman  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
255841858966SMel Gorman  * Because:
25591da177e4SLinus Torvalds  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
25601da177e4SLinus Torvalds  *    allocation or
256141858966SMel Gorman  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
256241858966SMel Gorman  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
256341858966SMel Gorman  *    zone defense algorithm.
25641da177e4SLinus Torvalds  *
25651da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
25661da177e4SLinus Torvalds  * scan then give up on it.
25671da177e4SLinus Torvalds  */
25680a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
25691da177e4SLinus Torvalds {
2570dd1a239fSMel Gorman 	struct zoneref *z;
257154a6eb5cSMel Gorman 	struct zone *zone;
25720608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
25730608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2574619d0d76SWeijie Yang 	gfp_t orig_mask;
2575b2e18757SMel Gorman 	enum zone_type classzone_idx;
25761cfb419bSKAMEZAWA Hiroyuki 
2577cc715d99SMel Gorman 	/*
2578cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2579cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2580cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2581cc715d99SMel Gorman 	 */
2582619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2583b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2584cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
2585b2e18757SMel Gorman 		sc->reclaim_idx = classzone_idx = gfp_zone(sc->gfp_mask);
2586b2e18757SMel Gorman 	}
2587cc715d99SMel Gorman 
2588d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2589b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2590f3fe6512SCon Kolivas 		if (!populated_zone(zone))
25911da177e4SLinus Torvalds 			continue;
25926b4f7799SJohannes Weiner 
2593b2e18757SMel Gorman 		/*
2594b2e18757SMel Gorman 		 * Note that reclaim_idx does not change as it is the highest
2595b2e18757SMel Gorman 		 * zone reclaimed from which for empty zones is a no-op but
2596b2e18757SMel Gorman 		 * classzone_idx is used by shrink_node to test if the slabs
2597b2e18757SMel Gorman 		 * should be shrunk on a given node.
2598b2e18757SMel Gorman 		 */
2599b2e18757SMel Gorman 		classzone_idx = sc->reclaim_idx;
26006b4f7799SJohannes Weiner 		while (!populated_zone(zone->zone_pgdat->node_zones +
26016b4f7799SJohannes Weiner 							classzone_idx))
26026b4f7799SJohannes Weiner 			classzone_idx--;
26036b4f7799SJohannes Weiner 
26041cfb419bSKAMEZAWA Hiroyuki 		/*
26051cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26061cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26071cfb419bSKAMEZAWA Hiroyuki 		 */
260889b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2609344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2610344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26111da177e4SLinus Torvalds 				continue;
261265ec02cbSVladimir Davydov 
26136e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
2614599d0c95SMel Gorman 			    !pgdat_reclaimable(zone->zone_pgdat))
26151da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
26160b06496aSJohannes Weiner 
2617e0887c19SRik van Riel 			/*
2618e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2619e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2620e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2621e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2622e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2623c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2624c7cfa37bSCopot Alexandru 			 * page allocations.
2625e0887c19SRik van Riel 			 */
26260b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
26270b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
2628b2e18757SMel Gorman 			    zonelist_zone_idx(z) <= classzone_idx &&
2629b2e18757SMel Gorman 			    compaction_ready(zone, sc->order, classzone_idx)) {
26300b06496aSJohannes Weiner 				sc->compaction_ready = true;
2631e0887c19SRik van Riel 				continue;
2632e0887c19SRik van Riel 			}
26330b06496aSJohannes Weiner 
26340608f43dSAndrew Morton 			/*
26350608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
26360608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
26370608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
26380608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
26390608f43dSAndrew Morton 			 */
26400608f43dSAndrew Morton 			nr_soft_scanned = 0;
26410608f43dSAndrew Morton 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
26420608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
26430608f43dSAndrew Morton 						&nr_soft_scanned);
26440608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
26450608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2646ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2647ac34a1a3SKAMEZAWA Hiroyuki 		}
2648d149e3b2SYing Han 
2649b2e18757SMel Gorman 		shrink_node(zone->zone_pgdat, sc, classzone_idx);
26501da177e4SLinus Torvalds 	}
2651e0c23279SMel Gorman 
265265ec02cbSVladimir Davydov 	/*
2653619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2654619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2655619d0d76SWeijie Yang 	 */
2656619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
26571da177e4SLinus Torvalds }
26581da177e4SLinus Torvalds 
26591da177e4SLinus Torvalds /*
26601da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
26611da177e4SLinus Torvalds  *
26621da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
26631da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
26641da177e4SLinus Torvalds  *
26651da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
26661da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
26675b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
26685b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
26695b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
26705b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2671a41f24eaSNishanth Aravamudan  *
2672a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2673a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
26741da177e4SLinus Torvalds  */
2675dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
26763115cd91SVladimir Davydov 					  struct scan_control *sc)
26771da177e4SLinus Torvalds {
2678241994edSJohannes Weiner 	int initial_priority = sc->priority;
267969e05944SAndrew Morton 	unsigned long total_scanned = 0;
268022fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
2681241994edSJohannes Weiner retry:
2682873b4771SKeika Kobayashi 	delayacct_freepages_start();
2683873b4771SKeika Kobayashi 
268489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
2685f8891e5eSChristoph Lameter 		count_vm_event(ALLOCSTALL);
26861da177e4SLinus Torvalds 
26879e3b2f8cSKonstantin Khlebnikov 	do {
268870ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
268970ddf637SAnton Vorontsov 				sc->priority);
269066e1707bSBalbir Singh 		sc->nr_scanned = 0;
26910a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2692e0c23279SMel Gorman 
269366e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2694bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
26950b06496aSJohannes Weiner 			break;
26960b06496aSJohannes Weiner 
26970b06496aSJohannes Weiner 		if (sc->compaction_ready)
26980b06496aSJohannes Weiner 			break;
26991da177e4SLinus Torvalds 
27001da177e4SLinus Torvalds 		/*
27010e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27020e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27030e50ce3bSMinchan Kim 		 */
27040e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27050e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27060e50ce3bSMinchan Kim 
27070e50ce3bSMinchan Kim 		/*
27081da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
27091da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
27101da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
27111da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
27121da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
27131da177e4SLinus Torvalds 		 */
271422fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
271522fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
27160e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
27170e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
271866e1707bSBalbir Singh 			sc->may_writepage = 1;
27191da177e4SLinus Torvalds 		}
27200b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2721bb21c7ceSKOSAKI Motohiro 
2722873b4771SKeika Kobayashi 	delayacct_freepages_end();
2723873b4771SKeika Kobayashi 
2724bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2725bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2726bb21c7ceSKOSAKI Motohiro 
27270cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
27280b06496aSJohannes Weiner 	if (sc->compaction_ready)
27297335084dSMel Gorman 		return 1;
27307335084dSMel Gorman 
2731241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2732241994edSJohannes Weiner 	if (!sc->may_thrash) {
2733241994edSJohannes Weiner 		sc->priority = initial_priority;
2734241994edSJohannes Weiner 		sc->may_thrash = 1;
2735241994edSJohannes Weiner 		goto retry;
2736241994edSJohannes Weiner 	}
2737241994edSJohannes Weiner 
2738bb21c7ceSKOSAKI Motohiro 	return 0;
27391da177e4SLinus Torvalds }
27401da177e4SLinus Torvalds 
27415515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
27425515061dSMel Gorman {
27435515061dSMel Gorman 	struct zone *zone;
27445515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
27455515061dSMel Gorman 	unsigned long free_pages = 0;
27465515061dSMel Gorman 	int i;
27475515061dSMel Gorman 	bool wmark_ok;
27485515061dSMel Gorman 
27495515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
27505515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2751f012a84aSNishanth Aravamudan 		if (!populated_zone(zone) ||
2752599d0c95SMel Gorman 		    pgdat_reclaimable_pages(pgdat) == 0)
2753675becceSMel Gorman 			continue;
2754675becceSMel Gorman 
27555515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
27565515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
27575515061dSMel Gorman 	}
27585515061dSMel Gorman 
2759675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2760675becceSMel Gorman 	if (!pfmemalloc_reserve)
2761675becceSMel Gorman 		return true;
2762675becceSMel Gorman 
27635515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
27645515061dSMel Gorman 
27655515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
27665515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
27675515061dSMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx,
27685515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
27695515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
27705515061dSMel Gorman 	}
27715515061dSMel Gorman 
27725515061dSMel Gorman 	return wmark_ok;
27735515061dSMel Gorman }
27745515061dSMel Gorman 
27755515061dSMel Gorman /*
27765515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
27775515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
27785515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
277950694c28SMel Gorman  * when the low watermark is reached.
278050694c28SMel Gorman  *
278150694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
278250694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
27835515061dSMel Gorman  */
278450694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
27855515061dSMel Gorman 					nodemask_t *nodemask)
27865515061dSMel Gorman {
2787675becceSMel Gorman 	struct zoneref *z;
27885515061dSMel Gorman 	struct zone *zone;
2789675becceSMel Gorman 	pg_data_t *pgdat = NULL;
27905515061dSMel Gorman 
27915515061dSMel Gorman 	/*
27925515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
27935515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
27945515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
27955515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
27965515061dSMel Gorman 	 * processes to block on log_wait_commit().
27975515061dSMel Gorman 	 */
27985515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
279950694c28SMel Gorman 		goto out;
280050694c28SMel Gorman 
280150694c28SMel Gorman 	/*
280250694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
280350694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
280450694c28SMel Gorman 	 */
280550694c28SMel Gorman 	if (fatal_signal_pending(current))
280650694c28SMel Gorman 		goto out;
28075515061dSMel Gorman 
2808675becceSMel Gorman 	/*
2809675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2810675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2811675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2812675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2813675becceSMel Gorman 	 *
2814675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2815675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2816675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2817675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2818675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2819675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2820675becceSMel Gorman 	 * should make reasonable progress.
2821675becceSMel Gorman 	 */
2822675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
282317636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2824675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2825675becceSMel Gorman 			continue;
2826675becceSMel Gorman 
2827675becceSMel Gorman 		/* Throttle based on the first usable node */
28285515061dSMel Gorman 		pgdat = zone->zone_pgdat;
28295515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
283050694c28SMel Gorman 			goto out;
2831675becceSMel Gorman 		break;
2832675becceSMel Gorman 	}
2833675becceSMel Gorman 
2834675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2835675becceSMel Gorman 	if (!pgdat)
2836675becceSMel Gorman 		goto out;
28375515061dSMel Gorman 
283868243e76SMel Gorman 	/* Account for the throttling */
283968243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
284068243e76SMel Gorman 
28415515061dSMel Gorman 	/*
28425515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
28435515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
28445515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
28455515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
28465515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
28475515061dSMel Gorman 	 * second before continuing.
28485515061dSMel Gorman 	 */
28495515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
28505515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
28515515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
285250694c28SMel Gorman 
285350694c28SMel Gorman 		goto check_pending;
28545515061dSMel Gorman 	}
28555515061dSMel Gorman 
28565515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
28575515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
28585515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
285950694c28SMel Gorman 
286050694c28SMel Gorman check_pending:
286150694c28SMel Gorman 	if (fatal_signal_pending(current))
286250694c28SMel Gorman 		return true;
286350694c28SMel Gorman 
286450694c28SMel Gorman out:
286550694c28SMel Gorman 	return false;
28665515061dSMel Gorman }
28675515061dSMel Gorman 
2868dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2869327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
287066e1707bSBalbir Singh {
287133906bc5SMel Gorman 	unsigned long nr_reclaimed;
287266e1707bSBalbir Singh 	struct scan_control sc = {
287322fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2874ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2875b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2876ee814fe2SJohannes Weiner 		.order = order,
2877ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2878ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2879ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2880a6dc60f8SJohannes Weiner 		.may_unmap = 1,
28812e2e4259SKOSAKI Motohiro 		.may_swap = 1,
288266e1707bSBalbir Singh 	};
288366e1707bSBalbir Singh 
28845515061dSMel Gorman 	/*
288550694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
288650694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
288750694c28SMel Gorman 	 * point.
28885515061dSMel Gorman 	 */
288950694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
28905515061dSMel Gorman 		return 1;
28915515061dSMel Gorman 
289233906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
289333906bc5SMel Gorman 				sc.may_writepage,
289433906bc5SMel Gorman 				gfp_mask);
289533906bc5SMel Gorman 
28963115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
289733906bc5SMel Gorman 
289833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
289933906bc5SMel Gorman 
290033906bc5SMel Gorman 	return nr_reclaimed;
290166e1707bSBalbir Singh }
290266e1707bSBalbir Singh 
2903c255a458SAndrew Morton #ifdef CONFIG_MEMCG
290466e1707bSBalbir Singh 
290572835c86SJohannes Weiner unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
29064e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
29070ae5e89cSYing Han 						struct zone *zone,
29080ae5e89cSYing Han 						unsigned long *nr_scanned)
29094e416953SBalbir Singh {
29104e416953SBalbir Singh 	struct scan_control sc = {
2911b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2912ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
29134e416953SBalbir Singh 		.may_writepage = !laptop_mode,
29144e416953SBalbir Singh 		.may_unmap = 1,
2915b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
29164e416953SBalbir Singh 		.may_swap = !noswap,
29174e416953SBalbir Singh 	};
29186b4f7799SJohannes Weiner 	unsigned long lru_pages;
29190ae5e89cSYing Han 
29204e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
29214e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2922bdce6d9eSKOSAKI Motohiro 
29239e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2924bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2925bdce6d9eSKOSAKI Motohiro 						      sc.gfp_mask);
2926bdce6d9eSKOSAKI Motohiro 
29274e416953SBalbir Singh 	/*
29284e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
29294e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
29304e416953SBalbir Singh 	 * if we don't reclaim here, the shrink_zone from balance_pgdat
29314e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
29324e416953SBalbir Singh 	 * the priority and make it zero.
29334e416953SBalbir Singh 	 */
293433377678SVladimir Davydov 	shrink_zone_memcg(zone, memcg, &sc, &lru_pages);
2935bdce6d9eSKOSAKI Motohiro 
2936bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2937bdce6d9eSKOSAKI Motohiro 
29380ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
29394e416953SBalbir Singh 	return sc.nr_reclaimed;
29404e416953SBalbir Singh }
29414e416953SBalbir Singh 
294272835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2943b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
29448c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2945b70a2a21SJohannes Weiner 					   bool may_swap)
294666e1707bSBalbir Singh {
29474e416953SBalbir Singh 	struct zonelist *zonelist;
2948bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2949889976dbSYing Han 	int nid;
295066e1707bSBalbir Singh 	struct scan_control sc = {
2951b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2952ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2953ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2954b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
2955ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2956ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
295766e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2958a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2959b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2960a09ed5e0SYing Han 	};
296166e1707bSBalbir Singh 
2962889976dbSYing Han 	/*
2963889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2964889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2965889976dbSYing Han 	 * scan does not need to be the current node.
2966889976dbSYing Han 	 */
296772835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2968889976dbSYing Han 
2969889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2970bdce6d9eSKOSAKI Motohiro 
2971bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2972bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
2973bdce6d9eSKOSAKI Motohiro 					    sc.gfp_mask);
2974bdce6d9eSKOSAKI Motohiro 
29753115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
2976bdce6d9eSKOSAKI Motohiro 
2977bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2978bdce6d9eSKOSAKI Motohiro 
2979bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
298066e1707bSBalbir Singh }
298166e1707bSBalbir Singh #endif
298266e1707bSBalbir Singh 
2983*1d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
2984*1d82de61SMel Gorman 				struct zone *zone, struct scan_control *sc)
2985f16015fbSJohannes Weiner {
2986b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
2987b95a2f2dSJohannes Weiner 
2988b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
2989b95a2f2dSJohannes Weiner 		return;
2990b95a2f2dSJohannes Weiner 
2991b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
2992b95a2f2dSJohannes Weiner 	do {
2993c56d5c7dSKonstantin Khlebnikov 		struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2994f16015fbSJohannes Weiner 
299559dc76b0SRik van Riel 		if (inactive_list_is_low(lruvec, false))
29961a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
29979e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
2998b95a2f2dSJohannes Weiner 
2999b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3000b95a2f2dSJohannes Weiner 	} while (memcg);
3001f16015fbSJohannes Weiner }
3002f16015fbSJohannes Weiner 
3003*1d82de61SMel Gorman static bool zone_balanced(struct zone *zone, int order,
300460cefed4SJohannes Weiner 			unsigned long balance_gap, int classzone_idx)
300560cefed4SJohannes Weiner {
3006accf6242SVlastimil Babka 	unsigned long mark = high_wmark_pages(zone) + balance_gap;
300760cefed4SJohannes Weiner 
3008accf6242SVlastimil Babka 	return zone_watermark_ok_safe(zone, order, mark, classzone_idx);
300960cefed4SJohannes Weiner }
301060cefed4SJohannes Weiner 
30111741c877SMel Gorman /*
30125515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30135515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30145515061dSMel Gorman  *
30155515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30165515061dSMel Gorman  */
30175515061dSMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
3018dc83edd9SMel Gorman 					int classzone_idx)
3019f50de2d3SMel Gorman {
3020*1d82de61SMel Gorman 	int i;
3021*1d82de61SMel Gorman 
3022f50de2d3SMel Gorman 	/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
3023f50de2d3SMel Gorman 	if (remaining)
30245515061dSMel Gorman 		return false;
30255515061dSMel Gorman 
30265515061dSMel Gorman 	/*
30279e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
30289e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
30299e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
30309e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
30319e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
30329e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
30339e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
30349e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
30359e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
30369e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
30379e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
30385515061dSMel Gorman 	 */
30399e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
30409e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3041f50de2d3SMel Gorman 
3042*1d82de61SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3043*1d82de61SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
3044*1d82de61SMel Gorman 
3045*1d82de61SMel Gorman 		if (!populated_zone(zone))
3046*1d82de61SMel Gorman 			continue;
3047*1d82de61SMel Gorman 
3048*1d82de61SMel Gorman 		if (zone_balanced(zone, order, 0, classzone_idx))
3049*1d82de61SMel Gorman 			return true;
3050*1d82de61SMel Gorman 	}
3051*1d82de61SMel Gorman 
3052*1d82de61SMel Gorman 	return false;
3053f50de2d3SMel Gorman }
3054f50de2d3SMel Gorman 
30551da177e4SLinus Torvalds /*
3056*1d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
3057*1d82de61SMel Gorman  * zone that is currently unbalanced.
3058b8e83b94SMel Gorman  *
3059b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3060283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3061283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
306275485363SMel Gorman  */
3063*1d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
30647c954f6dSMel Gorman 			       int classzone_idx,
3065accf6242SVlastimil Babka 			       struct scan_control *sc)
306675485363SMel Gorman {
3067*1d82de61SMel Gorman 	struct zone *zone;
3068*1d82de61SMel Gorman 	int z;
306975485363SMel Gorman 
3070*1d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
3071*1d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3072*1d82de61SMel Gorman 	for (z = 0; z <= classzone_idx; z++) {
3073*1d82de61SMel Gorman 		zone = pgdat->node_zones + z;
3074*1d82de61SMel Gorman 		if (!populated_zone(zone))
3075*1d82de61SMel Gorman 			continue;
30767c954f6dSMel Gorman 
3077*1d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
30787c954f6dSMel Gorman 	}
30797c954f6dSMel Gorman 
3080*1d82de61SMel Gorman 	/*
3081*1d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
3082*1d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
3083*1d82de61SMel Gorman 	 */
3084*1d82de61SMel Gorman 	shrink_node(pgdat, sc, classzone_idx);
3085*1d82de61SMel Gorman 
3086*1d82de61SMel Gorman 	/*
3087*1d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
3088*1d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
3089*1d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
3090*1d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
3091*1d82de61SMel Gorman 	 * can direct reclaim/compact.
3092*1d82de61SMel Gorman 	 */
3093*1d82de61SMel Gorman 	if (sc->order && sc->nr_reclaimed >= 2UL << sc->order)
3094*1d82de61SMel Gorman 		sc->order = 0;
3095*1d82de61SMel Gorman 
3096b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
309775485363SMel Gorman }
309875485363SMel Gorman 
309975485363SMel Gorman /*
3100*1d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3101*1d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
3102*1d82de61SMel Gorman  * balanced.
31031da177e4SLinus Torvalds  *
3104*1d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
31051da177e4SLinus Torvalds  *
31061da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
310741858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3108*1d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
3109*1d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
3110*1d82de61SMel Gorman  * balanced.
31111da177e4SLinus Torvalds  */
3112accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
31131da177e4SLinus Torvalds {
31141da177e4SLinus Torvalds 	int i;
31150608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31160608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3117*1d82de61SMel Gorman 	struct zone *zone;
3118179e9639SAndrew Morton 	struct scan_control sc = {
3119179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3120ee814fe2SJohannes Weiner 		.order = order,
3121b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3122ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3123a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31242e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3125*1d82de61SMel Gorman 		.reclaim_idx = classzone_idx,
3126179e9639SAndrew Morton 	};
3127f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
31281da177e4SLinus Torvalds 
31299e3b2f8cSKonstantin Khlebnikov 	do {
3130b8e83b94SMel Gorman 		bool raise_priority = true;
3131b8e83b94SMel Gorman 
3132b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
31331da177e4SLinus Torvalds 
3134f7b60926SMel Gorman 		/* Scan from the highest requested zone to dma */
3135f7b60926SMel Gorman 		for (i = classzone_idx; i >= 0; i--) {
3136*1d82de61SMel Gorman 			zone = pgdat->node_zones + i;
3137f3fe6512SCon Kolivas 			if (!populated_zone(zone))
31381da177e4SLinus Torvalds 				continue;
31391da177e4SLinus Torvalds 
3140cc715d99SMel Gorman 			/*
3141cc715d99SMel Gorman 			 * If the number of buffer_heads in the machine
3142cc715d99SMel Gorman 			 * exceeds the maximum allowed level and this node
3143cc715d99SMel Gorman 			 * has a highmem zone, force kswapd to reclaim from
3144cc715d99SMel Gorman 			 * it to relieve lowmem pressure.
3145cc715d99SMel Gorman 			 */
3146cc715d99SMel Gorman 			if (buffer_heads_over_limit && is_highmem_idx(i)) {
3147*1d82de61SMel Gorman 				classzone_idx = i;
3148cc715d99SMel Gorman 				break;
3149cc715d99SMel Gorman 			}
3150cc715d99SMel Gorman 
3151*1d82de61SMel Gorman 			if (!zone_balanced(zone, order, 0, 0)) {
3152*1d82de61SMel Gorman 				classzone_idx = i;
3153e1dbeda6SAndrew Morton 				break;
3154439423f6SShaohua Li 			} else {
3155d43006d5SMel Gorman 				/*
3156*1d82de61SMel Gorman 				 * If any eligible zone is balanced then the
3157*1d82de61SMel Gorman 				 * node is not considered congested or dirty.
3158d43006d5SMel Gorman 				 */
3159599d0c95SMel Gorman 				clear_bit(PGDAT_CONGESTED, &zone->zone_pgdat->flags);
3160599d0c95SMel Gorman 				clear_bit(PGDAT_DIRTY, &zone->zone_pgdat->flags);
31611da177e4SLinus Torvalds 			}
31621da177e4SLinus Torvalds 		}
3163dafcb73eSZlatko Calusic 
3164b8e83b94SMel Gorman 		if (i < 0)
31651da177e4SLinus Torvalds 			goto out;
3166e1dbeda6SAndrew Morton 
31671da177e4SLinus Torvalds 		/*
3168*1d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
3169*1d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
3170*1d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
3171*1d82de61SMel Gorman 		 * about consistent aging.
3172*1d82de61SMel Gorman 		 */
3173*1d82de61SMel Gorman 		age_active_anon(pgdat, &pgdat->node_zones[MAX_NR_ZONES - 1], &sc);
3174*1d82de61SMel Gorman 
3175*1d82de61SMel Gorman 		/*
3176b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3177b7ea3c41SMel Gorman 		 * even in laptop mode.
3178b7ea3c41SMel Gorman 		 */
3179*1d82de61SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2 || !pgdat_reclaimable(pgdat))
3180b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3181b7ea3c41SMel Gorman 
3182*1d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
31831da177e4SLinus Torvalds 		sc.nr_scanned = 0;
31840608f43dSAndrew Morton 		nr_soft_scanned = 0;
3185*1d82de61SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone, sc.order,
3186*1d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
31870608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
31880608f43dSAndrew Morton 
318932a4330dSRik van Riel 		/*
3190*1d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
3191*1d82de61SMel Gorman 		 * enough pages are already being scanned that that high
3192*1d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
319332a4330dSRik van Riel 		 */
3194*1d82de61SMel Gorman 		if (kswapd_shrink_node(pgdat, classzone_idx, &sc))
3195b8e83b94SMel Gorman 			raise_priority = false;
3196d7868daeSMel Gorman 
31975515061dSMel Gorman 		/*
31985515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
31995515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32005515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32015515061dSMel Gorman 		 */
32025515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
32035515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3204cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32055515061dSMel Gorman 
3206b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3207b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3208b8e83b94SMel Gorman 			break;
3209b8e83b94SMel Gorman 
3210b8e83b94SMel Gorman 		/*
3211*1d82de61SMel Gorman 		 * Stop reclaiming if any eligible zone is balanced and clear
3212*1d82de61SMel Gorman 		 * node writeback or congested.
3213*1d82de61SMel Gorman 		 */
3214*1d82de61SMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
3215*1d82de61SMel Gorman 			zone = pgdat->node_zones + i;
3216*1d82de61SMel Gorman 			if (!populated_zone(zone))
3217*1d82de61SMel Gorman 				continue;
3218*1d82de61SMel Gorman 
3219*1d82de61SMel Gorman 			if (zone_balanced(zone, sc.order, 0, classzone_idx)) {
3220*1d82de61SMel Gorman 				clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3221*1d82de61SMel Gorman 				clear_bit(PGDAT_DIRTY, &pgdat->flags);
3222*1d82de61SMel Gorman 				goto out;
3223*1d82de61SMel Gorman 			}
3224*1d82de61SMel Gorman 		}
3225*1d82de61SMel Gorman 
3226*1d82de61SMel Gorman 		/*
3227b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3228b8e83b94SMel Gorman 		 * progress in reclaiming pages
3229b8e83b94SMel Gorman 		 */
3230b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3231b8e83b94SMel Gorman 			sc.priority--;
3232*1d82de61SMel Gorman 	} while (sc.priority >= 1);
32331da177e4SLinus Torvalds 
3234b8e83b94SMel Gorman out:
32350abdee2bSMel Gorman 	/*
3236*1d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
3237*1d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
3238*1d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
3239*1d82de61SMel Gorman 	 * remain at the higher level.
32400abdee2bSMel Gorman 	 */
3241*1d82de61SMel Gorman 	return sc.order;
32421da177e4SLinus Torvalds }
32431da177e4SLinus Torvalds 
3244accf6242SVlastimil Babka static void kswapd_try_to_sleep(pg_data_t *pgdat, int order,
3245accf6242SVlastimil Babka 				int classzone_idx, int balanced_classzone_idx)
3246f0bc0a60SKOSAKI Motohiro {
3247f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3248f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3249f0bc0a60SKOSAKI Motohiro 
3250f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3251f0bc0a60SKOSAKI Motohiro 		return;
3252f0bc0a60SKOSAKI Motohiro 
3253f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3254f0bc0a60SKOSAKI Motohiro 
3255f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3256accf6242SVlastimil Babka 	if (prepare_kswapd_sleep(pgdat, order, remaining,
3257accf6242SVlastimil Babka 						balanced_classzone_idx)) {
3258fd901c95SVlastimil Babka 		/*
3259fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3260fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3261fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3262fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3263fd901c95SVlastimil Babka 		 */
3264fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3265fd901c95SVlastimil Babka 
3266fd901c95SVlastimil Babka 		/*
3267fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3268fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3269fd901c95SVlastimil Babka 		 */
3270fd901c95SVlastimil Babka 		wakeup_kcompactd(pgdat, order, classzone_idx);
3271fd901c95SVlastimil Babka 
3272f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
3273f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3274f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3275f0bc0a60SKOSAKI Motohiro 	}
3276f0bc0a60SKOSAKI Motohiro 
3277f0bc0a60SKOSAKI Motohiro 	/*
3278f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3279f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3280f0bc0a60SKOSAKI Motohiro 	 */
3281accf6242SVlastimil Babka 	if (prepare_kswapd_sleep(pgdat, order, remaining,
3282accf6242SVlastimil Babka 						balanced_classzone_idx)) {
3283f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3284f0bc0a60SKOSAKI Motohiro 
3285f0bc0a60SKOSAKI Motohiro 		/*
3286f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3287f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3288f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3289f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3290f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3291f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3292f0bc0a60SKOSAKI Motohiro 		 */
3293f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
32941c7e7f6cSAaditya Kumar 
32951c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3296f0bc0a60SKOSAKI Motohiro 			schedule();
32971c7e7f6cSAaditya Kumar 
3298f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3299f0bc0a60SKOSAKI Motohiro 	} else {
3300f0bc0a60SKOSAKI Motohiro 		if (remaining)
3301f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3302f0bc0a60SKOSAKI Motohiro 		else
3303f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3304f0bc0a60SKOSAKI Motohiro 	}
3305f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3306f0bc0a60SKOSAKI Motohiro }
3307f0bc0a60SKOSAKI Motohiro 
33081da177e4SLinus Torvalds /*
33091da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33101da177e4SLinus Torvalds  * from the init process.
33111da177e4SLinus Torvalds  *
33121da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33131da177e4SLinus Torvalds  * free memory available even if there is no other activity
33141da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33151da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33161da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33171da177e4SLinus Torvalds  *
33181da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33191da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33201da177e4SLinus Torvalds  */
33211da177e4SLinus Torvalds static int kswapd(void *p)
33221da177e4SLinus Torvalds {
3323215ddd66SMel Gorman 	unsigned long order, new_order;
3324215ddd66SMel Gorman 	int classzone_idx, new_classzone_idx;
3325d2ebd0f6SAlex,Shi 	int balanced_classzone_idx;
33261da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
33271da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3328f0bc0a60SKOSAKI Motohiro 
33291da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
33301da177e4SLinus Torvalds 		.reclaimed_slab = 0,
33311da177e4SLinus Torvalds 	};
3332a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
33331da177e4SLinus Torvalds 
3334cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3335cf40bd16SNick Piggin 
3336174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3337c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
33381da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
33391da177e4SLinus Torvalds 
33401da177e4SLinus Torvalds 	/*
33411da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
33421da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
33431da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
33441da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
33451da177e4SLinus Torvalds 	 *
33461da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
33471da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
33481da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
33491da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
33501da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
33511da177e4SLinus Torvalds 	 */
3352930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
335383144186SRafael J. Wysocki 	set_freezable();
33541da177e4SLinus Torvalds 
3355215ddd66SMel Gorman 	order = new_order = 0;
3356215ddd66SMel Gorman 	classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3357d2ebd0f6SAlex,Shi 	balanced_classzone_idx = classzone_idx;
33581da177e4SLinus Torvalds 	for ( ; ; ) {
33596f6313d4SJeff Liu 		bool ret;
33603e1d1d28SChristoph Lameter 
3361215ddd66SMel Gorman 		/*
3362accf6242SVlastimil Babka 		 * While we were reclaiming, there might have been another
3363accf6242SVlastimil Babka 		 * wakeup, so check the values.
3364215ddd66SMel Gorman 		 */
33651da177e4SLinus Torvalds 		new_order = pgdat->kswapd_max_order;
336699504748SMel Gorman 		new_classzone_idx = pgdat->classzone_idx;
33671da177e4SLinus Torvalds 		pgdat->kswapd_max_order =  0;
3368215ddd66SMel Gorman 		pgdat->classzone_idx = pgdat->nr_zones - 1;
3369215ddd66SMel Gorman 
337099504748SMel Gorman 		if (order < new_order || classzone_idx > new_classzone_idx) {
33711da177e4SLinus Torvalds 			/*
33721da177e4SLinus Torvalds 			 * Don't sleep if someone wants a larger 'order'
337399504748SMel Gorman 			 * allocation or has tigher zone constraints
33741da177e4SLinus Torvalds 			 */
33751da177e4SLinus Torvalds 			order = new_order;
337699504748SMel Gorman 			classzone_idx = new_classzone_idx;
33771da177e4SLinus Torvalds 		} else {
3378accf6242SVlastimil Babka 			kswapd_try_to_sleep(pgdat, order, classzone_idx,
3379d2ebd0f6SAlex,Shi 						balanced_classzone_idx);
33801da177e4SLinus Torvalds 			order = pgdat->kswapd_max_order;
338199504748SMel Gorman 			classzone_idx = pgdat->classzone_idx;
3382f0dfcde0SAlex,Shi 			new_order = order;
3383f0dfcde0SAlex,Shi 			new_classzone_idx = classzone_idx;
33844d40502eSMel Gorman 			pgdat->kswapd_max_order = 0;
3385215ddd66SMel Gorman 			pgdat->classzone_idx = pgdat->nr_zones - 1;
33861da177e4SLinus Torvalds 		}
33871da177e4SLinus Torvalds 
33888fe23e05SDavid Rientjes 		ret = try_to_freeze();
33898fe23e05SDavid Rientjes 		if (kthread_should_stop())
33908fe23e05SDavid Rientjes 			break;
33918fe23e05SDavid Rientjes 
33928fe23e05SDavid Rientjes 		/*
33938fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
33948fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3395b1296cc4SRafael J. Wysocki 		 */
339633906bc5SMel Gorman 		if (!ret) {
339733906bc5SMel Gorman 			trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3398*1d82de61SMel Gorman 
3399*1d82de61SMel Gorman 			/* return value ignored until next patch */
3400*1d82de61SMel Gorman 			balance_pgdat(pgdat, order, classzone_idx);
34011da177e4SLinus Torvalds 		}
340233906bc5SMel Gorman 	}
3403b0a8cc58STakamori Yamaguchi 
340471abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3405b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
340671abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
340771abdc15SJohannes Weiner 
34081da177e4SLinus Torvalds 	return 0;
34091da177e4SLinus Torvalds }
34101da177e4SLinus Torvalds 
34111da177e4SLinus Torvalds /*
34121da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34131da177e4SLinus Torvalds  */
341499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34151da177e4SLinus Torvalds {
34161da177e4SLinus Torvalds 	pg_data_t *pgdat;
34171da177e4SLinus Torvalds 
3418f3fe6512SCon Kolivas 	if (!populated_zone(zone))
34191da177e4SLinus Torvalds 		return;
34201da177e4SLinus Torvalds 
3421344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34221da177e4SLinus Torvalds 		return;
342388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
342499504748SMel Gorman 	if (pgdat->kswapd_max_order < order) {
342588f5acf8SMel Gorman 		pgdat->kswapd_max_order = order;
342699504748SMel Gorman 		pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
342799504748SMel Gorman 	}
34288d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34291da177e4SLinus Torvalds 		return;
3430*1d82de61SMel Gorman 	if (zone_balanced(zone, order, 0, 0))
343188f5acf8SMel Gorman 		return;
343288f5acf8SMel Gorman 
343388f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
34348d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
34351da177e4SLinus Torvalds }
34361da177e4SLinus Torvalds 
3437c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
34381da177e4SLinus Torvalds /*
34397b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3440d6277db4SRafael J. Wysocki  * freed pages.
3441d6277db4SRafael J. Wysocki  *
3442d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3443d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3444d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
34451da177e4SLinus Torvalds  */
34467b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
34471da177e4SLinus Torvalds {
3448d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3449d6277db4SRafael J. Wysocki 	struct scan_control sc = {
34507b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3451ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3452b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
34539e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3454ee814fe2SJohannes Weiner 		.may_writepage = 1,
3455ee814fe2SJohannes Weiner 		.may_unmap = 1,
3456ee814fe2SJohannes Weiner 		.may_swap = 1,
3457ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
34581da177e4SLinus Torvalds 	};
34597b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
34607b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
34617b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
34621da177e4SLinus Torvalds 
34637b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
34647b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3465d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
34667b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3467d6277db4SRafael J. Wysocki 
34683115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3469d6277db4SRafael J. Wysocki 
34707b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
34717b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
34727b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3473d6277db4SRafael J. Wysocki 
34747b51755cSKOSAKI Motohiro 	return nr_reclaimed;
34751da177e4SLinus Torvalds }
3476c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
34771da177e4SLinus Torvalds 
34781da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
34791da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
34801da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
34811da177e4SLinus Torvalds    restore their cpu bindings. */
3482fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3483fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
34841da177e4SLinus Torvalds {
348558c0a4a7SYasunori Goto 	int nid;
34861da177e4SLinus Torvalds 
34878bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
348848fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3489c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3490a70f7302SRusty Russell 			const struct cpumask *mask;
3491a70f7302SRusty Russell 
3492a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3493c5f59f08SMike Travis 
34943e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
34951da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3496c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
34971da177e4SLinus Torvalds 		}
34981da177e4SLinus Torvalds 	}
34991da177e4SLinus Torvalds 	return NOTIFY_OK;
35001da177e4SLinus Torvalds }
35011da177e4SLinus Torvalds 
35023218ae14SYasunori Goto /*
35033218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35043218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35053218ae14SYasunori Goto  */
35063218ae14SYasunori Goto int kswapd_run(int nid)
35073218ae14SYasunori Goto {
35083218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35093218ae14SYasunori Goto 	int ret = 0;
35103218ae14SYasunori Goto 
35113218ae14SYasunori Goto 	if (pgdat->kswapd)
35123218ae14SYasunori Goto 		return 0;
35133218ae14SYasunori Goto 
35143218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35153218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35163218ae14SYasunori Goto 		/* failure at boot is fatal */
35173218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3518d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3519d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3520d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35213218ae14SYasunori Goto 	}
35223218ae14SYasunori Goto 	return ret;
35233218ae14SYasunori Goto }
35243218ae14SYasunori Goto 
35258fe23e05SDavid Rientjes /*
3526d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3527bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
35288fe23e05SDavid Rientjes  */
35298fe23e05SDavid Rientjes void kswapd_stop(int nid)
35308fe23e05SDavid Rientjes {
35318fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
35328fe23e05SDavid Rientjes 
3533d8adde17SJiang Liu 	if (kswapd) {
35348fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3535d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3536d8adde17SJiang Liu 	}
35378fe23e05SDavid Rientjes }
35388fe23e05SDavid Rientjes 
35391da177e4SLinus Torvalds static int __init kswapd_init(void)
35401da177e4SLinus Torvalds {
35413218ae14SYasunori Goto 	int nid;
354269e05944SAndrew Morton 
35431da177e4SLinus Torvalds 	swap_setup();
354448fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
35453218ae14SYasunori Goto  		kswapd_run(nid);
35461da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
35471da177e4SLinus Torvalds 	return 0;
35481da177e4SLinus Torvalds }
35491da177e4SLinus Torvalds 
35501da177e4SLinus Torvalds module_init(kswapd_init)
35519eeff239SChristoph Lameter 
35529eeff239SChristoph Lameter #ifdef CONFIG_NUMA
35539eeff239SChristoph Lameter /*
35549eeff239SChristoph Lameter  * Zone reclaim mode
35559eeff239SChristoph Lameter  *
35569eeff239SChristoph Lameter  * If non-zero call zone_reclaim when the number of free pages falls below
35579eeff239SChristoph Lameter  * the watermarks.
35589eeff239SChristoph Lameter  */
35599eeff239SChristoph Lameter int zone_reclaim_mode __read_mostly;
35609eeff239SChristoph Lameter 
35611b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
35627d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
35631b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
356495bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
35651b2ffb78SChristoph Lameter 
35669eeff239SChristoph Lameter /*
3567a92f7126SChristoph Lameter  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3568a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3569a92f7126SChristoph Lameter  * a zone.
3570a92f7126SChristoph Lameter  */
3571a92f7126SChristoph Lameter #define ZONE_RECLAIM_PRIORITY 4
3572a92f7126SChristoph Lameter 
35739eeff239SChristoph Lameter /*
35749614634fSChristoph Lameter  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
35759614634fSChristoph Lameter  * occur.
35769614634fSChristoph Lameter  */
35779614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
35789614634fSChristoph Lameter 
35799614634fSChristoph Lameter /*
35800ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
35810ff38490SChristoph Lameter  * slab reclaim needs to occur.
35820ff38490SChristoph Lameter  */
35830ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
35840ff38490SChristoph Lameter 
358590afa5deSMel Gorman static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
358690afa5deSMel Gorman {
358790afa5deSMel Gorman 	unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
3588599d0c95SMel Gorman 	unsigned long file_lru = node_page_state(zone->zone_pgdat, NR_INACTIVE_FILE) +
3589599d0c95SMel Gorman 		node_page_state(zone->zone_pgdat, NR_ACTIVE_FILE);
359090afa5deSMel Gorman 
359190afa5deSMel Gorman 	/*
359290afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
359390afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
359490afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
359590afa5deSMel Gorman 	 */
359690afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
359790afa5deSMel Gorman }
359890afa5deSMel Gorman 
359990afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3600d031a157SAlexandru Moise static unsigned long zone_pagecache_reclaimable(struct zone *zone)
360190afa5deSMel Gorman {
3602d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3603d031a157SAlexandru Moise 	unsigned long delta = 0;
360490afa5deSMel Gorman 
360590afa5deSMel Gorman 	/*
360695bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
360790afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
360890afa5deSMel Gorman 	 * pages like swapcache and zone_unmapped_file_pages() provides
360990afa5deSMel Gorman 	 * a better estimate
361090afa5deSMel Gorman 	 */
361195bbc0c7SZhihui Zhang 	if (zone_reclaim_mode & RECLAIM_UNMAP)
361290afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
361390afa5deSMel Gorman 	else
361490afa5deSMel Gorman 		nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
361590afa5deSMel Gorman 
361690afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
361790afa5deSMel Gorman 	if (!(zone_reclaim_mode & RECLAIM_WRITE))
361890afa5deSMel Gorman 		delta += zone_page_state(zone, NR_FILE_DIRTY);
361990afa5deSMel Gorman 
362090afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
362190afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
362290afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
362390afa5deSMel Gorman 
362490afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
362590afa5deSMel Gorman }
362690afa5deSMel Gorman 
36270ff38490SChristoph Lameter /*
36289eeff239SChristoph Lameter  * Try to free up some pages from this zone through reclaim.
36299eeff239SChristoph Lameter  */
3630179e9639SAndrew Morton static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
36319eeff239SChristoph Lameter {
36327fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
363369e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
36349eeff239SChristoph Lameter 	struct task_struct *p = current;
36359eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3636179e9639SAndrew Morton 	struct scan_control sc = {
363762b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
363821caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3639bd2f6199SJohannes Weiner 		.order = order,
36409e3b2f8cSKonstantin Khlebnikov 		.priority = ZONE_RECLAIM_PRIORITY,
3641ee814fe2SJohannes Weiner 		.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
364295bbc0c7SZhihui Zhang 		.may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP),
3643ee814fe2SJohannes Weiner 		.may_swap = 1,
3644b2e18757SMel Gorman 		.reclaim_idx = zone_idx(zone),
3645179e9639SAndrew Morton 	};
36469eeff239SChristoph Lameter 
36479eeff239SChristoph Lameter 	cond_resched();
3648d4f7796eSChristoph Lameter 	/*
364995bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3650d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
365195bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3652d4f7796eSChristoph Lameter 	 */
3653d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
365476ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
36559eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
36569eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3657c84db23cSChristoph Lameter 
365890afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3659a92f7126SChristoph Lameter 		/*
36600ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
36610ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3662a92f7126SChristoph Lameter 		 */
3663a92f7126SChristoph Lameter 		do {
3664b2e18757SMel Gorman 			shrink_node(zone->zone_pgdat, &sc, zone_idx(zone));
36659e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
36660ff38490SChristoph Lameter 	}
3667a92f7126SChristoph Lameter 
36689eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3669d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
367076ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3671a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
36729eeff239SChristoph Lameter }
3673179e9639SAndrew Morton 
3674179e9639SAndrew Morton int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3675179e9639SAndrew Morton {
3676179e9639SAndrew Morton 	int node_id;
3677d773ed6bSDavid Rientjes 	int ret;
3678179e9639SAndrew Morton 
3679179e9639SAndrew Morton 	/*
36800ff38490SChristoph Lameter 	 * Zone reclaim reclaims unmapped file backed pages and
36810ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
368234aa1330SChristoph Lameter 	 *
36839614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
36849614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
36859614634fSChristoph Lameter 	 * thrown out if the zone is overallocated. So we do not reclaim
36869614634fSChristoph Lameter 	 * if less than a specified percentage of the zone is used by
36879614634fSChristoph Lameter 	 * unmapped file backed pages.
3688179e9639SAndrew Morton 	 */
368990afa5deSMel Gorman 	if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
369090afa5deSMel Gorman 	    zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3691fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3692179e9639SAndrew Morton 
3693599d0c95SMel Gorman 	if (!pgdat_reclaimable(zone->zone_pgdat))
3694fa5e084eSMel Gorman 		return ZONE_RECLAIM_FULL;
3695d773ed6bSDavid Rientjes 
3696179e9639SAndrew Morton 	/*
3697d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3698179e9639SAndrew Morton 	 */
3699d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3700fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3701179e9639SAndrew Morton 
3702179e9639SAndrew Morton 	/*
3703179e9639SAndrew Morton 	 * Only run zone reclaim on the local zone or on zones that do not
3704179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3705179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3706179e9639SAndrew Morton 	 * as wide as possible.
3707179e9639SAndrew Morton 	 */
370889fa3024SChristoph Lameter 	node_id = zone_to_nid(zone);
370937c0708dSChristoph Lameter 	if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3710fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3711d773ed6bSDavid Rientjes 
371257054651SJohannes Weiner 	if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
3713fa5e084eSMel Gorman 		return ZONE_RECLAIM_NOSCAN;
3714fa5e084eSMel Gorman 
3715d773ed6bSDavid Rientjes 	ret = __zone_reclaim(zone, gfp_mask, order);
371657054651SJohannes Weiner 	clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
3717d773ed6bSDavid Rientjes 
371824cf7251SMel Gorman 	if (!ret)
371924cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
372024cf7251SMel Gorman 
3721d773ed6bSDavid Rientjes 	return ret;
3722179e9639SAndrew Morton }
37239eeff239SChristoph Lameter #endif
3724894bc310SLee Schermerhorn 
3725894bc310SLee Schermerhorn /*
3726894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3727894bc310SLee Schermerhorn  * @page: the page to test
3728894bc310SLee Schermerhorn  *
3729894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
373039b5f29aSHugh Dickins  * lists vs unevictable list.
3731894bc310SLee Schermerhorn  *
3732894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3733ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3734b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3735ba9ddf49SLee Schermerhorn  *
3736894bc310SLee Schermerhorn  */
373739b5f29aSHugh Dickins int page_evictable(struct page *page)
3738894bc310SLee Schermerhorn {
373939b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3740894bc310SLee Schermerhorn }
374189e004eaSLee Schermerhorn 
374285046579SHugh Dickins #ifdef CONFIG_SHMEM
374389e004eaSLee Schermerhorn /**
374424513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
374524513264SHugh Dickins  * @pages:	array of pages to check
374624513264SHugh Dickins  * @nr_pages:	number of pages to check
374789e004eaSLee Schermerhorn  *
374824513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
374985046579SHugh Dickins  *
375085046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
375189e004eaSLee Schermerhorn  */
375224513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
375389e004eaSLee Schermerhorn {
3754925b7673SJohannes Weiner 	struct lruvec *lruvec;
375524513264SHugh Dickins 	struct zone *zone = NULL;
375624513264SHugh Dickins 	int pgscanned = 0;
375724513264SHugh Dickins 	int pgrescued = 0;
375889e004eaSLee Schermerhorn 	int i;
375989e004eaSLee Schermerhorn 
376024513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
376124513264SHugh Dickins 		struct page *page = pages[i];
376224513264SHugh Dickins 		struct zone *pagezone;
376389e004eaSLee Schermerhorn 
376424513264SHugh Dickins 		pgscanned++;
376524513264SHugh Dickins 		pagezone = page_zone(page);
376689e004eaSLee Schermerhorn 		if (pagezone != zone) {
376789e004eaSLee Schermerhorn 			if (zone)
3768a52633d8SMel Gorman 				spin_unlock_irq(zone_lru_lock(zone));
376989e004eaSLee Schermerhorn 			zone = pagezone;
3770a52633d8SMel Gorman 			spin_lock_irq(zone_lru_lock(zone));
377189e004eaSLee Schermerhorn 		}
3772599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
377389e004eaSLee Schermerhorn 
377424513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
377524513264SHugh Dickins 			continue;
377689e004eaSLee Schermerhorn 
377739b5f29aSHugh Dickins 		if (page_evictable(page)) {
377824513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
377924513264SHugh Dickins 
3780309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
378124513264SHugh Dickins 			ClearPageUnevictable(page);
3782fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3783fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
378424513264SHugh Dickins 			pgrescued++;
378589e004eaSLee Schermerhorn 		}
378689e004eaSLee Schermerhorn 	}
378724513264SHugh Dickins 
378824513264SHugh Dickins 	if (zone) {
378924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
379024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3791a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
379224513264SHugh Dickins 	}
379385046579SHugh Dickins }
379485046579SHugh Dickins #endif /* CONFIG_SHMEM */
3795