xref: /openbmc/linux/mm/vmscan.c (revision 5a1c84b404a7176b8b36e2a0041b6f0adb3151a3)
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 
197*5a1c84b4SMel Gorman /*
198*5a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
199*5a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
200*5a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
201*5a1c84b4SMel Gorman  */
202*5a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
203*5a1c84b4SMel Gorman {
204*5a1c84b4SMel Gorman 	unsigned long nr;
205*5a1c84b4SMel Gorman 
206*5a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
207*5a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
208*5a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
209*5a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
210*5a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
211*5a1c84b4SMel Gorman 
212*5a1c84b4SMel Gorman 	return nr;
213*5a1c84b4SMel Gorman }
214*5a1c84b4SMel Gorman 
215599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2166e543d57SLisa Du {
217599d0c95SMel Gorman 	unsigned long nr;
218599d0c95SMel Gorman 
219599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
220599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
221599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
222599d0c95SMel Gorman 
223599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
224599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
225599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
226599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
227599d0c95SMel Gorman 
228599d0c95SMel Gorman 	return nr;
229599d0c95SMel Gorman }
230599d0c95SMel Gorman 
231599d0c95SMel Gorman bool pgdat_reclaimable(struct pglist_data *pgdat)
232599d0c95SMel Gorman {
233599d0c95SMel Gorman 	return node_page_state_snapshot(pgdat, NR_PAGES_SCANNED) <
234599d0c95SMel Gorman 		pgdat_reclaimable_pages(pgdat) * 6;
2356e543d57SLisa Du }
2366e543d57SLisa Du 
23723047a96SJohannes Weiner unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
238c9f299d9SKOSAKI Motohiro {
239c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2404d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
241a3d8e054SKOSAKI Motohiro 
242599d0c95SMel Gorman 	return node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
243c9f299d9SKOSAKI Motohiro }
244c9f299d9SKOSAKI Motohiro 
2451da177e4SLinus Torvalds /*
2461d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2471da177e4SLinus Torvalds  */
2481d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2491da177e4SLinus Torvalds {
2501d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2511d3d4437SGlauber Costa 
2521d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2531d3d4437SGlauber Costa 		size *= nr_node_ids;
2541d3d4437SGlauber Costa 
2551d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2561d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2571d3d4437SGlauber Costa 		return -ENOMEM;
2581d3d4437SGlauber Costa 
2591da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2601da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2611da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2621d3d4437SGlauber Costa 	return 0;
2631da177e4SLinus Torvalds }
2648e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2651da177e4SLinus Torvalds 
2661da177e4SLinus Torvalds /*
2671da177e4SLinus Torvalds  * Remove one
2681da177e4SLinus Torvalds  */
2698e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2701da177e4SLinus Torvalds {
2711da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2721da177e4SLinus Torvalds 	list_del(&shrinker->list);
2731da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
274ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2751da177e4SLinus Torvalds }
2768e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2771da177e4SLinus Torvalds 
2781da177e4SLinus Torvalds #define SHRINK_BATCH 128
2791d3d4437SGlauber Costa 
280cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2816b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2826b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2836b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2841da177e4SLinus Torvalds {
28524f7c6b9SDave Chinner 	unsigned long freed = 0;
2861da177e4SLinus Torvalds 	unsigned long long delta;
287635697c6SKonstantin Khlebnikov 	long total_scan;
288d5bc5fd3SVladimir Davydov 	long freeable;
289acf92b48SDave Chinner 	long nr;
290acf92b48SDave Chinner 	long new_nr;
2911d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
292e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
293e9299f50SDave Chinner 					  : SHRINK_BATCH;
2941da177e4SLinus Torvalds 
295d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
296d5bc5fd3SVladimir Davydov 	if (freeable == 0)
2971d3d4437SGlauber Costa 		return 0;
298635697c6SKonstantin Khlebnikov 
299acf92b48SDave Chinner 	/*
300acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
301acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
302acf92b48SDave Chinner 	 * don't also do this scanning work.
303acf92b48SDave Chinner 	 */
3041d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
305acf92b48SDave Chinner 
306acf92b48SDave Chinner 	total_scan = nr;
3076b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
308d5bc5fd3SVladimir Davydov 	delta *= freeable;
3096b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
310acf92b48SDave Chinner 	total_scan += delta;
311acf92b48SDave Chinner 	if (total_scan < 0) {
3128612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
313a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
314d5bc5fd3SVladimir Davydov 		total_scan = freeable;
315ea164d73SAndrea Arcangeli 	}
316ea164d73SAndrea Arcangeli 
317ea164d73SAndrea Arcangeli 	/*
3183567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3193567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3203567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3213567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3223567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
323d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3243567b59aSDave Chinner 	 * memory.
3253567b59aSDave Chinner 	 *
3263567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3273567b59aSDave Chinner 	 * a large delta change is calculated directly.
3283567b59aSDave Chinner 	 */
329d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
330d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3313567b59aSDave Chinner 
3323567b59aSDave Chinner 	/*
333ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
334ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
335ea164d73SAndrea Arcangeli 	 * freeable entries.
336ea164d73SAndrea Arcangeli 	 */
337d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
338d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3391da177e4SLinus Torvalds 
34024f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3416b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
342d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
34309576073SDave Chinner 
3440b1fb40aSVladimir Davydov 	/*
3450b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3460b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3470b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3480b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3490b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3500b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3510b1fb40aSVladimir Davydov 	 * batch_size.
3520b1fb40aSVladimir Davydov 	 *
3530b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3540b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
355d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3560b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3570b1fb40aSVladimir Davydov 	 * possible.
3580b1fb40aSVladimir Davydov 	 */
3590b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
360d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
36124f7c6b9SDave Chinner 		unsigned long ret;
3620b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3631da177e4SLinus Torvalds 
3640b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
36524f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
36624f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3671da177e4SLinus Torvalds 			break;
36824f7c6b9SDave Chinner 		freed += ret;
36924f7c6b9SDave Chinner 
3700b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3710b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3721da177e4SLinus Torvalds 
3731da177e4SLinus Torvalds 		cond_resched();
3741da177e4SLinus Torvalds 	}
3751da177e4SLinus Torvalds 
376acf92b48SDave Chinner 	/*
377acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
378acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
379acf92b48SDave Chinner 	 * scan, there is no need to do an update.
380acf92b48SDave Chinner 	 */
38183aeeadaSKonstantin Khlebnikov 	if (total_scan > 0)
38283aeeadaSKonstantin Khlebnikov 		new_nr = atomic_long_add_return(total_scan,
3831d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
38483aeeadaSKonstantin Khlebnikov 	else
3851d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
386acf92b48SDave Chinner 
387df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
3881d3d4437SGlauber Costa 	return freed;
3891d3d4437SGlauber Costa }
3901d3d4437SGlauber Costa 
3916b4f7799SJohannes Weiner /**
392cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
3936b4f7799SJohannes Weiner  * @gfp_mask: allocation context
3946b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
395cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
3966b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
3976b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
3981d3d4437SGlauber Costa  *
3996b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4001d3d4437SGlauber Costa  *
4016b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4026b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4031d3d4437SGlauber Costa  *
404cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
405cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4060fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4070fc9f58aSVladimir Davydov  * shrinkers are called.
408cb731d6cSVladimir Davydov  *
4096b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4106b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4116b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4126b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4136b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4146b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4156b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4161d3d4437SGlauber Costa  *
4176b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4181d3d4437SGlauber Costa  */
419cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
420cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4216b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4226b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4231d3d4437SGlauber Costa {
4241d3d4437SGlauber Costa 	struct shrinker *shrinker;
4251d3d4437SGlauber Costa 	unsigned long freed = 0;
4261d3d4437SGlauber Costa 
4270fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
428cb731d6cSVladimir Davydov 		return 0;
429cb731d6cSVladimir Davydov 
4306b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4316b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4321d3d4437SGlauber Costa 
4331d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4341d3d4437SGlauber Costa 		/*
4351d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4361d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4371d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4381d3d4437SGlauber Costa 		 * time.
4391d3d4437SGlauber Costa 		 */
4401d3d4437SGlauber Costa 		freed = 1;
4411d3d4437SGlauber Costa 		goto out;
4421d3d4437SGlauber Costa 	}
4431d3d4437SGlauber Costa 
4441d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4456b4f7799SJohannes Weiner 		struct shrink_control sc = {
4466b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4476b4f7799SJohannes Weiner 			.nid = nid,
448cb731d6cSVladimir Davydov 			.memcg = memcg,
4496b4f7799SJohannes Weiner 		};
4506b4f7799SJohannes Weiner 
4510fc9f58aSVladimir Davydov 		/*
4520fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4530fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4540fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4550fc9f58aSVladimir Davydov 		 */
4560fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4570fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
458cb731d6cSVladimir Davydov 			continue;
459cb731d6cSVladimir Davydov 
4606b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4616b4f7799SJohannes Weiner 			sc.nid = 0;
4626b4f7799SJohannes Weiner 
463cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
464ec97097bSVladimir Davydov 	}
4651d3d4437SGlauber Costa 
4661da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
467f06590bdSMinchan Kim out:
468f06590bdSMinchan Kim 	cond_resched();
46924f7c6b9SDave Chinner 	return freed;
4701da177e4SLinus Torvalds }
4711da177e4SLinus Torvalds 
472cb731d6cSVladimir Davydov void drop_slab_node(int nid)
473cb731d6cSVladimir Davydov {
474cb731d6cSVladimir Davydov 	unsigned long freed;
475cb731d6cSVladimir Davydov 
476cb731d6cSVladimir Davydov 	do {
477cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
478cb731d6cSVladimir Davydov 
479cb731d6cSVladimir Davydov 		freed = 0;
480cb731d6cSVladimir Davydov 		do {
481cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
482cb731d6cSVladimir Davydov 					     1000, 1000);
483cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
484cb731d6cSVladimir Davydov 	} while (freed > 10);
485cb731d6cSVladimir Davydov }
486cb731d6cSVladimir Davydov 
487cb731d6cSVladimir Davydov void drop_slab(void)
488cb731d6cSVladimir Davydov {
489cb731d6cSVladimir Davydov 	int nid;
490cb731d6cSVladimir Davydov 
491cb731d6cSVladimir Davydov 	for_each_online_node(nid)
492cb731d6cSVladimir Davydov 		drop_slab_node(nid);
493cb731d6cSVladimir Davydov }
494cb731d6cSVladimir Davydov 
4951da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
4961da177e4SLinus Torvalds {
497ceddc3a5SJohannes Weiner 	/*
498ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
499ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
500ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
501ceddc3a5SJohannes Weiner 	 */
502edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5031da177e4SLinus Torvalds }
5041da177e4SLinus Torvalds 
505703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5061da177e4SLinus Torvalds {
507930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5081da177e4SLinus Torvalds 		return 1;
509703c2708STejun Heo 	if (!inode_write_congested(inode))
5101da177e4SLinus Torvalds 		return 1;
511703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5121da177e4SLinus Torvalds 		return 1;
5131da177e4SLinus Torvalds 	return 0;
5141da177e4SLinus Torvalds }
5151da177e4SLinus Torvalds 
5161da177e4SLinus Torvalds /*
5171da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5181da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5191da177e4SLinus Torvalds  * fsync(), msync() or close().
5201da177e4SLinus Torvalds  *
5211da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5221da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5231da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5241da177e4SLinus Torvalds  *
5251da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5261da177e4SLinus Torvalds  * __GFP_FS.
5271da177e4SLinus Torvalds  */
5281da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5291da177e4SLinus Torvalds 				struct page *page, int error)
5301da177e4SLinus Torvalds {
5317eaceaccSJens Axboe 	lock_page(page);
5323e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5333e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5341da177e4SLinus Torvalds 	unlock_page(page);
5351da177e4SLinus Torvalds }
5361da177e4SLinus Torvalds 
53704e62a29SChristoph Lameter /* possible outcome of pageout() */
53804e62a29SChristoph Lameter typedef enum {
53904e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
54004e62a29SChristoph Lameter 	PAGE_KEEP,
54104e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
54204e62a29SChristoph Lameter 	PAGE_ACTIVATE,
54304e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
54404e62a29SChristoph Lameter 	PAGE_SUCCESS,
54504e62a29SChristoph Lameter 	/* page is clean and locked */
54604e62a29SChristoph Lameter 	PAGE_CLEAN,
54704e62a29SChristoph Lameter } pageout_t;
54804e62a29SChristoph Lameter 
5491da177e4SLinus Torvalds /*
5501742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5511742f19fSAndrew Morton  * Calls ->writepage().
5521da177e4SLinus Torvalds  */
553c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5547d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5551da177e4SLinus Torvalds {
5561da177e4SLinus Torvalds 	/*
5571da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5581da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5591da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5601da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5611da177e4SLinus Torvalds 	 * PagePrivate for that.
5621da177e4SLinus Torvalds 	 *
5638174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5641da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5651da177e4SLinus Torvalds 	 * will block.
5661da177e4SLinus Torvalds 	 *
5671da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5681da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5691da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5701da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5711da177e4SLinus Torvalds 	 */
5721da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5731da177e4SLinus Torvalds 		return PAGE_KEEP;
5741da177e4SLinus Torvalds 	if (!mapping) {
5751da177e4SLinus Torvalds 		/*
5761da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5771da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5781da177e4SLinus Torvalds 		 */
579266cf658SDavid Howells 		if (page_has_private(page)) {
5801da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5811da177e4SLinus Torvalds 				ClearPageDirty(page);
582b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5831da177e4SLinus Torvalds 				return PAGE_CLEAN;
5841da177e4SLinus Torvalds 			}
5851da177e4SLinus Torvalds 		}
5861da177e4SLinus Torvalds 		return PAGE_KEEP;
5871da177e4SLinus Torvalds 	}
5881da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
5891da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
590703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
5911da177e4SLinus Torvalds 		return PAGE_KEEP;
5921da177e4SLinus Torvalds 
5931da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
5941da177e4SLinus Torvalds 		int res;
5951da177e4SLinus Torvalds 		struct writeback_control wbc = {
5961da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
5971da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
598111ebb6eSOGAWA Hirofumi 			.range_start = 0,
599111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6001da177e4SLinus Torvalds 			.for_reclaim = 1,
6011da177e4SLinus Torvalds 		};
6021da177e4SLinus Torvalds 
6031da177e4SLinus Torvalds 		SetPageReclaim(page);
6041da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6051da177e4SLinus Torvalds 		if (res < 0)
6061da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
607994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6081da177e4SLinus Torvalds 			ClearPageReclaim(page);
6091da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6101da177e4SLinus Torvalds 		}
611c661b078SAndy Whitcroft 
6121da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6131da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6141da177e4SLinus Torvalds 			ClearPageReclaim(page);
6151da177e4SLinus Torvalds 		}
6163aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
617c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6181da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6191da177e4SLinus Torvalds 	}
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds 	return PAGE_CLEAN;
6221da177e4SLinus Torvalds }
6231da177e4SLinus Torvalds 
624a649fd92SAndrew Morton /*
625e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
626e286781dSNick Piggin  * gets returned with a refcount of 0.
627a649fd92SAndrew Morton  */
628a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
629a528910eSJohannes Weiner 			    bool reclaimed)
63049d2e9ccSChristoph Lameter {
631c4843a75SGreg Thelen 	unsigned long flags;
632c4843a75SGreg Thelen 
63328e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
63428e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
63549d2e9ccSChristoph Lameter 
636c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
63749d2e9ccSChristoph Lameter 	/*
6380fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6390fd0e6b0SNick Piggin 	 *
6400fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6410fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6420fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6430fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6440fd0e6b0SNick Piggin 	 *
6450fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6460fd0e6b0SNick Piggin 	 * [user mapping goes away]
6470fd0e6b0SNick Piggin 	 * write_to(page);
6480fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6490fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6500fd0e6b0SNick Piggin 	 * put_page(page);
6510fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6520fd0e6b0SNick Piggin 	 *
6530fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6540fd0e6b0SNick Piggin 	 *
6550fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6560fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6570139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6580fd0e6b0SNick Piggin 	 *
6590fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6600fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
66149d2e9ccSChristoph Lameter 	 */
662fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
66349d2e9ccSChristoph Lameter 		goto cannot_free;
664e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
665e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
666fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
66749d2e9ccSChristoph Lameter 		goto cannot_free;
668e286781dSNick Piggin 	}
66949d2e9ccSChristoph Lameter 
67049d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
67149d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6720a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
67349d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
674c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6750a31bc97SJohannes Weiner 		swapcache_free(swap);
676e286781dSNick Piggin 	} else {
6776072d13cSLinus Torvalds 		void (*freepage)(struct page *);
678a528910eSJohannes Weiner 		void *shadow = NULL;
6796072d13cSLinus Torvalds 
6806072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
681a528910eSJohannes Weiner 		/*
682a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
683a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
684a528910eSJohannes Weiner 		 *
685a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
686a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
687a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
688a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
689a528910eSJohannes Weiner 		 * back.
690f9fe48beSRoss Zwisler 		 *
691f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
692f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
693f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
694f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
695f9fe48beSRoss Zwisler 		 * same page_tree.
696a528910eSJohannes Weiner 		 */
697a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
698f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
699a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
70062cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
701c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7026072d13cSLinus Torvalds 
7036072d13cSLinus Torvalds 		if (freepage != NULL)
7046072d13cSLinus Torvalds 			freepage(page);
705e286781dSNick Piggin 	}
706e286781dSNick Piggin 
70749d2e9ccSChristoph Lameter 	return 1;
70849d2e9ccSChristoph Lameter 
70949d2e9ccSChristoph Lameter cannot_free:
710c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
71149d2e9ccSChristoph Lameter 	return 0;
71249d2e9ccSChristoph Lameter }
71349d2e9ccSChristoph Lameter 
7141da177e4SLinus Torvalds /*
715e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
716e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
717e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
718e286781dSNick Piggin  * this page.
719e286781dSNick Piggin  */
720e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
721e286781dSNick Piggin {
722a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
723e286781dSNick Piggin 		/*
724e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
725e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
726e286781dSNick Piggin 		 * atomic operation.
727e286781dSNick Piggin 		 */
728fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
729e286781dSNick Piggin 		return 1;
730e286781dSNick Piggin 	}
731e286781dSNick Piggin 	return 0;
732e286781dSNick Piggin }
733e286781dSNick Piggin 
734894bc310SLee Schermerhorn /**
735894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
736894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
737894bc310SLee Schermerhorn  *
738894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
739894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
740894bc310SLee Schermerhorn  *
741894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
742894bc310SLee Schermerhorn  */
743894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
744894bc310SLee Schermerhorn {
7450ec3b74cSVlastimil Babka 	bool is_unevictable;
746bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
747894bc310SLee Schermerhorn 
748309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
749894bc310SLee Schermerhorn 
750894bc310SLee Schermerhorn redo:
751894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
752894bc310SLee Schermerhorn 
75339b5f29aSHugh Dickins 	if (page_evictable(page)) {
754894bc310SLee Schermerhorn 		/*
755894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
756894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
757894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
758894bc310SLee Schermerhorn 		 * We know how to handle that.
759894bc310SLee Schermerhorn 		 */
7600ec3b74cSVlastimil Babka 		is_unevictable = false;
761c53954a0SMel Gorman 		lru_cache_add(page);
762894bc310SLee Schermerhorn 	} else {
763894bc310SLee Schermerhorn 		/*
764894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
765894bc310SLee Schermerhorn 		 * list.
766894bc310SLee Schermerhorn 		 */
7670ec3b74cSVlastimil Babka 		is_unevictable = true;
768894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7696a7b9548SJohannes Weiner 		/*
77021ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
77121ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
77221ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
77324513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
77421ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7756a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7766a7b9548SJohannes Weiner 		 *
77721ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7786a7b9548SJohannes Weiner 		 */
7796a7b9548SJohannes Weiner 		smp_mb();
780894bc310SLee Schermerhorn 	}
781894bc310SLee Schermerhorn 
782894bc310SLee Schermerhorn 	/*
783894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
784894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
785894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
786894bc310SLee Schermerhorn 	 */
7870ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
788894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
789894bc310SLee Schermerhorn 			put_page(page);
790894bc310SLee Schermerhorn 			goto redo;
791894bc310SLee Schermerhorn 		}
792894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
793894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
794894bc310SLee Schermerhorn 		 * nothing to do here.
795894bc310SLee Schermerhorn 		 */
796894bc310SLee Schermerhorn 	}
797894bc310SLee Schermerhorn 
7980ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
799bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8000ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
801bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
802bbfd28eeSLee Schermerhorn 
803894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
804894bc310SLee Schermerhorn }
805894bc310SLee Schermerhorn 
806dfc8d636SJohannes Weiner enum page_references {
807dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
808dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
80964574746SJohannes Weiner 	PAGEREF_KEEP,
810dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
811dfc8d636SJohannes Weiner };
812dfc8d636SJohannes Weiner 
813dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
814dfc8d636SJohannes Weiner 						  struct scan_control *sc)
815dfc8d636SJohannes Weiner {
81664574746SJohannes Weiner 	int referenced_ptes, referenced_page;
817dfc8d636SJohannes Weiner 	unsigned long vm_flags;
818dfc8d636SJohannes Weiner 
819c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
820c3ac9a8aSJohannes Weiner 					  &vm_flags);
82164574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
822dfc8d636SJohannes Weiner 
823dfc8d636SJohannes Weiner 	/*
824dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
825dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
826dfc8d636SJohannes Weiner 	 */
827dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
828dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
829dfc8d636SJohannes Weiner 
83064574746SJohannes Weiner 	if (referenced_ptes) {
831e4898273SMichal Hocko 		if (PageSwapBacked(page))
83264574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
83364574746SJohannes Weiner 		/*
83464574746SJohannes Weiner 		 * All mapped pages start out with page table
83564574746SJohannes Weiner 		 * references from the instantiating fault, so we need
83664574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
83764574746SJohannes Weiner 		 * than once.
83864574746SJohannes Weiner 		 *
83964574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
84064574746SJohannes Weiner 		 * inactive list.  Another page table reference will
84164574746SJohannes Weiner 		 * lead to its activation.
84264574746SJohannes Weiner 		 *
84364574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
84464574746SJohannes Weiner 		 * so that recently deactivated but used pages are
84564574746SJohannes Weiner 		 * quickly recovered.
84664574746SJohannes Weiner 		 */
84764574746SJohannes Weiner 		SetPageReferenced(page);
84864574746SJohannes Weiner 
84934dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
850dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
851dfc8d636SJohannes Weiner 
852c909e993SKonstantin Khlebnikov 		/*
853c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
854c909e993SKonstantin Khlebnikov 		 */
855c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
856c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
857c909e993SKonstantin Khlebnikov 
85864574746SJohannes Weiner 		return PAGEREF_KEEP;
85964574746SJohannes Weiner 	}
86064574746SJohannes Weiner 
861dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8622e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
863dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
86464574746SJohannes Weiner 
86564574746SJohannes Weiner 	return PAGEREF_RECLAIM;
866dfc8d636SJohannes Weiner }
867dfc8d636SJohannes Weiner 
868e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
869e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
870e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
871e2be15f6SMel Gorman {
872b4597226SMel Gorman 	struct address_space *mapping;
873b4597226SMel Gorman 
874e2be15f6SMel Gorman 	/*
875e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
876e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
877e2be15f6SMel Gorman 	 */
878e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
879e2be15f6SMel Gorman 		*dirty = false;
880e2be15f6SMel Gorman 		*writeback = false;
881e2be15f6SMel Gorman 		return;
882e2be15f6SMel Gorman 	}
883e2be15f6SMel Gorman 
884e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
885e2be15f6SMel Gorman 	*dirty = PageDirty(page);
886e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
887b4597226SMel Gorman 
888b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
889b4597226SMel Gorman 	if (!page_has_private(page))
890b4597226SMel Gorman 		return;
891b4597226SMel Gorman 
892b4597226SMel Gorman 	mapping = page_mapping(page);
893b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
894b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
895e2be15f6SMel Gorman }
896e2be15f6SMel Gorman 
897e286781dSNick Piggin /*
8981742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8991da177e4SLinus Torvalds  */
9001742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
901599d0c95SMel Gorman 				      struct pglist_data *pgdat,
902f84f6e2bSMel Gorman 				      struct scan_control *sc,
90302c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9048e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
905d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
9068e950282SMel Gorman 				      unsigned long *ret_nr_congested,
90702c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
908b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
90902c6de8dSMinchan Kim 				      bool force_reclaim)
9101da177e4SLinus Torvalds {
9111da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
912abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9131da177e4SLinus Torvalds 	int pgactivate = 0;
914d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
9150e093d99SMel Gorman 	unsigned long nr_dirty = 0;
9160e093d99SMel Gorman 	unsigned long nr_congested = 0;
91705ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
91892df3a72SMel Gorman 	unsigned long nr_writeback = 0;
919b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
9201da177e4SLinus Torvalds 
9211da177e4SLinus Torvalds 	cond_resched();
9221da177e4SLinus Torvalds 
9231da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9241da177e4SLinus Torvalds 		struct address_space *mapping;
9251da177e4SLinus Torvalds 		struct page *page;
9261da177e4SLinus Torvalds 		int may_enter_fs;
92702c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
928e2be15f6SMel Gorman 		bool dirty, writeback;
929854e9ed0SMinchan Kim 		bool lazyfree = false;
930854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9311da177e4SLinus Torvalds 
9321da177e4SLinus Torvalds 		cond_resched();
9331da177e4SLinus Torvalds 
9341da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9351da177e4SLinus Torvalds 		list_del(&page->lru);
9361da177e4SLinus Torvalds 
937529ae9aaSNick Piggin 		if (!trylock_page(page))
9381da177e4SLinus Torvalds 			goto keep;
9391da177e4SLinus Torvalds 
940309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9411da177e4SLinus Torvalds 
9421da177e4SLinus Torvalds 		sc->nr_scanned++;
94380e43426SChristoph Lameter 
94439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
945b291f000SNick Piggin 			goto cull_mlocked;
946894bc310SLee Schermerhorn 
947a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
94880e43426SChristoph Lameter 			goto keep_locked;
94980e43426SChristoph Lameter 
9501da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9511da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9521da177e4SLinus Torvalds 			sc->nr_scanned++;
9531da177e4SLinus Torvalds 
954c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
955c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
956c661b078SAndy Whitcroft 
957e62e384eSMichal Hocko 		/*
958e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
959e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
960e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
961e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
962e2be15f6SMel Gorman 		 */
963e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
964e2be15f6SMel Gorman 		if (dirty || writeback)
965e2be15f6SMel Gorman 			nr_dirty++;
966e2be15f6SMel Gorman 
967e2be15f6SMel Gorman 		if (dirty && !writeback)
968e2be15f6SMel Gorman 			nr_unqueued_dirty++;
969e2be15f6SMel Gorman 
970d04e8acdSMel Gorman 		/*
971d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
972d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
973d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
974d04e8acdSMel Gorman 		 * end of the LRU a second time.
975d04e8acdSMel Gorman 		 */
976e2be15f6SMel Gorman 		mapping = page_mapping(page);
9771da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
978703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
979d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
980e2be15f6SMel Gorman 			nr_congested++;
981e2be15f6SMel Gorman 
982e2be15f6SMel Gorman 		/*
983283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
984283aba9fSMel Gorman 		 * are three cases to consider.
985e62e384eSMichal Hocko 		 *
986283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
987283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
988283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
989283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
990283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
991283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
992283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
993b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
994b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
995c3b94f44SHugh Dickins 		 *
99697c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
997ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
998ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
999ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
100097c9341fSTejun Heo 		 *    reclaim and continue scanning.
1001283aba9fSMel Gorman 		 *
1002ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1003ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1004283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1005283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1006283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1007283aba9fSMel Gorman 		 *    would probably show more reasons.
1008283aba9fSMel Gorman 		 *
10097fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1010283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1011283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1012283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1013283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1014e62e384eSMichal Hocko 		 */
1015283aba9fSMel Gorman 		if (PageWriteback(page)) {
1016283aba9fSMel Gorman 			/* Case 1 above */
1017283aba9fSMel Gorman 			if (current_is_kswapd() &&
1018283aba9fSMel Gorman 			    PageReclaim(page) &&
1019599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1020b1a6f21eSMel Gorman 				nr_immediate++;
1021b1a6f21eSMel Gorman 				goto keep_locked;
1022283aba9fSMel Gorman 
1023283aba9fSMel Gorman 			/* Case 2 above */
102497c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1025ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1026c3b94f44SHugh Dickins 				/*
1027c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1028c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1029c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1030c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1031c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1032c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1033c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1034c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1035c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1036c3b94f44SHugh Dickins 				 */
1037c3b94f44SHugh Dickins 				SetPageReclaim(page);
103892df3a72SMel Gorman 				nr_writeback++;
1039c3b94f44SHugh Dickins 				goto keep_locked;
1040283aba9fSMel Gorman 
1041283aba9fSMel Gorman 			/* Case 3 above */
1042283aba9fSMel Gorman 			} else {
10437fadc820SHugh Dickins 				unlock_page(page);
1044c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10457fadc820SHugh Dickins 				/* then go back and try same page again */
10467fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10477fadc820SHugh Dickins 				continue;
1048e62e384eSMichal Hocko 			}
1049283aba9fSMel Gorman 		}
10501da177e4SLinus Torvalds 
105102c6de8dSMinchan Kim 		if (!force_reclaim)
10526a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
105302c6de8dSMinchan Kim 
1054dfc8d636SJohannes Weiner 		switch (references) {
1055dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10561da177e4SLinus Torvalds 			goto activate_locked;
105764574746SJohannes Weiner 		case PAGEREF_KEEP:
105864574746SJohannes Weiner 			goto keep_locked;
1059dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1060dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1061dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1062dfc8d636SJohannes Weiner 		}
10631da177e4SLinus Torvalds 
10641da177e4SLinus Torvalds 		/*
10651da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10661da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10671da177e4SLinus Torvalds 		 */
1068b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
106963eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
107063eb6b93SHugh Dickins 				goto keep_locked;
10715bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10721da177e4SLinus Torvalds 				goto activate_locked;
1073854e9ed0SMinchan Kim 			lazyfree = true;
107463eb6b93SHugh Dickins 			may_enter_fs = 1;
10751da177e4SLinus Torvalds 
1076e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10771da177e4SLinus Torvalds 			mapping = page_mapping(page);
10787751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
10797751b2daSKirill A. Shutemov 			/* Split file THP */
10807751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
10817751b2daSKirill A. Shutemov 				goto keep_locked;
1082e2be15f6SMel Gorman 		}
10831da177e4SLinus Torvalds 
10847751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
10857751b2daSKirill A. Shutemov 
10861da177e4SLinus Torvalds 		/*
10871da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10881da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10891da177e4SLinus Torvalds 		 */
10901da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1091854e9ed0SMinchan Kim 			switch (ret = try_to_unmap(page, lazyfree ?
1092854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
1093854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH))) {
10941da177e4SLinus Torvalds 			case SWAP_FAIL:
10951da177e4SLinus Torvalds 				goto activate_locked;
10961da177e4SLinus Torvalds 			case SWAP_AGAIN:
10971da177e4SLinus Torvalds 				goto keep_locked;
1098b291f000SNick Piggin 			case SWAP_MLOCK:
1099b291f000SNick Piggin 				goto cull_mlocked;
1100854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1101854e9ed0SMinchan Kim 				goto lazyfree;
11021da177e4SLinus Torvalds 			case SWAP_SUCCESS:
11031da177e4SLinus Torvalds 				; /* try to free the page below */
11041da177e4SLinus Torvalds 			}
11051da177e4SLinus Torvalds 		}
11061da177e4SLinus Torvalds 
11071da177e4SLinus Torvalds 		if (PageDirty(page)) {
1108ee72886dSMel Gorman 			/*
1109ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1110d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1111d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1112ee72886dSMel Gorman 			 */
1113f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11149e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
1115599d0c95SMel Gorman 					 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
111649ea7eb6SMel Gorman 				/*
111749ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
111849ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
111949ea7eb6SMel Gorman 				 * except we already have the page isolated
112049ea7eb6SMel Gorman 				 * and know it's dirty
112149ea7eb6SMel Gorman 				 */
1122c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
112349ea7eb6SMel Gorman 				SetPageReclaim(page);
112449ea7eb6SMel Gorman 
1125ee72886dSMel Gorman 				goto keep_locked;
1126ee72886dSMel Gorman 			}
1127ee72886dSMel Gorman 
1128dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11291da177e4SLinus Torvalds 				goto keep_locked;
11304dd4b920SAndrew Morton 			if (!may_enter_fs)
11311da177e4SLinus Torvalds 				goto keep_locked;
113252a8363eSChristoph Lameter 			if (!sc->may_writepage)
11331da177e4SLinus Torvalds 				goto keep_locked;
11341da177e4SLinus Torvalds 
1135d950c947SMel Gorman 			/*
1136d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1137d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1138d950c947SMel Gorman 			 * starts and then write it out here.
1139d950c947SMel Gorman 			 */
1140d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11417d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11421da177e4SLinus Torvalds 			case PAGE_KEEP:
11431da177e4SLinus Torvalds 				goto keep_locked;
11441da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11451da177e4SLinus Torvalds 				goto activate_locked;
11461da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11477d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
114841ac1999SMel Gorman 					goto keep;
11497d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11501da177e4SLinus Torvalds 					goto keep;
11517d3579e8SKOSAKI Motohiro 
11521da177e4SLinus Torvalds 				/*
11531da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11541da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11551da177e4SLinus Torvalds 				 */
1156529ae9aaSNick Piggin 				if (!trylock_page(page))
11571da177e4SLinus Torvalds 					goto keep;
11581da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11591da177e4SLinus Torvalds 					goto keep_locked;
11601da177e4SLinus Torvalds 				mapping = page_mapping(page);
11611da177e4SLinus Torvalds 			case PAGE_CLEAN:
11621da177e4SLinus Torvalds 				; /* try to free the page below */
11631da177e4SLinus Torvalds 			}
11641da177e4SLinus Torvalds 		}
11651da177e4SLinus Torvalds 
11661da177e4SLinus Torvalds 		/*
11671da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11681da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11691da177e4SLinus Torvalds 		 * the page as well.
11701da177e4SLinus Torvalds 		 *
11711da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11721da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11731da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11741da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11751da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11761da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11771da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11781da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11791da177e4SLinus Torvalds 		 *
11801da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11811da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11821da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11831da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11841da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11851da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11861da177e4SLinus Torvalds 		 */
1187266cf658SDavid Howells 		if (page_has_private(page)) {
11881da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11891da177e4SLinus Torvalds 				goto activate_locked;
1190e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1191e286781dSNick Piggin 				unlock_page(page);
1192e286781dSNick Piggin 				if (put_page_testzero(page))
11931da177e4SLinus Torvalds 					goto free_it;
1194e286781dSNick Piggin 				else {
1195e286781dSNick Piggin 					/*
1196e286781dSNick Piggin 					 * rare race with speculative reference.
1197e286781dSNick Piggin 					 * the speculative reference will free
1198e286781dSNick Piggin 					 * this page shortly, so we may
1199e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1200e286781dSNick Piggin 					 * leave it off the LRU).
1201e286781dSNick Piggin 					 */
1202e286781dSNick Piggin 					nr_reclaimed++;
1203e286781dSNick Piggin 					continue;
1204e286781dSNick Piggin 				}
1205e286781dSNick Piggin 			}
12061da177e4SLinus Torvalds 		}
12071da177e4SLinus Torvalds 
1208854e9ed0SMinchan Kim lazyfree:
1209a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
121049d2e9ccSChristoph Lameter 			goto keep_locked;
12111da177e4SLinus Torvalds 
1212a978d6f5SNick Piggin 		/*
1213a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1214a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1215a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1216a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1217a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1218a978d6f5SNick Piggin 		 */
121948c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1220e286781dSNick Piggin free_it:
1221854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1222854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1223854e9ed0SMinchan Kim 
122405ff5137SAndrew Morton 		nr_reclaimed++;
1225abe4c3b5SMel Gorman 
1226abe4c3b5SMel Gorman 		/*
1227abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1228abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1229abe4c3b5SMel Gorman 		 */
1230abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12311da177e4SLinus Torvalds 		continue;
12321da177e4SLinus Torvalds 
1233b291f000SNick Piggin cull_mlocked:
123463d6c5adSHugh Dickins 		if (PageSwapCache(page))
123563d6c5adSHugh Dickins 			try_to_free_swap(page);
1236b291f000SNick Piggin 		unlock_page(page);
1237c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1238b291f000SNick Piggin 		continue;
1239b291f000SNick Piggin 
12401da177e4SLinus Torvalds activate_locked:
124168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12425ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1243a2c43eedSHugh Dickins 			try_to_free_swap(page);
1244309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12451da177e4SLinus Torvalds 		SetPageActive(page);
12461da177e4SLinus Torvalds 		pgactivate++;
12471da177e4SLinus Torvalds keep_locked:
12481da177e4SLinus Torvalds 		unlock_page(page);
12491da177e4SLinus Torvalds keep:
12501da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1251309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12521da177e4SLinus Torvalds 	}
1253abe4c3b5SMel Gorman 
1254747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
125572b252aeSMel Gorman 	try_to_unmap_flush();
1256b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1257abe4c3b5SMel Gorman 
12581da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1259f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12600a31bc97SJohannes Weiner 
12618e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12628e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1263d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
126492df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1265b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
126605ff5137SAndrew Morton 	return nr_reclaimed;
12671da177e4SLinus Torvalds }
12681da177e4SLinus Torvalds 
126902c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
127002c6de8dSMinchan Kim 					    struct list_head *page_list)
127102c6de8dSMinchan Kim {
127202c6de8dSMinchan Kim 	struct scan_control sc = {
127302c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
127402c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
127502c6de8dSMinchan Kim 		.may_unmap = 1,
127602c6de8dSMinchan Kim 	};
12778e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
127802c6de8dSMinchan Kim 	struct page *page, *next;
127902c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
128002c6de8dSMinchan Kim 
128102c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1282117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1283b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
128402c6de8dSMinchan Kim 			ClearPageActive(page);
128502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
128602c6de8dSMinchan Kim 		}
128702c6de8dSMinchan Kim 	}
128802c6de8dSMinchan Kim 
1289599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
129002c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
12918e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
129202c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1293599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
129402c6de8dSMinchan Kim 	return ret;
129502c6de8dSMinchan Kim }
129602c6de8dSMinchan Kim 
12975ad333ebSAndy Whitcroft /*
12985ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
12995ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13005ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13015ad333ebSAndy Whitcroft  *
13025ad333ebSAndy Whitcroft  * page:	page to consider
13035ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13045ad333ebSAndy Whitcroft  *
13055ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13065ad333ebSAndy Whitcroft  */
1307f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13085ad333ebSAndy Whitcroft {
13095ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13105ad333ebSAndy Whitcroft 
13115ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13125ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13135ad333ebSAndy Whitcroft 		return ret;
13145ad333ebSAndy Whitcroft 
1315e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1316e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1317894bc310SLee Schermerhorn 		return ret;
1318894bc310SLee Schermerhorn 
13195ad333ebSAndy Whitcroft 	ret = -EBUSY;
132008e552c6SKAMEZAWA Hiroyuki 
1321c8244935SMel Gorman 	/*
1322c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1323c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1324c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1325c8244935SMel Gorman 	 *
1326c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1327c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1328c8244935SMel Gorman 	 *
1329c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1330c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1331c8244935SMel Gorman 	 */
1332c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1333c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1334c8244935SMel Gorman 		if (PageWriteback(page))
133539deaf85SMinchan Kim 			return ret;
133639deaf85SMinchan Kim 
1337c8244935SMel Gorman 		if (PageDirty(page)) {
1338c8244935SMel Gorman 			struct address_space *mapping;
1339c8244935SMel Gorman 
1340c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1341c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1342c8244935SMel Gorman 				return ret;
1343c8244935SMel Gorman 
1344c8244935SMel Gorman 			/*
1345c8244935SMel Gorman 			 * Only pages without mappings or that have a
1346c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1347c8244935SMel Gorman 			 * without blocking
1348c8244935SMel Gorman 			 */
1349c8244935SMel Gorman 			mapping = page_mapping(page);
1350c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1351c8244935SMel Gorman 				return ret;
1352c8244935SMel Gorman 		}
1353c8244935SMel Gorman 	}
1354c8244935SMel Gorman 
1355f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1356f80c0673SMinchan Kim 		return ret;
1357f80c0673SMinchan Kim 
13585ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13595ad333ebSAndy Whitcroft 		/*
13605ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13615ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13625ad333ebSAndy Whitcroft 		 * page release code relies on it.
13635ad333ebSAndy Whitcroft 		 */
13645ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13655ad333ebSAndy Whitcroft 		ret = 0;
13665ad333ebSAndy Whitcroft 	}
13675ad333ebSAndy Whitcroft 
13685ad333ebSAndy Whitcroft 	return ret;
13695ad333ebSAndy Whitcroft }
13705ad333ebSAndy Whitcroft 
13717ee36a14SMel Gorman 
13727ee36a14SMel Gorman /*
13737ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
13747ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
13757ee36a14SMel Gorman  */
13767ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
13777ee36a14SMel Gorman 			enum lru_list lru, unsigned long *nr_zone_taken,
13787ee36a14SMel Gorman 			unsigned long nr_taken)
13797ee36a14SMel Gorman {
13807ee36a14SMel Gorman 	int zid;
13817ee36a14SMel Gorman 
13827ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
13837ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
13847ee36a14SMel Gorman 			continue;
13857ee36a14SMel Gorman 
13867ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
13877ee36a14SMel Gorman 	}
13887ee36a14SMel Gorman 
13897ee36a14SMel Gorman #ifdef CONFIG_MEMCG
13907ee36a14SMel Gorman 	mem_cgroup_update_lru_size(lruvec, lru, -nr_taken);
13917ee36a14SMel Gorman #endif
13927ee36a14SMel Gorman }
13937ee36a14SMel Gorman 
139449d2e9ccSChristoph Lameter /*
1395a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
13961da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
13971da177e4SLinus Torvalds  * and working on them outside the LRU lock.
13981da177e4SLinus Torvalds  *
13991da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14001da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14011da177e4SLinus Torvalds  *
14021da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14031da177e4SLinus Torvalds  *
14041da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
14055dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14061da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1407f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1408fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14095ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14103cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14111da177e4SLinus Torvalds  *
14121da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14131da177e4SLinus Torvalds  */
141469e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14155dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1416fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14173cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14181da177e4SLinus Torvalds {
141975b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
142069e05944SAndrew Morton 	unsigned long nr_taken = 0;
1421599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14227cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1423599d0c95SMel Gorman 	unsigned long scan, nr_pages;
1424b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14251da177e4SLinus Torvalds 
14260b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
14270b802f10SVladimir Davydov 					!list_empty(src); scan++) {
14285ad333ebSAndy Whitcroft 		struct page *page;
14295ad333ebSAndy Whitcroft 
14301da177e4SLinus Torvalds 		page = lru_to_page(src);
14311da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14321da177e4SLinus Torvalds 
1433309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14348d438f96SNick Piggin 
1435b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1436b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
14377cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1438b2e18757SMel Gorman 			continue;
1439b2e18757SMel Gorman 		}
1440b2e18757SMel Gorman 
1441f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14425ad333ebSAndy Whitcroft 		case 0:
1443599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1444599d0c95SMel Gorman 			nr_taken += nr_pages;
1445599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14465ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14475ad333ebSAndy Whitcroft 			break;
14487c8ee9a8SNick Piggin 
14495ad333ebSAndy Whitcroft 		case -EBUSY:
14505ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
14515ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
14525ad333ebSAndy Whitcroft 			continue;
14535ad333ebSAndy Whitcroft 
14545ad333ebSAndy Whitcroft 		default:
14555ad333ebSAndy Whitcroft 			BUG();
14565ad333ebSAndy Whitcroft 		}
14575ad333ebSAndy Whitcroft 	}
14581da177e4SLinus Torvalds 
1459b2e18757SMel Gorman 	/*
1460b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1461b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1462b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1463b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1464b2e18757SMel Gorman 	 * system at risk of premature OOM.
1465b2e18757SMel Gorman 	 */
14667cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
14677cc30fcfSMel Gorman 		int zid;
14687cc30fcfSMel Gorman 
1469b2e18757SMel Gorman 		list_splice(&pages_skipped, src);
14707cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14717cc30fcfSMel Gorman 			if (!nr_skipped[zid])
14727cc30fcfSMel Gorman 				continue;
14737cc30fcfSMel Gorman 
14747cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
14757cc30fcfSMel Gorman 		}
14767cc30fcfSMel Gorman 	}
1477f626012dSHugh Dickins 	*nr_scanned = scan;
1478e5146b12SMel Gorman 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, scan,
147975b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
14807ee36a14SMel Gorman 	update_lru_sizes(lruvec, lru, nr_zone_taken, nr_taken);
14811da177e4SLinus Torvalds 	return nr_taken;
14821da177e4SLinus Torvalds }
14831da177e4SLinus Torvalds 
148462695a84SNick Piggin /**
148562695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
148662695a84SNick Piggin  * @page: page to isolate from its LRU list
148762695a84SNick Piggin  *
148862695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
148962695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
149062695a84SNick Piggin  *
149162695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
149262695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
149362695a84SNick Piggin  *
149462695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1495894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1496894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1497894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
149862695a84SNick Piggin  *
149962695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
150062695a84SNick Piggin  * found will be decremented.
150162695a84SNick Piggin  *
150262695a84SNick Piggin  * Restrictions:
150362695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
150462695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
150562695a84SNick Piggin  *     without a stable reference).
150662695a84SNick Piggin  * (2) the lru_lock must not be held.
150762695a84SNick Piggin  * (3) interrupts must be enabled.
150862695a84SNick Piggin  */
150962695a84SNick Piggin int isolate_lru_page(struct page *page)
151062695a84SNick Piggin {
151162695a84SNick Piggin 	int ret = -EBUSY;
151262695a84SNick Piggin 
1513309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1514cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15150c917313SKonstantin Khlebnikov 
151662695a84SNick Piggin 	if (PageLRU(page)) {
151762695a84SNick Piggin 		struct zone *zone = page_zone(page);
1518fa9add64SHugh Dickins 		struct lruvec *lruvec;
151962695a84SNick Piggin 
1520a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1521599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
15220c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1523894bc310SLee Schermerhorn 			int lru = page_lru(page);
15240c917313SKonstantin Khlebnikov 			get_page(page);
152562695a84SNick Piggin 			ClearPageLRU(page);
1526fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1527fa9add64SHugh Dickins 			ret = 0;
152862695a84SNick Piggin 		}
1529a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
153062695a84SNick Piggin 	}
153162695a84SNick Piggin 	return ret;
153262695a84SNick Piggin }
153362695a84SNick Piggin 
15345ad333ebSAndy Whitcroft /*
1535d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1536d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1537d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1538d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1539d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
154035cd7815SRik van Riel  */
1541599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
154235cd7815SRik van Riel 		struct scan_control *sc)
154335cd7815SRik van Riel {
154435cd7815SRik van Riel 	unsigned long inactive, isolated;
154535cd7815SRik van Riel 
154635cd7815SRik van Riel 	if (current_is_kswapd())
154735cd7815SRik van Riel 		return 0;
154835cd7815SRik van Riel 
154997c9341fSTejun Heo 	if (!sane_reclaim(sc))
155035cd7815SRik van Riel 		return 0;
155135cd7815SRik van Riel 
155235cd7815SRik van Riel 	if (file) {
1553599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1554599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
155535cd7815SRik van Riel 	} else {
1556599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1557599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
155835cd7815SRik van Riel 	}
155935cd7815SRik van Riel 
15603cf23841SFengguang Wu 	/*
15613cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
15623cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
15633cf23841SFengguang Wu 	 * deadlock.
15643cf23841SFengguang Wu 	 */
1565d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
15663cf23841SFengguang Wu 		inactive >>= 3;
15673cf23841SFengguang Wu 
156835cd7815SRik van Riel 	return isolated > inactive;
156935cd7815SRik van Riel }
157035cd7815SRik van Riel 
157166635629SMel Gorman static noinline_for_stack void
157275b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
157366635629SMel Gorman {
157427ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1575599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
15763f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
157766635629SMel Gorman 
157866635629SMel Gorman 	/*
157966635629SMel Gorman 	 * Put back any unfreeable pages.
158066635629SMel Gorman 	 */
158166635629SMel Gorman 	while (!list_empty(page_list)) {
15823f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
158366635629SMel Gorman 		int lru;
15843f79768fSHugh Dickins 
1585309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
158666635629SMel Gorman 		list_del(&page->lru);
158739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1588599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
158966635629SMel Gorman 			putback_lru_page(page);
1590599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
159166635629SMel Gorman 			continue;
159266635629SMel Gorman 		}
1593fa9add64SHugh Dickins 
1594599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1595fa9add64SHugh Dickins 
15967a608572SLinus Torvalds 		SetPageLRU(page);
159766635629SMel Gorman 		lru = page_lru(page);
1598fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1599fa9add64SHugh Dickins 
160066635629SMel Gorman 		if (is_active_lru(lru)) {
160166635629SMel Gorman 			int file = is_file_lru(lru);
16029992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16039992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
160466635629SMel Gorman 		}
16052bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16062bcf8879SHugh Dickins 			__ClearPageLRU(page);
16072bcf8879SHugh Dickins 			__ClearPageActive(page);
1608fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16092bcf8879SHugh Dickins 
16102bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1611599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1612747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16132bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1614599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16152bcf8879SHugh Dickins 			} else
16162bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
161766635629SMel Gorman 		}
161866635629SMel Gorman 	}
161966635629SMel Gorman 
16203f79768fSHugh Dickins 	/*
16213f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
16223f79768fSHugh Dickins 	 */
16233f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
162466635629SMel Gorman }
162566635629SMel Gorman 
162666635629SMel Gorman /*
1627399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1628399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1629399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1630399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1631399ba0b9SNeilBrown  */
1632399ba0b9SNeilBrown static int current_may_throttle(void)
1633399ba0b9SNeilBrown {
1634399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1635399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1636399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1637399ba0b9SNeilBrown }
1638399ba0b9SNeilBrown 
1639399ba0b9SNeilBrown /*
1640b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16411742f19fSAndrew Morton  * of reclaimed pages
16421da177e4SLinus Torvalds  */
164366635629SMel Gorman static noinline_for_stack unsigned long
16441a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
16459e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
16461da177e4SLinus Torvalds {
16471da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1648e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
164905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1650e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
16518e950282SMel Gorman 	unsigned long nr_dirty = 0;
16528e950282SMel Gorman 	unsigned long nr_congested = 0;
1653e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
165492df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1655b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1656f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16573cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1658599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16591a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
166078dc583dSKOSAKI Motohiro 
1661599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
166258355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
166335cd7815SRik van Riel 
166435cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
166535cd7815SRik van Riel 		if (fatal_signal_pending(current))
166635cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
166735cd7815SRik van Riel 	}
166835cd7815SRik van Riel 
16691da177e4SLinus Torvalds 	lru_add_drain();
1670f80c0673SMinchan Kim 
1671f80c0673SMinchan Kim 	if (!sc->may_unmap)
167261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1673f80c0673SMinchan Kim 	if (!sc->may_writepage)
167461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1675f80c0673SMinchan Kim 
1676599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
16771da177e4SLinus Torvalds 
16785dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
16795dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
168095d918fcSKonstantin Khlebnikov 
1681599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
16829d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
168395d918fcSKonstantin Khlebnikov 
168489b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1685599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1686b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1687599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
1688b35ea17bSKOSAKI Motohiro 		else
1689599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
1690b35ea17bSKOSAKI Motohiro 	}
1691599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1692d563c050SHillf Danton 
1693d563c050SHillf Danton 	if (nr_taken == 0)
169466635629SMel Gorman 		return 0;
1695b35ea17bSKOSAKI Motohiro 
1696599d0c95SMel Gorman 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, TTU_UNMAP,
16978e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
16988e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1699b1a6f21eSMel Gorman 				false);
1700c661b078SAndy Whitcroft 
1701599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17023f79768fSHugh Dickins 
1703904249aaSYing Han 	if (global_reclaim(sc)) {
1704b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1705599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
1706904249aaSYing Han 		else
1707599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
1708904249aaSYing Han 	}
1709a74609faSNick Piggin 
171027ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
17113f79768fSHugh Dickins 
1712599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
17133f79768fSHugh Dickins 
1714599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
17153f79768fSHugh Dickins 
1716747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1717b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1718e11da5b4SMel Gorman 
171992df3a72SMel Gorman 	/*
172092df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
172192df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
172292df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
172392df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
172492df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
172592df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
172692df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
172792df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
172892df3a72SMel Gorman 	 *
17298e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
17308e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17318e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
173292df3a72SMel Gorman 	 */
1733918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1734599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
173592df3a72SMel Gorman 
1736d43006d5SMel Gorman 	/*
173797c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
173897c9341fSTejun Heo 	 * stalling here.
1739d43006d5SMel Gorman 	 */
174097c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1741b1a6f21eSMel Gorman 		/*
17428e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
17438e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
17448e950282SMel Gorman 		 */
17458e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
1746599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
17478e950282SMel Gorman 
17488e950282SMel Gorman 		/*
1749b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1750b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1751599d0c95SMel Gorman 		 * the pgdat PGDAT_DIRTY and kswapd will start writing pages from
175257054651SJohannes Weiner 		 * reclaim context.
1753b1a6f21eSMel Gorman 		 */
1754b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1755599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1756b1a6f21eSMel Gorman 
1757b1a6f21eSMel Gorman 		/*
1758b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1759b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1760b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1761b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1762b1a6f21eSMel Gorman 		 */
1763b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1764b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1765e2be15f6SMel Gorman 	}
1766d43006d5SMel Gorman 
17678e950282SMel Gorman 	/*
17688e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
17698e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
17708e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
17718e950282SMel Gorman 	 */
1772399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1773399ba0b9SNeilBrown 	    current_may_throttle())
1774599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
17758e950282SMel Gorman 
1776599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1777599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
1778ba5e9579Syalin wang 			sc->priority, file);
177905ff5137SAndrew Morton 	return nr_reclaimed;
17801da177e4SLinus Torvalds }
17811da177e4SLinus Torvalds 
17823bb1a852SMartin Bligh /*
17831cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
17841cfb419bSKAMEZAWA Hiroyuki  *
17851cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
17861cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
17871cfb419bSKAMEZAWA Hiroyuki  *
17881cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1789a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
17901cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1791a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
17921cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
17931cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
17941cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
17951cfb419bSKAMEZAWA Hiroyuki  *
17960139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
17971cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
17981cfb419bSKAMEZAWA Hiroyuki  */
17991cfb419bSKAMEZAWA Hiroyuki 
1800fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
18013eb4140fSWu Fengguang 				     struct list_head *list,
18022bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18033eb4140fSWu Fengguang 				     enum lru_list lru)
18043eb4140fSWu Fengguang {
1805599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18063eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
18073eb4140fSWu Fengguang 	struct page *page;
1808fa9add64SHugh Dickins 	int nr_pages;
18093eb4140fSWu Fengguang 
18103eb4140fSWu Fengguang 	while (!list_empty(list)) {
18113eb4140fSWu Fengguang 		page = lru_to_page(list);
1812599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18133eb4140fSWu Fengguang 
1814309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18153eb4140fSWu Fengguang 		SetPageLRU(page);
18163eb4140fSWu Fengguang 
1817fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1818599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1819925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1820fa9add64SHugh Dickins 		pgmoved += nr_pages;
18213eb4140fSWu Fengguang 
18222bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18232bcf8879SHugh Dickins 			__ClearPageLRU(page);
18242bcf8879SHugh Dickins 			__ClearPageActive(page);
1825fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18262bcf8879SHugh Dickins 
18272bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1828599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1829747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18302bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1831599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18322bcf8879SHugh Dickins 			} else
18332bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18343eb4140fSWu Fengguang 		}
18353eb4140fSWu Fengguang 	}
18369d5e6a9fSHugh Dickins 
18373eb4140fSWu Fengguang 	if (!is_active_lru(lru))
18383eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
18393eb4140fSWu Fengguang }
18401cfb419bSKAMEZAWA Hiroyuki 
1841f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
18421a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1843f16015fbSJohannes Weiner 			       struct scan_control *sc,
18449e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
18451cfb419bSKAMEZAWA Hiroyuki {
184644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1847f626012dSHugh Dickins 	unsigned long nr_scanned;
18486fe6b7e3SWu Fengguang 	unsigned long vm_flags;
18491cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
18508cab4754SWu Fengguang 	LIST_HEAD(l_active);
1851b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
18521cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
18531a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
185444c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1855f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
18563cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1857599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18581cfb419bSKAMEZAWA Hiroyuki 
18591da177e4SLinus Torvalds 	lru_add_drain();
1860f80c0673SMinchan Kim 
1861f80c0673SMinchan Kim 	if (!sc->may_unmap)
186261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1863f80c0673SMinchan Kim 	if (!sc->may_writepage)
186461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1865f80c0673SMinchan Kim 
1866599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1867925b7673SJohannes Weiner 
18685dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
18695dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
187089b5fae5SJohannes Weiner 
1871599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1872b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
18731cfb419bSKAMEZAWA Hiroyuki 
18749d5e6a9fSHugh Dickins 	if (global_reclaim(sc))
1875599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1876599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
18779d5e6a9fSHugh Dickins 
1878599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
18791da177e4SLinus Torvalds 
18801da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
18811da177e4SLinus Torvalds 		cond_resched();
18821da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
18831da177e4SLinus Torvalds 		list_del(&page->lru);
18847e9cd484SRik van Riel 
188539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1886894bc310SLee Schermerhorn 			putback_lru_page(page);
1887894bc310SLee Schermerhorn 			continue;
1888894bc310SLee Schermerhorn 		}
1889894bc310SLee Schermerhorn 
1890cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1891cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1892cc715d99SMel Gorman 				if (page_has_private(page))
1893cc715d99SMel Gorman 					try_to_release_page(page, 0);
1894cc715d99SMel Gorman 				unlock_page(page);
1895cc715d99SMel Gorman 			}
1896cc715d99SMel Gorman 		}
1897cc715d99SMel Gorman 
1898c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1899c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19009992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19018cab4754SWu Fengguang 			/*
19028cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19038cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19048cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19058cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19068cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19078cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19088cab4754SWu Fengguang 			 * so we ignore them here.
19098cab4754SWu Fengguang 			 */
191041e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19118cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19128cab4754SWu Fengguang 				continue;
19138cab4754SWu Fengguang 			}
19148cab4754SWu Fengguang 		}
19157e9cd484SRik van Riel 
19165205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19171da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19181da177e4SLinus Torvalds 	}
19191da177e4SLinus Torvalds 
1920b555749aSAndrew Morton 	/*
19218cab4754SWu Fengguang 	 * Move pages back to the lru list.
1922b555749aSAndrew Morton 	 */
1923599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19244f98a2feSRik van Riel 	/*
19258cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19268cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19278cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19287c0db9e9SJerome Marchand 	 * get_scan_count.
1929556adecbSRik van Riel 	 */
1930b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1931556adecbSRik van Riel 
1932fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1933fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1934599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1935599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19362bcf8879SHugh Dickins 
1937747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1938b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
19391da177e4SLinus Torvalds }
19401da177e4SLinus Torvalds 
194159dc76b0SRik van Riel /*
194259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
194359dc76b0SRik van Riel  * to do too much work.
194414797e23SKOSAKI Motohiro  *
194559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
194659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
194759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
194859dc76b0SRik van Riel  *
194959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
195059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
195159dc76b0SRik van Riel  *
195259dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
195359dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
195459dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
195559dc76b0SRik van Riel  *
195659dc76b0SRik van Riel  * total     target    max
195759dc76b0SRik van Riel  * memory    ratio     inactive
195859dc76b0SRik van Riel  * -------------------------------------
195959dc76b0SRik van Riel  *   10MB       1         5MB
196059dc76b0SRik van Riel  *  100MB       1        50MB
196159dc76b0SRik van Riel  *    1GB       3       250MB
196259dc76b0SRik van Riel  *   10GB      10       0.9GB
196359dc76b0SRik van Riel  *  100GB      31         3GB
196459dc76b0SRik van Riel  *    1TB     101        10GB
196559dc76b0SRik van Riel  *   10TB     320        32GB
196614797e23SKOSAKI Motohiro  */
196759dc76b0SRik van Riel static bool inactive_list_is_low(struct lruvec *lruvec, bool file)
196814797e23SKOSAKI Motohiro {
196959dc76b0SRik van Riel 	unsigned long inactive_ratio;
197059dc76b0SRik van Riel 	unsigned long inactive;
197159dc76b0SRik van Riel 	unsigned long active;
197259dc76b0SRik van Riel 	unsigned long gb;
197359dc76b0SRik van Riel 
197474e3f3c3SMinchan Kim 	/*
197574e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
197674e3f3c3SMinchan Kim 	 * is pointless.
197774e3f3c3SMinchan Kim 	 */
197859dc76b0SRik van Riel 	if (!file && !total_swap_pages)
197942e2e457SYaowei Bai 		return false;
198074e3f3c3SMinchan Kim 
198159dc76b0SRik van Riel 	inactive = lruvec_lru_size(lruvec, file * LRU_FILE);
198259dc76b0SRik van Riel 	active = lruvec_lru_size(lruvec, file * LRU_FILE + LRU_ACTIVE);
1983f16015fbSJohannes Weiner 
198459dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
198559dc76b0SRik van Riel 	if (gb)
198659dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
1987b39415b2SRik van Riel 	else
198859dc76b0SRik van Riel 		inactive_ratio = 1;
198959dc76b0SRik van Riel 
199059dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
1991b39415b2SRik van Riel }
1992b39415b2SRik van Riel 
19934f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
19941a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
1995b69408e8SChristoph Lameter {
1996b39415b2SRik van Riel 	if (is_active_lru(lru)) {
199759dc76b0SRik van Riel 		if (inactive_list_is_low(lruvec, is_file_lru(lru)))
19981a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
1999556adecbSRik van Riel 		return 0;
2000556adecbSRik van Riel 	}
2001556adecbSRik van Riel 
20021a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2003b69408e8SChristoph Lameter }
2004b69408e8SChristoph Lameter 
20059a265114SJohannes Weiner enum scan_balance {
20069a265114SJohannes Weiner 	SCAN_EQUAL,
20079a265114SJohannes Weiner 	SCAN_FRACT,
20089a265114SJohannes Weiner 	SCAN_ANON,
20099a265114SJohannes Weiner 	SCAN_FILE,
20109a265114SJohannes Weiner };
20119a265114SJohannes Weiner 
20121da177e4SLinus Torvalds /*
20134f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
20144f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
20154f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
20164f98a2feSRik van Riel  * onto the active list instead of evict.
20174f98a2feSRik van Riel  *
2018be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2019be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
20204f98a2feSRik van Riel  */
202133377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
20226b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
20236b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
20244f98a2feSRik van Riel {
202533377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
202690126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20279a265114SJohannes Weiner 	u64 fraction[2];
20289a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2029599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20309a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
20319a265114SJohannes Weiner 	enum scan_balance scan_balance;
20320bf1457fSJohannes Weiner 	unsigned long anon, file;
20339a265114SJohannes Weiner 	bool force_scan = false;
20349a265114SJohannes Weiner 	unsigned long ap, fp;
20359a265114SJohannes Weiner 	enum lru_list lru;
20366f04f48dSSuleiman Souhlal 	bool some_scanned;
20376f04f48dSSuleiman Souhlal 	int pass;
2038246e87a9SKAMEZAWA Hiroyuki 
2039f11c0ca5SJohannes Weiner 	/*
2040f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
2041f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
2042f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
2043f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
2044f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
2045f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
2046f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
2047f11c0ca5SJohannes Weiner 	 * well.
2048f11c0ca5SJohannes Weiner 	 */
204990cbc250SVladimir Davydov 	if (current_is_kswapd()) {
2050599d0c95SMel Gorman 		if (!pgdat_reclaimable(pgdat))
2051a4d3e9e7SJohannes Weiner 			force_scan = true;
2052eb01aaabSVladimir Davydov 		if (!mem_cgroup_online(memcg))
205390cbc250SVladimir Davydov 			force_scan = true;
205490cbc250SVladimir Davydov 	}
205589b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
2056a4d3e9e7SJohannes Weiner 		force_scan = true;
205776a33fc3SShaohua Li 
205876a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2059d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
20609a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
206176a33fc3SShaohua Li 		goto out;
206276a33fc3SShaohua Li 	}
20634f98a2feSRik van Riel 
206410316b31SJohannes Weiner 	/*
206510316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
206610316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
206710316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
206810316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
206910316b31SJohannes Weiner 	 * too expensive.
207010316b31SJohannes Weiner 	 */
207102695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
20729a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
207310316b31SJohannes Weiner 		goto out;
207410316b31SJohannes Weiner 	}
207510316b31SJohannes Weiner 
207610316b31SJohannes Weiner 	/*
207710316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
207810316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
207910316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
208010316b31SJohannes Weiner 	 */
208102695175SJohannes Weiner 	if (!sc->priority && swappiness) {
20829a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
208310316b31SJohannes Weiner 		goto out;
208410316b31SJohannes Weiner 	}
208510316b31SJohannes Weiner 
208611d16c25SJohannes Weiner 	/*
208762376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
208862376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
208962376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
209062376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
209162376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
209262376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
209362376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
209462376251SJohannes Weiner 	 */
209562376251SJohannes Weiner 	if (global_reclaim(sc)) {
2096599d0c95SMel Gorman 		unsigned long pgdatfile;
2097599d0c95SMel Gorman 		unsigned long pgdatfree;
2098599d0c95SMel Gorman 		int z;
2099599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
210062376251SJohannes Weiner 
2101599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2102599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2103599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21042ab051e1SJerome Marchand 
2105599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2106599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
2107599d0c95SMel Gorman 			if (!populated_zone(zone))
2108599d0c95SMel Gorman 				continue;
2109599d0c95SMel Gorman 
2110599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2111599d0c95SMel Gorman 		}
2112599d0c95SMel Gorman 
2113599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
211462376251SJohannes Weiner 			scan_balance = SCAN_ANON;
211562376251SJohannes Weiner 			goto out;
211662376251SJohannes Weiner 		}
211762376251SJohannes Weiner 	}
211862376251SJohannes Weiner 
211962376251SJohannes Weiner 	/*
2120316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2121316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2122316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2123316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2124316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2125316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2126316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2127e9868505SRik van Riel 	 */
212859dc76b0SRik van Riel 	if (!inactive_list_is_low(lruvec, true) &&
212923047a96SJohannes Weiner 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
21309a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2131e9868505SRik van Riel 		goto out;
21324f98a2feSRik van Riel 	}
21334f98a2feSRik van Riel 
21349a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
21359a265114SJohannes Weiner 
21364f98a2feSRik van Riel 	/*
213758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
213858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
213958c37f6eSKOSAKI Motohiro 	 */
214002695175SJohannes Weiner 	anon_prio = swappiness;
214175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
214258c37f6eSKOSAKI Motohiro 
214358c37f6eSKOSAKI Motohiro 	/*
21444f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
21454f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
21464f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
21474f98a2feSRik van Riel 	 *
21484f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
21494f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
21504f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
21514f98a2feSRik van Riel 	 *
21524f98a2feSRik van Riel 	 * anon in [0], file in [1]
21534f98a2feSRik van Riel 	 */
21542ab051e1SJerome Marchand 
215523047a96SJohannes Weiner 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
215623047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
215723047a96SJohannes Weiner 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
215823047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
21592ab051e1SJerome Marchand 
2160599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
216158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
21626e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
21636e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
21644f98a2feSRik van Riel 	}
21654f98a2feSRik van Riel 
21666e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
21676e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
21686e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
21694f98a2feSRik van Riel 	}
21704f98a2feSRik van Riel 
21714f98a2feSRik van Riel 	/*
217200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
217300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
217400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
21754f98a2feSRik van Riel 	 */
2176fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
21776e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
21784f98a2feSRik van Riel 
2179fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
21806e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2181599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21824f98a2feSRik van Riel 
218376a33fc3SShaohua Li 	fraction[0] = ap;
218476a33fc3SShaohua Li 	fraction[1] = fp;
218576a33fc3SShaohua Li 	denominator = ap + fp + 1;
218676a33fc3SShaohua Li out:
21876f04f48dSSuleiman Souhlal 	some_scanned = false;
21886f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
21896f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
21906b4f7799SJohannes Weiner 		*lru_pages = 0;
21914111304dSHugh Dickins 		for_each_evictable_lru(lru) {
21924111304dSHugh Dickins 			int file = is_file_lru(lru);
2193d778df51SJohannes Weiner 			unsigned long size;
219476a33fc3SShaohua Li 			unsigned long scan;
219576a33fc3SShaohua Li 
219623047a96SJohannes Weiner 			size = lruvec_lru_size(lruvec, lru);
2197d778df51SJohannes Weiner 			scan = size >> sc->priority;
21989a265114SJohannes Weiner 
21996f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2200d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
22019a265114SJohannes Weiner 
22029a265114SJohannes Weiner 			switch (scan_balance) {
22039a265114SJohannes Weiner 			case SCAN_EQUAL:
22049a265114SJohannes Weiner 				/* Scan lists relative to size */
22059a265114SJohannes Weiner 				break;
22069a265114SJohannes Weiner 			case SCAN_FRACT:
22079a265114SJohannes Weiner 				/*
22089a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
22099a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
22109a265114SJohannes Weiner 				 */
22116f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
22126f04f48dSSuleiman Souhlal 							denominator);
22139a265114SJohannes Weiner 				break;
22149a265114SJohannes Weiner 			case SCAN_FILE:
22159a265114SJohannes Weiner 			case SCAN_ANON:
22169a265114SJohannes Weiner 				/* Scan one type exclusively */
22176b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
22186b4f7799SJohannes Weiner 					size = 0;
22199a265114SJohannes Weiner 					scan = 0;
22206b4f7799SJohannes Weiner 				}
22219a265114SJohannes Weiner 				break;
22229a265114SJohannes Weiner 			default:
22239a265114SJohannes Weiner 				/* Look ma, no brain */
22249a265114SJohannes Weiner 				BUG();
22259a265114SJohannes Weiner 			}
22266b4f7799SJohannes Weiner 
22276b4f7799SJohannes Weiner 			*lru_pages += size;
22284111304dSHugh Dickins 			nr[lru] = scan;
22296b4f7799SJohannes Weiner 
22306f04f48dSSuleiman Souhlal 			/*
22316f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
22326f04f48dSSuleiman Souhlal 			 * if we found something to scan.
22336f04f48dSSuleiman Souhlal 			 */
22346f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
22356f04f48dSSuleiman Souhlal 		}
223676a33fc3SShaohua Li 	}
22376e08a369SWu Fengguang }
22384f98a2feSRik van Riel 
223972b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
224072b252aeSMel Gorman static void init_tlb_ubc(void)
224172b252aeSMel Gorman {
224272b252aeSMel Gorman 	/*
224372b252aeSMel Gorman 	 * This deliberately does not clear the cpumask as it's expensive
224472b252aeSMel Gorman 	 * and unnecessary. If there happens to be data in there then the
224572b252aeSMel Gorman 	 * first SWAP_CLUSTER_MAX pages will send an unnecessary IPI and
224672b252aeSMel Gorman 	 * then will be cleared.
224772b252aeSMel Gorman 	 */
224872b252aeSMel Gorman 	current->tlb_ubc.flush_required = false;
224972b252aeSMel Gorman }
225072b252aeSMel Gorman #else
225172b252aeSMel Gorman static inline void init_tlb_ubc(void)
225272b252aeSMel Gorman {
225372b252aeSMel Gorman }
225472b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
225572b252aeSMel Gorman 
22569b4f98cdSJohannes Weiner /*
2257a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
22589b4f98cdSJohannes Weiner  */
2259a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
22606b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
22619b4f98cdSJohannes Weiner {
2262ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
22639b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2264e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
22659b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
22669b4f98cdSJohannes Weiner 	enum lru_list lru;
22679b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
22689b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
22699b4f98cdSJohannes Weiner 	struct blk_plug plug;
22701a501907SMel Gorman 	bool scan_adjusted;
22719b4f98cdSJohannes Weiner 
227233377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
22739b4f98cdSJohannes Weiner 
2274e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2275e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2276e82e0561SMel Gorman 
22771a501907SMel Gorman 	/*
22781a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
22791a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
22801a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
22811a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
22821a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
22831a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
22841a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
22851a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
22861a501907SMel Gorman 	 * dropped to zero at the first pass.
22871a501907SMel Gorman 	 */
22881a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
22891a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
22901a501907SMel Gorman 
229172b252aeSMel Gorman 	init_tlb_ubc();
229272b252aeSMel Gorman 
22939b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
22949b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
22959b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2296e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2297e82e0561SMel Gorman 		unsigned long nr_scanned;
2298e82e0561SMel Gorman 
22999b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23009b4f98cdSJohannes Weiner 			if (nr[lru]) {
23019b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23029b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23039b4f98cdSJohannes Weiner 
23049b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23059b4f98cdSJohannes Weiner 							    lruvec, sc);
23069b4f98cdSJohannes Weiner 			}
23079b4f98cdSJohannes Weiner 		}
2308e82e0561SMel Gorman 
2309e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2310e82e0561SMel Gorman 			continue;
2311e82e0561SMel Gorman 
23129b4f98cdSJohannes Weiner 		/*
2313e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23141a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2315e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2316e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2317e82e0561SMel Gorman 		 * proportional to the original scan target.
2318e82e0561SMel Gorman 		 */
2319e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2320e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2321e82e0561SMel Gorman 
23221a501907SMel Gorman 		/*
23231a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23241a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23251a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23261a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23271a501907SMel Gorman 		 */
23281a501907SMel Gorman 		if (!nr_file || !nr_anon)
23291a501907SMel Gorman 			break;
23301a501907SMel Gorman 
2331e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2332e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2333e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2334e82e0561SMel Gorman 			lru = LRU_BASE;
2335e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2336e82e0561SMel Gorman 		} else {
2337e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2338e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2339e82e0561SMel Gorman 			lru = LRU_FILE;
2340e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2341e82e0561SMel Gorman 		}
2342e82e0561SMel Gorman 
2343e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2344e82e0561SMel Gorman 		nr[lru] = 0;
2345e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2346e82e0561SMel Gorman 
2347e82e0561SMel Gorman 		/*
2348e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2349e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2350e82e0561SMel Gorman 		 */
2351e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2352e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2353e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2354e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2355e82e0561SMel Gorman 
2356e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2357e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2358e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2359e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2360e82e0561SMel Gorman 
2361e82e0561SMel Gorman 		scan_adjusted = true;
23629b4f98cdSJohannes Weiner 	}
23639b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
23649b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
23659b4f98cdSJohannes Weiner 
23669b4f98cdSJohannes Weiner 	/*
23679b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
23689b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
23699b4f98cdSJohannes Weiner 	 */
237059dc76b0SRik van Riel 	if (inactive_list_is_low(lruvec, false))
23719b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
23729b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
23739b4f98cdSJohannes Weiner 
23749b4f98cdSJohannes Weiner 	throttle_vm_writeout(sc->gfp_mask);
23759b4f98cdSJohannes Weiner }
23769b4f98cdSJohannes Weiner 
237723b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
23789e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
237923b9da55SMel Gorman {
2380d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
238123b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
23829e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
238323b9da55SMel Gorman 		return true;
238423b9da55SMel Gorman 
238523b9da55SMel Gorman 	return false;
238623b9da55SMel Gorman }
238723b9da55SMel Gorman 
23884f98a2feSRik van Riel /*
238923b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
239023b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
239123b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
239223b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
239323b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
23943e7d3449SMel Gorman  */
2395a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
23963e7d3449SMel Gorman 					unsigned long nr_reclaimed,
23973e7d3449SMel Gorman 					unsigned long nr_scanned,
23983e7d3449SMel Gorman 					struct scan_control *sc)
23993e7d3449SMel Gorman {
24003e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24013e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2402a9dd0a83SMel Gorman 	int z;
24033e7d3449SMel Gorman 
24043e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24059e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24063e7d3449SMel Gorman 		return false;
24073e7d3449SMel Gorman 
24082876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
24092876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
24103e7d3449SMel Gorman 		/*
24112876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
24122876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24132876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
24142876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
24153e7d3449SMel Gorman 		 */
24163e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24173e7d3449SMel Gorman 			return false;
24182876592fSMel Gorman 	} else {
24192876592fSMel Gorman 		/*
24202876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
24212876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24222876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24232876592fSMel Gorman 		 * pages that were scanned. This will return to the
24242876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24252876592fSMel Gorman 		 * the resulting allocation attempt fails
24262876592fSMel Gorman 		 */
24272876592fSMel Gorman 		if (!nr_reclaimed)
24282876592fSMel Gorman 			return false;
24292876592fSMel Gorman 	}
24303e7d3449SMel Gorman 
24313e7d3449SMel Gorman 	/*
24323e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24333e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24343e7d3449SMel Gorman 	 */
24353e7d3449SMel Gorman 	pages_for_compaction = (2UL << sc->order);
2436a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2437ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2438a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
24393e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24403e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24413e7d3449SMel Gorman 		return true;
24423e7d3449SMel Gorman 
24433e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2444a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2445a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
2446a9dd0a83SMel Gorman 		if (!populated_zone(zone))
2447a9dd0a83SMel Gorman 			continue;
2448a9dd0a83SMel Gorman 
2449a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
24503e7d3449SMel Gorman 		case COMPACT_PARTIAL:
24513e7d3449SMel Gorman 		case COMPACT_CONTINUE:
24523e7d3449SMel Gorman 			return false;
24533e7d3449SMel Gorman 		default:
2454a9dd0a83SMel Gorman 			/* check next zone */
2455a9dd0a83SMel Gorman 			;
24563e7d3449SMel Gorman 		}
24573e7d3449SMel Gorman 	}
2458a9dd0a83SMel Gorman 	return true;
2459a9dd0a83SMel Gorman }
24603e7d3449SMel Gorman 
2461970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2462f16015fbSJohannes Weiner {
2463cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
24649b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
24652344d7e4SJohannes Weiner 	bool reclaimable = false;
24669b4f98cdSJohannes Weiner 
24679b4f98cdSJohannes Weiner 	do {
24685660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
24695660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2470ef8f2327SMel Gorman 			.pgdat = pgdat,
24719e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
24725660048cSJohannes Weiner 		};
2473a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2474694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
24755660048cSJohannes Weiner 
24769b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
24779b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
24789b4f98cdSJohannes Weiner 
2479694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2480694fbc0fSAndrew Morton 		do {
24816b4f7799SJohannes Weiner 			unsigned long lru_pages;
24828e8ae645SJohannes Weiner 			unsigned long reclaimed;
2483cb731d6cSVladimir Davydov 			unsigned long scanned;
24849b4f98cdSJohannes Weiner 
2485241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2486241994edSJohannes Weiner 				if (!sc->may_thrash)
2487241994edSJohannes Weiner 					continue;
2488241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2489241994edSJohannes Weiner 			}
2490241994edSJohannes Weiner 
24918e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2492cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
24935660048cSJohannes Weiner 
2494a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2495a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2496f9be23d6SKonstantin Khlebnikov 
2497b2e18757SMel Gorman 			if (!global_reclaim(sc))
2498a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
2499cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2500cb731d6cSVladimir Davydov 					    lru_pages);
2501cb731d6cSVladimir Davydov 
25028e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25038e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25048e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25058e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25068e8ae645SJohannes Weiner 
25075660048cSJohannes Weiner 			/*
2508a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2509a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2510a9dd0a83SMel Gorman 			 * node.
2511a394cb8eSMichal Hocko 			 *
2512a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2513a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2514a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2515a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25165660048cSJohannes Weiner 			 */
2517a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2518a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25195660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25205660048cSJohannes Weiner 				break;
25215660048cSJohannes Weiner 			}
2522241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
252370ddf637SAnton Vorontsov 
25246b4f7799SJohannes Weiner 		/*
25256b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
25266b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
25276b4f7799SJohannes Weiner 		 */
2528b2e18757SMel Gorman 		if (global_reclaim(sc))
2529a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25306b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
2531a9dd0a83SMel Gorman 				    node_lru_pages);
25326b4f7799SJohannes Weiner 
25336b4f7799SJohannes Weiner 		if (reclaim_state) {
2534cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25356b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25366b4f7799SJohannes Weiner 		}
25376b4f7799SJohannes Weiner 
25388e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25398e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
254070ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
254170ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
254270ddf637SAnton Vorontsov 
25432344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
25442344d7e4SJohannes Weiner 			reclaimable = true;
25452344d7e4SJohannes Weiner 
2546a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
25479b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
25482344d7e4SJohannes Weiner 
25492344d7e4SJohannes Weiner 	return reclaimable;
2550f16015fbSJohannes Weiner }
2551f16015fbSJohannes Weiner 
255253853e2dSVlastimil Babka /*
255353853e2dSVlastimil Babka  * Returns true if compaction should go ahead for a high-order request, or
255453853e2dSVlastimil Babka  * the high-order allocation would succeed without compaction.
255553853e2dSVlastimil Babka  */
25564f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2557fe4b1b24SMel Gorman {
255831483b6aSMel Gorman 	unsigned long watermark;
2559fe4b1b24SMel Gorman 	bool watermark_ok;
2560fe4b1b24SMel Gorman 
2561fe4b1b24SMel Gorman 	/*
2562fe4b1b24SMel Gorman 	 * Compaction takes time to run and there are potentially other
2563fe4b1b24SMel Gorman 	 * callers using the pages just freed. Continue reclaiming until
2564fe4b1b24SMel Gorman 	 * there is a buffer of free pages available to give compaction
2565fe4b1b24SMel Gorman 	 * a reasonable chance of completing and allocating the page
2566fe4b1b24SMel Gorman 	 */
25674f588331SMel Gorman 	watermark = high_wmark_pages(zone) + (2UL << sc->order);
25684f588331SMel Gorman 	watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2569fe4b1b24SMel Gorman 
2570fe4b1b24SMel Gorman 	/*
2571fe4b1b24SMel Gorman 	 * If compaction is deferred, reclaim up to a point where
2572fe4b1b24SMel Gorman 	 * compaction will have a chance of success when re-enabled
2573fe4b1b24SMel Gorman 	 */
25744f588331SMel Gorman 	if (compaction_deferred(zone, sc->order))
2575fe4b1b24SMel Gorman 		return watermark_ok;
2576fe4b1b24SMel Gorman 
257753853e2dSVlastimil Babka 	/*
257853853e2dSVlastimil Babka 	 * If compaction is not ready to start and allocation is not likely
257953853e2dSVlastimil Babka 	 * to succeed without it, then keep reclaiming.
258053853e2dSVlastimil Babka 	 */
25814f588331SMel Gorman 	if (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx) == COMPACT_SKIPPED)
2582fe4b1b24SMel Gorman 		return false;
2583fe4b1b24SMel Gorman 
2584fe4b1b24SMel Gorman 	return watermark_ok;
2585fe4b1b24SMel Gorman }
2586fe4b1b24SMel Gorman 
25871da177e4SLinus Torvalds /*
25881da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
25891da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
25901da177e4SLinus Torvalds  * request.
25911da177e4SLinus Torvalds  *
25921da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
25931da177e4SLinus Torvalds  * scan then give up on it.
25941da177e4SLinus Torvalds  */
25950a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
25961da177e4SLinus Torvalds {
2597dd1a239fSMel Gorman 	struct zoneref *z;
259854a6eb5cSMel Gorman 	struct zone *zone;
25990608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26000608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2601619d0d76SWeijie Yang 	gfp_t orig_mask;
260279dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
26031cfb419bSKAMEZAWA Hiroyuki 
2604cc715d99SMel Gorman 	/*
2605cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2606cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2607cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2608cc715d99SMel Gorman 	 */
2609619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2610b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2611cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
26124f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2613b2e18757SMel Gorman 	}
2614cc715d99SMel Gorman 
2615d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2616b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2617b2e18757SMel Gorman 		/*
26181cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26191cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26201cfb419bSKAMEZAWA Hiroyuki 		 */
262189b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2622344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2623344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26241da177e4SLinus Torvalds 				continue;
262565ec02cbSVladimir Davydov 
26266e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
2627599d0c95SMel Gorman 			    !pgdat_reclaimable(zone->zone_pgdat))
26281da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
26290b06496aSJohannes Weiner 
2630e0887c19SRik van Riel 			/*
2631e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2632e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2633e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2634e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2635e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2636c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2637c7cfa37bSCopot Alexandru 			 * page allocations.
2638e0887c19SRik van Riel 			 */
26390b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
26400b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
26414f588331SMel Gorman 			    compaction_ready(zone, sc)) {
26420b06496aSJohannes Weiner 				sc->compaction_ready = true;
2643e0887c19SRik van Riel 				continue;
2644e0887c19SRik van Riel 			}
26450b06496aSJohannes Weiner 
26460608f43dSAndrew Morton 			/*
264779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
264879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
264979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
265079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
265179dafcdcSMel Gorman 			 */
265279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
265379dafcdcSMel Gorman 				continue;
265479dafcdcSMel Gorman 
265579dafcdcSMel Gorman 			/*
26560608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
26570608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
26580608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
26590608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
26600608f43dSAndrew Morton 			 */
26610608f43dSAndrew Morton 			nr_soft_scanned = 0;
2662ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
26630608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
26640608f43dSAndrew Morton 						&nr_soft_scanned);
26650608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
26660608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2667ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2668ac34a1a3SKAMEZAWA Hiroyuki 		}
2669d149e3b2SYing Han 
267079dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
267179dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
267279dafcdcSMel Gorman 			continue;
267379dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2674970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
26751da177e4SLinus Torvalds 	}
2676e0c23279SMel Gorman 
267765ec02cbSVladimir Davydov 	/*
2678619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2679619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2680619d0d76SWeijie Yang 	 */
2681619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
26821da177e4SLinus Torvalds }
26831da177e4SLinus Torvalds 
26841da177e4SLinus Torvalds /*
26851da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
26861da177e4SLinus Torvalds  *
26871da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
26881da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
26891da177e4SLinus Torvalds  *
26901da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
26911da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
26925b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
26935b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
26945b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
26955b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2696a41f24eaSNishanth Aravamudan  *
2697a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2698a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
26991da177e4SLinus Torvalds  */
2700dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
27013115cd91SVladimir Davydov 					  struct scan_control *sc)
27021da177e4SLinus Torvalds {
2703241994edSJohannes Weiner 	int initial_priority = sc->priority;
270469e05944SAndrew Morton 	unsigned long total_scanned = 0;
270522fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
2706241994edSJohannes Weiner retry:
2707873b4771SKeika Kobayashi 	delayacct_freepages_start();
2708873b4771SKeika Kobayashi 
270989b5fae5SJohannes Weiner 	if (global_reclaim(sc))
27107cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
27111da177e4SLinus Torvalds 
27129e3b2f8cSKonstantin Khlebnikov 	do {
271370ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
271470ddf637SAnton Vorontsov 				sc->priority);
271566e1707bSBalbir Singh 		sc->nr_scanned = 0;
27160a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2717e0c23279SMel Gorman 
271866e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2719bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
27200b06496aSJohannes Weiner 			break;
27210b06496aSJohannes Weiner 
27220b06496aSJohannes Weiner 		if (sc->compaction_ready)
27230b06496aSJohannes Weiner 			break;
27241da177e4SLinus Torvalds 
27251da177e4SLinus Torvalds 		/*
27260e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27270e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27280e50ce3bSMinchan Kim 		 */
27290e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27300e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27310e50ce3bSMinchan Kim 
27320e50ce3bSMinchan Kim 		/*
27331da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
27341da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
27351da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
27361da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
27371da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
27381da177e4SLinus Torvalds 		 */
273922fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
274022fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
27410e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
27420e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
274366e1707bSBalbir Singh 			sc->may_writepage = 1;
27441da177e4SLinus Torvalds 		}
27450b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2746bb21c7ceSKOSAKI Motohiro 
2747873b4771SKeika Kobayashi 	delayacct_freepages_end();
2748873b4771SKeika Kobayashi 
2749bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2750bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2751bb21c7ceSKOSAKI Motohiro 
27520cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
27530b06496aSJohannes Weiner 	if (sc->compaction_ready)
27547335084dSMel Gorman 		return 1;
27557335084dSMel Gorman 
2756241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2757241994edSJohannes Weiner 	if (!sc->may_thrash) {
2758241994edSJohannes Weiner 		sc->priority = initial_priority;
2759241994edSJohannes Weiner 		sc->may_thrash = 1;
2760241994edSJohannes Weiner 		goto retry;
2761241994edSJohannes Weiner 	}
2762241994edSJohannes Weiner 
2763bb21c7ceSKOSAKI Motohiro 	return 0;
27641da177e4SLinus Torvalds }
27651da177e4SLinus Torvalds 
27665515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
27675515061dSMel Gorman {
27685515061dSMel Gorman 	struct zone *zone;
27695515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
27705515061dSMel Gorman 	unsigned long free_pages = 0;
27715515061dSMel Gorman 	int i;
27725515061dSMel Gorman 	bool wmark_ok;
27735515061dSMel Gorman 
27745515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
27755515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2776f012a84aSNishanth Aravamudan 		if (!populated_zone(zone) ||
2777599d0c95SMel Gorman 		    pgdat_reclaimable_pages(pgdat) == 0)
2778675becceSMel Gorman 			continue;
2779675becceSMel Gorman 
27805515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
27815515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
27825515061dSMel Gorman 	}
27835515061dSMel Gorman 
2784675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2785675becceSMel Gorman 	if (!pfmemalloc_reserve)
2786675becceSMel Gorman 		return true;
2787675becceSMel Gorman 
27885515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
27895515061dSMel Gorman 
27905515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
27915515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
279238087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
27935515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
27945515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
27955515061dSMel Gorman 	}
27965515061dSMel Gorman 
27975515061dSMel Gorman 	return wmark_ok;
27985515061dSMel Gorman }
27995515061dSMel Gorman 
28005515061dSMel Gorman /*
28015515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
28025515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
28035515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
280450694c28SMel Gorman  * when the low watermark is reached.
280550694c28SMel Gorman  *
280650694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
280750694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
28085515061dSMel Gorman  */
280950694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
28105515061dSMel Gorman 					nodemask_t *nodemask)
28115515061dSMel Gorman {
2812675becceSMel Gorman 	struct zoneref *z;
28135515061dSMel Gorman 	struct zone *zone;
2814675becceSMel Gorman 	pg_data_t *pgdat = NULL;
28155515061dSMel Gorman 
28165515061dSMel Gorman 	/*
28175515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
28185515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
28195515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
28205515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
28215515061dSMel Gorman 	 * processes to block on log_wait_commit().
28225515061dSMel Gorman 	 */
28235515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
282450694c28SMel Gorman 		goto out;
282550694c28SMel Gorman 
282650694c28SMel Gorman 	/*
282750694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
282850694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
282950694c28SMel Gorman 	 */
283050694c28SMel Gorman 	if (fatal_signal_pending(current))
283150694c28SMel Gorman 		goto out;
28325515061dSMel Gorman 
2833675becceSMel Gorman 	/*
2834675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2835675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2836675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2837675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2838675becceSMel Gorman 	 *
2839675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2840675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2841675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2842675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2843675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2844675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2845675becceSMel Gorman 	 * should make reasonable progress.
2846675becceSMel Gorman 	 */
2847675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
284817636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2849675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2850675becceSMel Gorman 			continue;
2851675becceSMel Gorman 
2852675becceSMel Gorman 		/* Throttle based on the first usable node */
28535515061dSMel Gorman 		pgdat = zone->zone_pgdat;
28545515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
285550694c28SMel Gorman 			goto out;
2856675becceSMel Gorman 		break;
2857675becceSMel Gorman 	}
2858675becceSMel Gorman 
2859675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2860675becceSMel Gorman 	if (!pgdat)
2861675becceSMel Gorman 		goto out;
28625515061dSMel Gorman 
286368243e76SMel Gorman 	/* Account for the throttling */
286468243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
286568243e76SMel Gorman 
28665515061dSMel Gorman 	/*
28675515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
28685515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
28695515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
28705515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
28715515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
28725515061dSMel Gorman 	 * second before continuing.
28735515061dSMel Gorman 	 */
28745515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
28755515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
28765515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
287750694c28SMel Gorman 
287850694c28SMel Gorman 		goto check_pending;
28795515061dSMel Gorman 	}
28805515061dSMel Gorman 
28815515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
28825515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
28835515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
288450694c28SMel Gorman 
288550694c28SMel Gorman check_pending:
288650694c28SMel Gorman 	if (fatal_signal_pending(current))
288750694c28SMel Gorman 		return true;
288850694c28SMel Gorman 
288950694c28SMel Gorman out:
289050694c28SMel Gorman 	return false;
28915515061dSMel Gorman }
28925515061dSMel Gorman 
2893dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2894327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
289566e1707bSBalbir Singh {
289633906bc5SMel Gorman 	unsigned long nr_reclaimed;
289766e1707bSBalbir Singh 	struct scan_control sc = {
289822fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2899ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2900b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2901ee814fe2SJohannes Weiner 		.order = order,
2902ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2903ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2904ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2905a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29062e2e4259SKOSAKI Motohiro 		.may_swap = 1,
290766e1707bSBalbir Singh 	};
290866e1707bSBalbir Singh 
29095515061dSMel Gorman 	/*
291050694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
291150694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
291250694c28SMel Gorman 	 * point.
29135515061dSMel Gorman 	 */
291450694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
29155515061dSMel Gorman 		return 1;
29165515061dSMel Gorman 
291733906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
291833906bc5SMel Gorman 				sc.may_writepage,
2919e5146b12SMel Gorman 				gfp_mask,
2920e5146b12SMel Gorman 				sc.reclaim_idx);
292133906bc5SMel Gorman 
29223115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
292333906bc5SMel Gorman 
292433906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
292533906bc5SMel Gorman 
292633906bc5SMel Gorman 	return nr_reclaimed;
292766e1707bSBalbir Singh }
292866e1707bSBalbir Singh 
2929c255a458SAndrew Morton #ifdef CONFIG_MEMCG
293066e1707bSBalbir Singh 
2931a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
29324e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
2933ef8f2327SMel Gorman 						pg_data_t *pgdat,
29340ae5e89cSYing Han 						unsigned long *nr_scanned)
29354e416953SBalbir Singh {
29364e416953SBalbir Singh 	struct scan_control sc = {
2937b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2938ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
29394e416953SBalbir Singh 		.may_writepage = !laptop_mode,
29404e416953SBalbir Singh 		.may_unmap = 1,
2941b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
29424e416953SBalbir Singh 		.may_swap = !noswap,
29434e416953SBalbir Singh 	};
29446b4f7799SJohannes Weiner 	unsigned long lru_pages;
29450ae5e89cSYing Han 
29464e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
29474e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2948bdce6d9eSKOSAKI Motohiro 
29499e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2950bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2951e5146b12SMel Gorman 						      sc.gfp_mask,
2952e5146b12SMel Gorman 						      sc.reclaim_idx);
2953bdce6d9eSKOSAKI Motohiro 
29544e416953SBalbir Singh 	/*
29554e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
29564e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
2957a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
29584e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
29594e416953SBalbir Singh 	 * the priority and make it zero.
29604e416953SBalbir Singh 	 */
2961ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
2962bdce6d9eSKOSAKI Motohiro 
2963bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2964bdce6d9eSKOSAKI Motohiro 
29650ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
29664e416953SBalbir Singh 	return sc.nr_reclaimed;
29674e416953SBalbir Singh }
29684e416953SBalbir Singh 
296972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2970b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
29718c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2972b70a2a21SJohannes Weiner 					   bool may_swap)
297366e1707bSBalbir Singh {
29744e416953SBalbir Singh 	struct zonelist *zonelist;
2975bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2976889976dbSYing Han 	int nid;
297766e1707bSBalbir Singh 	struct scan_control sc = {
2978b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2979ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2980ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2981b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
2982ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2983ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
298466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2985a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2986b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2987a09ed5e0SYing Han 	};
298866e1707bSBalbir Singh 
2989889976dbSYing Han 	/*
2990889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2991889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
2992889976dbSYing Han 	 * scan does not need to be the current node.
2993889976dbSYing Han 	 */
299472835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
2995889976dbSYing Han 
2996889976dbSYing Han 	zonelist = NODE_DATA(nid)->node_zonelists;
2997bdce6d9eSKOSAKI Motohiro 
2998bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
2999bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3000e5146b12SMel Gorman 					    sc.gfp_mask,
3001e5146b12SMel Gorman 					    sc.reclaim_idx);
3002bdce6d9eSKOSAKI Motohiro 
30033115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3004bdce6d9eSKOSAKI Motohiro 
3005bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3006bdce6d9eSKOSAKI Motohiro 
3007bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
300866e1707bSBalbir Singh }
300966e1707bSBalbir Singh #endif
301066e1707bSBalbir Singh 
30111d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3012ef8f2327SMel Gorman 				struct scan_control *sc)
3013f16015fbSJohannes Weiner {
3014b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3015b95a2f2dSJohannes Weiner 
3016b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3017b95a2f2dSJohannes Weiner 		return;
3018b95a2f2dSJohannes Weiner 
3019b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3020b95a2f2dSJohannes Weiner 	do {
3021ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3022f16015fbSJohannes Weiner 
302359dc76b0SRik van Riel 		if (inactive_list_is_low(lruvec, false))
30241a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30259e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3026b95a2f2dSJohannes Weiner 
3027b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3028b95a2f2dSJohannes Weiner 	} while (memcg);
3029f16015fbSJohannes Weiner }
3030f16015fbSJohannes Weiner 
303131483b6aSMel Gorman static bool zone_balanced(struct zone *zone, int order, int classzone_idx)
303260cefed4SJohannes Weiner {
303331483b6aSMel Gorman 	unsigned long mark = high_wmark_pages(zone);
303460cefed4SJohannes Weiner 
30356256c6b4SMel Gorman 	if (!zone_watermark_ok_safe(zone, order, mark, classzone_idx))
30366256c6b4SMel Gorman 		return false;
30376256c6b4SMel Gorman 
30386256c6b4SMel Gorman 	/*
30396256c6b4SMel Gorman 	 * If any eligible zone is balanced then the node is not considered
30406256c6b4SMel Gorman 	 * to be congested or dirty
30416256c6b4SMel Gorman 	 */
30426256c6b4SMel Gorman 	clear_bit(PGDAT_CONGESTED, &zone->zone_pgdat->flags);
30436256c6b4SMel Gorman 	clear_bit(PGDAT_DIRTY, &zone->zone_pgdat->flags);
30446256c6b4SMel Gorman 
30456256c6b4SMel Gorman 	return true;
304660cefed4SJohannes Weiner }
304760cefed4SJohannes Weiner 
30481741c877SMel Gorman /*
30495515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30505515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30515515061dSMel Gorman  *
30525515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30535515061dSMel Gorman  */
3054d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3055f50de2d3SMel Gorman {
30561d82de61SMel Gorman 	int i;
30571d82de61SMel Gorman 
30585515061dSMel Gorman 	/*
30599e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
30609e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
30619e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
30629e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
30639e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
30649e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
30659e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
30669e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
30679e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
30689e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
30699e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
30705515061dSMel Gorman 	 */
30719e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
30729e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3073f50de2d3SMel Gorman 
30741d82de61SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
30751d82de61SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
30761d82de61SMel Gorman 
30771d82de61SMel Gorman 		if (!populated_zone(zone))
30781d82de61SMel Gorman 			continue;
30791d82de61SMel Gorman 
308038087d9bSMel Gorman 		if (!zone_balanced(zone, order, classzone_idx))
308138087d9bSMel Gorman 			return false;
30821d82de61SMel Gorman 	}
30831d82de61SMel Gorman 
308438087d9bSMel Gorman 	return true;
3085f50de2d3SMel Gorman }
3086f50de2d3SMel Gorman 
30871da177e4SLinus Torvalds /*
30881d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
30891d82de61SMel Gorman  * zone that is currently unbalanced.
3090b8e83b94SMel Gorman  *
3091b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3092283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3093283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
309475485363SMel Gorman  */
30951d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3096accf6242SVlastimil Babka 			       struct scan_control *sc)
309775485363SMel Gorman {
30981d82de61SMel Gorman 	struct zone *zone;
30991d82de61SMel Gorman 	int z;
310075485363SMel Gorman 
31011d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
31021d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3103970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
31041d82de61SMel Gorman 		zone = pgdat->node_zones + z;
31051d82de61SMel Gorman 		if (!populated_zone(zone))
31061d82de61SMel Gorman 			continue;
31077c954f6dSMel Gorman 
31081d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
31097c954f6dSMel Gorman 	}
31107c954f6dSMel Gorman 
31111d82de61SMel Gorman 	/*
31121d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
31131d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
31141d82de61SMel Gorman 	 */
3115970a39a3SMel Gorman 	shrink_node(pgdat, sc);
31161d82de61SMel Gorman 
31171d82de61SMel Gorman 	/*
31181d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
31191d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
31201d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
31211d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
31221d82de61SMel Gorman 	 * can direct reclaim/compact.
31231d82de61SMel Gorman 	 */
31241d82de61SMel Gorman 	if (sc->order && sc->nr_reclaimed >= 2UL << sc->order)
31251d82de61SMel Gorman 		sc->order = 0;
31261d82de61SMel Gorman 
3127b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
312875485363SMel Gorman }
312975485363SMel Gorman 
313075485363SMel Gorman /*
31311d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
31321d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
31331d82de61SMel Gorman  * balanced.
31341da177e4SLinus Torvalds  *
31351d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
31361da177e4SLinus Torvalds  *
31371da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
313841858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
31391d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
31401d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
31411d82de61SMel Gorman  * balanced.
31421da177e4SLinus Torvalds  */
3143accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
31441da177e4SLinus Torvalds {
31451da177e4SLinus Torvalds 	int i;
31460608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31470608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
31481d82de61SMel Gorman 	struct zone *zone;
3149179e9639SAndrew Morton 	struct scan_control sc = {
3150179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3151ee814fe2SJohannes Weiner 		.order = order,
3152b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3153ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3154a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31552e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3156179e9639SAndrew Morton 	};
3157f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
31581da177e4SLinus Torvalds 
31599e3b2f8cSKonstantin Khlebnikov 	do {
3160b8e83b94SMel Gorman 		bool raise_priority = true;
3161b8e83b94SMel Gorman 
3162b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
316384c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
31641da177e4SLinus Torvalds 
316586c79f6bSMel Gorman 		/*
316684c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
316784c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
316884c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
316984c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
317084c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
317184c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
317284c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
317384c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
317486c79f6bSMel Gorman 		 */
317586c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
317686c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
317786c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
317886c79f6bSMel Gorman 				if (!populated_zone(zone))
317986c79f6bSMel Gorman 					continue;
318086c79f6bSMel Gorman 
3181970a39a3SMel Gorman 				sc.reclaim_idx = i;
318286c79f6bSMel Gorman 				break;
318386c79f6bSMel Gorman 			}
318486c79f6bSMel Gorman 		}
318586c79f6bSMel Gorman 
318686c79f6bSMel Gorman 		/*
318786c79f6bSMel Gorman 		 * Only reclaim if there are no eligible zones. Check from
318886c79f6bSMel Gorman 		 * high to low zone as allocations prefer higher zones.
318986c79f6bSMel Gorman 		 * Scanning from low to high zone would allow congestion to be
319086c79f6bSMel Gorman 		 * cleared during a very small window when a small low
319186c79f6bSMel Gorman 		 * zone was balanced even under extreme pressure when the
319284c7a777SMel Gorman 		 * overall node may be congested. Note that sc.reclaim_idx
319384c7a777SMel Gorman 		 * is not used as buffer_heads_over_limit may have adjusted
319484c7a777SMel Gorman 		 * it.
319586c79f6bSMel Gorman 		 */
319684c7a777SMel Gorman 		for (i = classzone_idx; i >= 0; i--) {
31971d82de61SMel Gorman 			zone = pgdat->node_zones + i;
3198f3fe6512SCon Kolivas 			if (!populated_zone(zone))
31991da177e4SLinus Torvalds 				continue;
32001da177e4SLinus Torvalds 
320184c7a777SMel Gorman 			if (zone_balanced(zone, sc.order, classzone_idx))
32021da177e4SLinus Torvalds 				goto out;
320386c79f6bSMel Gorman 		}
3204e1dbeda6SAndrew Morton 
32051da177e4SLinus Torvalds 		/*
32061d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
32071d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
32081d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
32091d82de61SMel Gorman 		 * about consistent aging.
32101d82de61SMel Gorman 		 */
3211ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
32121d82de61SMel Gorman 
32131d82de61SMel Gorman 		/*
3214b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3215b7ea3c41SMel Gorman 		 * even in laptop mode.
3216b7ea3c41SMel Gorman 		 */
32171d82de61SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2 || !pgdat_reclaimable(pgdat))
3218b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3219b7ea3c41SMel Gorman 
32201d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
32211da177e4SLinus Torvalds 		sc.nr_scanned = 0;
32220608f43dSAndrew Morton 		nr_soft_scanned = 0;
3223ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
32241d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
32250608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
32260608f43dSAndrew Morton 
322732a4330dSRik van Riel 		/*
32281d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
32291d82de61SMel Gorman 		 * enough pages are already being scanned that that high
32301d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
323132a4330dSRik van Riel 		 */
3232970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3233b8e83b94SMel Gorman 			raise_priority = false;
3234d7868daeSMel Gorman 
32355515061dSMel Gorman 		/*
32365515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32375515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32385515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32395515061dSMel Gorman 		 */
32405515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
32415515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3242cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32435515061dSMel Gorman 
3244b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3245b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3246b8e83b94SMel Gorman 			break;
3247b8e83b94SMel Gorman 
3248b8e83b94SMel Gorman 		/*
3249b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3250b8e83b94SMel Gorman 		 * progress in reclaiming pages
3251b8e83b94SMel Gorman 		 */
3252b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3253b8e83b94SMel Gorman 			sc.priority--;
32541d82de61SMel Gorman 	} while (sc.priority >= 1);
32551da177e4SLinus Torvalds 
3256b8e83b94SMel Gorman out:
32570abdee2bSMel Gorman 	/*
32581d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
32591d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
32601d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
32611d82de61SMel Gorman 	 * remain at the higher level.
32620abdee2bSMel Gorman 	 */
32631d82de61SMel Gorman 	return sc.order;
32641da177e4SLinus Torvalds }
32651da177e4SLinus Torvalds 
326638087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
326738087d9bSMel Gorman 				unsigned int classzone_idx)
3268f0bc0a60SKOSAKI Motohiro {
3269f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3270f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3271f0bc0a60SKOSAKI Motohiro 
3272f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3273f0bc0a60SKOSAKI Motohiro 		return;
3274f0bc0a60SKOSAKI Motohiro 
3275f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3276f0bc0a60SKOSAKI Motohiro 
3277f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3278d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3279fd901c95SVlastimil Babka 		/*
3280fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3281fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3282fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3283fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3284fd901c95SVlastimil Babka 		 */
3285fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3286fd901c95SVlastimil Babka 
3287fd901c95SVlastimil Babka 		/*
3288fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3289fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3290fd901c95SVlastimil Babka 		 */
329138087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3292fd901c95SVlastimil Babka 
3293f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
329438087d9bSMel Gorman 
329538087d9bSMel Gorman 		/*
329638087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
329738087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
329838087d9bSMel Gorman 		 * the previous request that slept prematurely.
329938087d9bSMel Gorman 		 */
330038087d9bSMel Gorman 		if (remaining) {
330138087d9bSMel Gorman 			pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
330238087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
330338087d9bSMel Gorman 		}
330438087d9bSMel Gorman 
3305f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3306f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3307f0bc0a60SKOSAKI Motohiro 	}
3308f0bc0a60SKOSAKI Motohiro 
3309f0bc0a60SKOSAKI Motohiro 	/*
3310f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3311f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3312f0bc0a60SKOSAKI Motohiro 	 */
3313d9f21d42SMel Gorman 	if (!remaining &&
3314d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3315f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3316f0bc0a60SKOSAKI Motohiro 
3317f0bc0a60SKOSAKI Motohiro 		/*
3318f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3319f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3320f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3321f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3322f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3323f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3324f0bc0a60SKOSAKI Motohiro 		 */
3325f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33261c7e7f6cSAaditya Kumar 
33271c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3328f0bc0a60SKOSAKI Motohiro 			schedule();
33291c7e7f6cSAaditya Kumar 
3330f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3331f0bc0a60SKOSAKI Motohiro 	} else {
3332f0bc0a60SKOSAKI Motohiro 		if (remaining)
3333f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3334f0bc0a60SKOSAKI Motohiro 		else
3335f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3336f0bc0a60SKOSAKI Motohiro 	}
3337f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3338f0bc0a60SKOSAKI Motohiro }
3339f0bc0a60SKOSAKI Motohiro 
33401da177e4SLinus Torvalds /*
33411da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33421da177e4SLinus Torvalds  * from the init process.
33431da177e4SLinus Torvalds  *
33441da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33451da177e4SLinus Torvalds  * free memory available even if there is no other activity
33461da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33471da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33481da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33491da177e4SLinus Torvalds  *
33501da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33511da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33521da177e4SLinus Torvalds  */
33531da177e4SLinus Torvalds static int kswapd(void *p)
33541da177e4SLinus Torvalds {
335538087d9bSMel Gorman 	unsigned int alloc_order, reclaim_order, classzone_idx;
33561da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
33571da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3358f0bc0a60SKOSAKI Motohiro 
33591da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
33601da177e4SLinus Torvalds 		.reclaimed_slab = 0,
33611da177e4SLinus Torvalds 	};
3362a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
33631da177e4SLinus Torvalds 
3364cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3365cf40bd16SNick Piggin 
3366174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3367c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
33681da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
33691da177e4SLinus Torvalds 
33701da177e4SLinus Torvalds 	/*
33711da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
33721da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
33731da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
33741da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
33751da177e4SLinus Torvalds 	 *
33761da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
33771da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
33781da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
33791da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
33801da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
33811da177e4SLinus Torvalds 	 */
3382930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
338383144186SRafael J. Wysocki 	set_freezable();
33841da177e4SLinus Torvalds 
338538087d9bSMel Gorman 	pgdat->kswapd_order = alloc_order = reclaim_order = 0;
338638087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = classzone_idx = 0;
33871da177e4SLinus Torvalds 	for ( ; ; ) {
33886f6313d4SJeff Liu 		bool ret;
33893e1d1d28SChristoph Lameter 
339038087d9bSMel Gorman kswapd_try_sleep:
339138087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
339238087d9bSMel Gorman 					classzone_idx);
3393215ddd66SMel Gorman 
339438087d9bSMel Gorman 		/* Read the new order and classzone_idx */
339538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
339638087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
339738087d9bSMel Gorman 		pgdat->kswapd_order = 0;
339838087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = 0;
33991da177e4SLinus Torvalds 
34008fe23e05SDavid Rientjes 		ret = try_to_freeze();
34018fe23e05SDavid Rientjes 		if (kthread_should_stop())
34028fe23e05SDavid Rientjes 			break;
34038fe23e05SDavid Rientjes 
34048fe23e05SDavid Rientjes 		/*
34058fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34068fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3407b1296cc4SRafael J. Wysocki 		 */
340838087d9bSMel Gorman 		if (ret)
340938087d9bSMel Gorman 			continue;
34101d82de61SMel Gorman 
341138087d9bSMel Gorman 		/*
341238087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
341338087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
341438087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
341538087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
341638087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
341738087d9bSMel Gorman 		 * request (alloc_order).
341838087d9bSMel Gorman 		 */
3419e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3420e5146b12SMel Gorman 						alloc_order);
342138087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
342238087d9bSMel Gorman 		if (reclaim_order < alloc_order)
342338087d9bSMel Gorman 			goto kswapd_try_sleep;
342438087d9bSMel Gorman 
342538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
342638087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
342733906bc5SMel Gorman 	}
3428b0a8cc58STakamori Yamaguchi 
342971abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3430b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
343171abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
343271abdc15SJohannes Weiner 
34331da177e4SLinus Torvalds 	return 0;
34341da177e4SLinus Torvalds }
34351da177e4SLinus Torvalds 
34361da177e4SLinus Torvalds /*
34371da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34381da177e4SLinus Torvalds  */
343999504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34401da177e4SLinus Torvalds {
34411da177e4SLinus Torvalds 	pg_data_t *pgdat;
3442e1a55637SMel Gorman 	int z;
34431da177e4SLinus Torvalds 
3444f3fe6512SCon Kolivas 	if (!populated_zone(zone))
34451da177e4SLinus Torvalds 		return;
34461da177e4SLinus Torvalds 
3447344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34481da177e4SLinus Torvalds 		return;
344988f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
345038087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
345138087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
34528d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34531da177e4SLinus Torvalds 		return;
3454e1a55637SMel Gorman 
3455e1a55637SMel Gorman 	/* Only wake kswapd if all zones are unbalanced */
3456e1a55637SMel Gorman 	for (z = 0; z <= classzone_idx; z++) {
3457e1a55637SMel Gorman 		zone = pgdat->node_zones + z;
3458e1a55637SMel Gorman 		if (!populated_zone(zone))
3459e1a55637SMel Gorman 			continue;
3460e1a55637SMel Gorman 
3461e1a55637SMel Gorman 		if (zone_balanced(zone, order, classzone_idx))
346288f5acf8SMel Gorman 			return;
3463e1a55637SMel Gorman 	}
346488f5acf8SMel Gorman 
346588f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
34668d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
34671da177e4SLinus Torvalds }
34681da177e4SLinus Torvalds 
3469c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
34701da177e4SLinus Torvalds /*
34717b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3472d6277db4SRafael J. Wysocki  * freed pages.
3473d6277db4SRafael J. Wysocki  *
3474d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3475d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3476d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
34771da177e4SLinus Torvalds  */
34787b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
34791da177e4SLinus Torvalds {
3480d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3481d6277db4SRafael J. Wysocki 	struct scan_control sc = {
34827b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3483ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3484b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
34859e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3486ee814fe2SJohannes Weiner 		.may_writepage = 1,
3487ee814fe2SJohannes Weiner 		.may_unmap = 1,
3488ee814fe2SJohannes Weiner 		.may_swap = 1,
3489ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
34901da177e4SLinus Torvalds 	};
34917b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
34927b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
34937b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
34941da177e4SLinus Torvalds 
34957b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
34967b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3497d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
34987b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3499d6277db4SRafael J. Wysocki 
35003115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3501d6277db4SRafael J. Wysocki 
35027b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35037b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35047b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3505d6277db4SRafael J. Wysocki 
35067b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35071da177e4SLinus Torvalds }
3508c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35091da177e4SLinus Torvalds 
35101da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35111da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35121da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35131da177e4SLinus Torvalds    restore their cpu bindings. */
3514fcb35a9bSGreg Kroah-Hartman static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3515fcb35a9bSGreg Kroah-Hartman 			void *hcpu)
35161da177e4SLinus Torvalds {
351758c0a4a7SYasunori Goto 	int nid;
35181da177e4SLinus Torvalds 
35198bb78442SRafael J. Wysocki 	if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
352048fb2e24SLai Jiangshan 		for_each_node_state(nid, N_MEMORY) {
3521c5f59f08SMike Travis 			pg_data_t *pgdat = NODE_DATA(nid);
3522a70f7302SRusty Russell 			const struct cpumask *mask;
3523a70f7302SRusty Russell 
3524a70f7302SRusty Russell 			mask = cpumask_of_node(pgdat->node_id);
3525c5f59f08SMike Travis 
35263e597945SRusty Russell 			if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35271da177e4SLinus Torvalds 				/* One of our CPUs online: restore mask */
3528c5f59f08SMike Travis 				set_cpus_allowed_ptr(pgdat->kswapd, mask);
35291da177e4SLinus Torvalds 		}
35301da177e4SLinus Torvalds 	}
35311da177e4SLinus Torvalds 	return NOTIFY_OK;
35321da177e4SLinus Torvalds }
35331da177e4SLinus Torvalds 
35343218ae14SYasunori Goto /*
35353218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35363218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35373218ae14SYasunori Goto  */
35383218ae14SYasunori Goto int kswapd_run(int nid)
35393218ae14SYasunori Goto {
35403218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35413218ae14SYasunori Goto 	int ret = 0;
35423218ae14SYasunori Goto 
35433218ae14SYasunori Goto 	if (pgdat->kswapd)
35443218ae14SYasunori Goto 		return 0;
35453218ae14SYasunori Goto 
35463218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35473218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35483218ae14SYasunori Goto 		/* failure at boot is fatal */
35493218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3550d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3551d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3552d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35533218ae14SYasunori Goto 	}
35543218ae14SYasunori Goto 	return ret;
35553218ae14SYasunori Goto }
35563218ae14SYasunori Goto 
35578fe23e05SDavid Rientjes /*
3558d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3559bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
35608fe23e05SDavid Rientjes  */
35618fe23e05SDavid Rientjes void kswapd_stop(int nid)
35628fe23e05SDavid Rientjes {
35638fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
35648fe23e05SDavid Rientjes 
3565d8adde17SJiang Liu 	if (kswapd) {
35668fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3567d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3568d8adde17SJiang Liu 	}
35698fe23e05SDavid Rientjes }
35708fe23e05SDavid Rientjes 
35711da177e4SLinus Torvalds static int __init kswapd_init(void)
35721da177e4SLinus Torvalds {
35733218ae14SYasunori Goto 	int nid;
357469e05944SAndrew Morton 
35751da177e4SLinus Torvalds 	swap_setup();
357648fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
35773218ae14SYasunori Goto  		kswapd_run(nid);
35781da177e4SLinus Torvalds 	hotcpu_notifier(cpu_callback, 0);
35791da177e4SLinus Torvalds 	return 0;
35801da177e4SLinus Torvalds }
35811da177e4SLinus Torvalds 
35821da177e4SLinus Torvalds module_init(kswapd_init)
35839eeff239SChristoph Lameter 
35849eeff239SChristoph Lameter #ifdef CONFIG_NUMA
35859eeff239SChristoph Lameter /*
3586a5f5f91dSMel Gorman  * Node reclaim mode
35879eeff239SChristoph Lameter  *
3588a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
35899eeff239SChristoph Lameter  * the watermarks.
35909eeff239SChristoph Lameter  */
3591a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
35929eeff239SChristoph Lameter 
35931b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
35947d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
35951b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
359695bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
35971b2ffb78SChristoph Lameter 
35989eeff239SChristoph Lameter /*
3599a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3600a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3601a92f7126SChristoph Lameter  * a zone.
3602a92f7126SChristoph Lameter  */
3603a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3604a92f7126SChristoph Lameter 
36059eeff239SChristoph Lameter /*
3606a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
36079614634fSChristoph Lameter  * occur.
36089614634fSChristoph Lameter  */
36099614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36109614634fSChristoph Lameter 
36119614634fSChristoph Lameter /*
36120ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36130ff38490SChristoph Lameter  * slab reclaim needs to occur.
36140ff38490SChristoph Lameter  */
36150ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36160ff38490SChristoph Lameter 
361711fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
361890afa5deSMel Gorman {
361911fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
362011fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
362111fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
362290afa5deSMel Gorman 
362390afa5deSMel Gorman 	/*
362490afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
362590afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
362690afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
362790afa5deSMel Gorman 	 */
362890afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
362990afa5deSMel Gorman }
363090afa5deSMel Gorman 
363190afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3632a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
363390afa5deSMel Gorman {
3634d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3635d031a157SAlexandru Moise 	unsigned long delta = 0;
363690afa5deSMel Gorman 
363790afa5deSMel Gorman 	/*
363895bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
363990afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
364011fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
364190afa5deSMel Gorman 	 * a better estimate
364290afa5deSMel Gorman 	 */
3643a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3644a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
364590afa5deSMel Gorman 	else
3646a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
364790afa5deSMel Gorman 
364890afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3649a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3650a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
365190afa5deSMel Gorman 
365290afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
365390afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
365490afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
365590afa5deSMel Gorman 
365690afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
365790afa5deSMel Gorman }
365890afa5deSMel Gorman 
36590ff38490SChristoph Lameter /*
3660a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
36619eeff239SChristoph Lameter  */
3662a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
36639eeff239SChristoph Lameter {
36647fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
366569e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
36669eeff239SChristoph Lameter 	struct task_struct *p = current;
36679eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3668a5f5f91dSMel Gorman 	int classzone_idx = gfp_zone(gfp_mask);
3669179e9639SAndrew Morton 	struct scan_control sc = {
367062b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
367121caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3672bd2f6199SJohannes Weiner 		.order = order,
3673a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3674a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3675a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3676ee814fe2SJohannes Weiner 		.may_swap = 1,
3677a5f5f91dSMel Gorman 		.reclaim_idx = classzone_idx,
3678179e9639SAndrew Morton 	};
36799eeff239SChristoph Lameter 
36809eeff239SChristoph Lameter 	cond_resched();
3681d4f7796eSChristoph Lameter 	/*
368295bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3683d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
368495bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3685d4f7796eSChristoph Lameter 	 */
3686d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
368776ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
36889eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
36899eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3690c84db23cSChristoph Lameter 
3691a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3692a92f7126SChristoph Lameter 		/*
36930ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
36940ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3695a92f7126SChristoph Lameter 		 */
3696a92f7126SChristoph Lameter 		do {
3697970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
36989e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
36990ff38490SChristoph Lameter 	}
3700a92f7126SChristoph Lameter 
37019eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3702d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
370376ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3704a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37059eeff239SChristoph Lameter }
3706179e9639SAndrew Morton 
3707a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3708179e9639SAndrew Morton {
3709d773ed6bSDavid Rientjes 	int ret;
3710179e9639SAndrew Morton 
3711179e9639SAndrew Morton 	/*
3712a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
37130ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
371434aa1330SChristoph Lameter 	 *
37159614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37169614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3717a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3718a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
37199614634fSChristoph Lameter 	 * unmapped file backed pages.
3720179e9639SAndrew Morton 	 */
3721a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3722a5f5f91dSMel Gorman 	    sum_zone_node_page_state(pgdat->node_id, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3723a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3724179e9639SAndrew Morton 
3725a5f5f91dSMel Gorman 	if (!pgdat_reclaimable(pgdat))
3726a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3727d773ed6bSDavid Rientjes 
3728179e9639SAndrew Morton 	/*
3729d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3730179e9639SAndrew Morton 	 */
3731d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3732a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3733179e9639SAndrew Morton 
3734179e9639SAndrew Morton 	/*
3735a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3736179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3737179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3738179e9639SAndrew Morton 	 * as wide as possible.
3739179e9639SAndrew Morton 	 */
3740a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3741a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3742d773ed6bSDavid Rientjes 
3743a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3744a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3745fa5e084eSMel Gorman 
3746a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3747a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3748d773ed6bSDavid Rientjes 
374924cf7251SMel Gorman 	if (!ret)
375024cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
375124cf7251SMel Gorman 
3752d773ed6bSDavid Rientjes 	return ret;
3753179e9639SAndrew Morton }
37549eeff239SChristoph Lameter #endif
3755894bc310SLee Schermerhorn 
3756894bc310SLee Schermerhorn /*
3757894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3758894bc310SLee Schermerhorn  * @page: the page to test
3759894bc310SLee Schermerhorn  *
3760894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
376139b5f29aSHugh Dickins  * lists vs unevictable list.
3762894bc310SLee Schermerhorn  *
3763894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3764ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3765b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3766ba9ddf49SLee Schermerhorn  *
3767894bc310SLee Schermerhorn  */
376839b5f29aSHugh Dickins int page_evictable(struct page *page)
3769894bc310SLee Schermerhorn {
377039b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3771894bc310SLee Schermerhorn }
377289e004eaSLee Schermerhorn 
377385046579SHugh Dickins #ifdef CONFIG_SHMEM
377489e004eaSLee Schermerhorn /**
377524513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
377624513264SHugh Dickins  * @pages:	array of pages to check
377724513264SHugh Dickins  * @nr_pages:	number of pages to check
377889e004eaSLee Schermerhorn  *
377924513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
378085046579SHugh Dickins  *
378185046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
378289e004eaSLee Schermerhorn  */
378324513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
378489e004eaSLee Schermerhorn {
3785925b7673SJohannes Weiner 	struct lruvec *lruvec;
3786785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
378724513264SHugh Dickins 	int pgscanned = 0;
378824513264SHugh Dickins 	int pgrescued = 0;
378989e004eaSLee Schermerhorn 	int i;
379089e004eaSLee Schermerhorn 
379124513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
379224513264SHugh Dickins 		struct page *page = pages[i];
3793785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
379489e004eaSLee Schermerhorn 
379524513264SHugh Dickins 		pgscanned++;
3796785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3797785b99feSMel Gorman 			if (pgdat)
3798785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3799785b99feSMel Gorman 			pgdat = pagepgdat;
3800785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
380189e004eaSLee Schermerhorn 		}
3802785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
380389e004eaSLee Schermerhorn 
380424513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
380524513264SHugh Dickins 			continue;
380689e004eaSLee Schermerhorn 
380739b5f29aSHugh Dickins 		if (page_evictable(page)) {
380824513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
380924513264SHugh Dickins 
3810309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
381124513264SHugh Dickins 			ClearPageUnevictable(page);
3812fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3813fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
381424513264SHugh Dickins 			pgrescued++;
381589e004eaSLee Schermerhorn 		}
381689e004eaSLee Schermerhorn 	}
381724513264SHugh Dickins 
3818785b99feSMel Gorman 	if (pgdat) {
381924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
382024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3821785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
382224513264SHugh Dickins 	}
382385046579SHugh Dickins }
382485046579SHugh Dickins #endif /* CONFIG_SHMEM */
3825