xref: /openbmc/linux/mm/vmscan.c (revision a128ca71fb29ed4444b80f38a0148b468826e19b)
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>
175b3cc15aSIngo Molnar #include <linux/sched/mm.h>
181da177e4SLinus Torvalds #include <linux/module.h>
195a0e3ad6STejun Heo #include <linux/gfp.h>
201da177e4SLinus Torvalds #include <linux/kernel_stat.h>
211da177e4SLinus Torvalds #include <linux/swap.h>
221da177e4SLinus Torvalds #include <linux/pagemap.h>
231da177e4SLinus Torvalds #include <linux/init.h>
241da177e4SLinus Torvalds #include <linux/highmem.h>
2570ddf637SAnton Vorontsov #include <linux/vmpressure.h>
26e129b5c2SAndrew Morton #include <linux/vmstat.h>
271da177e4SLinus Torvalds #include <linux/file.h>
281da177e4SLinus Torvalds #include <linux/writeback.h>
291da177e4SLinus Torvalds #include <linux/blkdev.h>
301da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
311da177e4SLinus Torvalds 					buffer_heads_over_limit */
321da177e4SLinus Torvalds #include <linux/mm_inline.h>
331da177e4SLinus Torvalds #include <linux/backing-dev.h>
341da177e4SLinus Torvalds #include <linux/rmap.h>
351da177e4SLinus Torvalds #include <linux/topology.h>
361da177e4SLinus Torvalds #include <linux/cpu.h>
371da177e4SLinus Torvalds #include <linux/cpuset.h>
383e7d3449SMel Gorman #include <linux/compaction.h>
391da177e4SLinus Torvalds #include <linux/notifier.h>
401da177e4SLinus Torvalds #include <linux/rwsem.h>
41248a0301SRafael J. Wysocki #include <linux/delay.h>
423218ae14SYasunori Goto #include <linux/kthread.h>
437dfb7103SNigel Cunningham #include <linux/freezer.h>
4466e1707bSBalbir Singh #include <linux/memcontrol.h>
45873b4771SKeika Kobayashi #include <linux/delayacct.h>
46af936a16SLee Schermerhorn #include <linux/sysctl.h>
47929bea7cSKOSAKI Motohiro #include <linux/oom.h>
48268bb0ceSLinus Torvalds #include <linux/prefetch.h>
49b1de0d13SMitchel Humpherys #include <linux/printk.h>
50f9fe48beSRoss Zwisler #include <linux/dax.h>
511da177e4SLinus Torvalds 
521da177e4SLinus Torvalds #include <asm/tlbflush.h>
531da177e4SLinus Torvalds #include <asm/div64.h>
541da177e4SLinus Torvalds 
551da177e4SLinus Torvalds #include <linux/swapops.h>
56117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
571da177e4SLinus Torvalds 
580f8053a5SNick Piggin #include "internal.h"
590f8053a5SNick Piggin 
6033906bc5SMel Gorman #define CREATE_TRACE_POINTS
6133906bc5SMel Gorman #include <trace/events/vmscan.h>
6233906bc5SMel Gorman 
631da177e4SLinus Torvalds struct scan_control {
6422fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6522fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6622fba335SKOSAKI Motohiro 
671da177e4SLinus Torvalds 	/* This context's GFP mask */
686daa0e28SAl Viro 	gfp_t gfp_mask;
691da177e4SLinus Torvalds 
70ee814fe2SJohannes Weiner 	/* Allocation order */
715ad333ebSAndy Whitcroft 	int order;
7266e1707bSBalbir Singh 
73ee814fe2SJohannes Weiner 	/*
74ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
75ee814fe2SJohannes Weiner 	 * are scanned.
76ee814fe2SJohannes Weiner 	 */
77ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
789e3b2f8cSKonstantin Khlebnikov 
795f53e762SKOSAKI Motohiro 	/*
80f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
81f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
82f16015fbSJohannes Weiner 	 */
83f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8466e1707bSBalbir Singh 
85ee814fe2SJohannes Weiner 	/* Scan (total_size >> priority) pages at once */
86ee814fe2SJohannes Weiner 	int priority;
87ee814fe2SJohannes Weiner 
88b2e18757SMel Gorman 	/* The highest zone to isolate pages for reclaim from */
89b2e18757SMel Gorman 	enum zone_type reclaim_idx;
90b2e18757SMel Gorman 
911276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
92ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
93ee814fe2SJohannes Weiner 
94ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
95ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
96ee814fe2SJohannes Weiner 
97ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
98ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
99ee814fe2SJohannes Weiner 
100241994edSJohannes Weiner 	/* Can cgroups be reclaimed below their normal consumption range? */
101241994edSJohannes Weiner 	unsigned int may_thrash:1;
102241994edSJohannes Weiner 
103ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
104ee814fe2SJohannes Weiner 
105ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
106ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
107ee814fe2SJohannes Weiner 
108ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
109ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
110ee814fe2SJohannes Weiner 
111ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
112ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1131da177e4SLinus Torvalds };
1141da177e4SLinus Torvalds 
1151da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1161da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1171da177e4SLinus Torvalds 	do {								\
1181da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1191da177e4SLinus Torvalds 			struct page *prev;				\
1201da177e4SLinus Torvalds 									\
1211da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1221da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1231da177e4SLinus Torvalds 		}							\
1241da177e4SLinus Torvalds 	} while (0)
1251da177e4SLinus Torvalds #else
1261da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1271da177e4SLinus Torvalds #endif
1281da177e4SLinus Torvalds 
1291da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1301da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1311da177e4SLinus Torvalds 	do {								\
1321da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1331da177e4SLinus Torvalds 			struct page *prev;				\
1341da177e4SLinus Torvalds 									\
1351da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1361da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1371da177e4SLinus Torvalds 		}							\
1381da177e4SLinus Torvalds 	} while (0)
1391da177e4SLinus Torvalds #else
1401da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1411da177e4SLinus Torvalds #endif
1421da177e4SLinus Torvalds 
1431da177e4SLinus Torvalds /*
1441da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1451da177e4SLinus Torvalds  */
1461da177e4SLinus Torvalds int vm_swappiness = 60;
147d0480be4SWang Sheng-Hui /*
148d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
149d0480be4SWang Sheng-Hui  * zones.
150d0480be4SWang Sheng-Hui  */
151d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1521da177e4SLinus Torvalds 
1531da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1541da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1551da177e4SLinus Torvalds 
156c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15789b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15889b5fae5SJohannes Weiner {
159f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
16089b5fae5SJohannes Weiner }
16197c9341fSTejun Heo 
16297c9341fSTejun Heo /**
16397c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
16497c9341fSTejun Heo  * @sc: scan_control in question
16597c9341fSTejun Heo  *
16697c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
16797c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
16897c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
16997c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
17097c9341fSTejun Heo  * allocation and configurability.
17197c9341fSTejun Heo  *
17297c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
17397c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
17497c9341fSTejun Heo  */
17597c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
17697c9341fSTejun Heo {
17797c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
17897c9341fSTejun Heo 
17997c9341fSTejun Heo 	if (!memcg)
18097c9341fSTejun Heo 		return true;
18197c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
18269234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
18397c9341fSTejun Heo 		return true;
18497c9341fSTejun Heo #endif
18597c9341fSTejun Heo 	return false;
18697c9341fSTejun Heo }
18791a45470SKAMEZAWA Hiroyuki #else
18889b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
18989b5fae5SJohannes Weiner {
19089b5fae5SJohannes Weiner 	return true;
19189b5fae5SJohannes Weiner }
19297c9341fSTejun Heo 
19397c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19497c9341fSTejun Heo {
19597c9341fSTejun Heo 	return true;
19697c9341fSTejun Heo }
19791a45470SKAMEZAWA Hiroyuki #endif
19891a45470SKAMEZAWA Hiroyuki 
1995a1c84b4SMel Gorman /*
2005a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2015a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2025a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2035a1c84b4SMel Gorman  */
2045a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2055a1c84b4SMel Gorman {
2065a1c84b4SMel Gorman 	unsigned long nr;
2075a1c84b4SMel Gorman 
2085a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2095a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2105a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2115a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2125a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2135a1c84b4SMel Gorman 
2145a1c84b4SMel Gorman 	return nr;
2155a1c84b4SMel Gorman }
2165a1c84b4SMel Gorman 
217599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2186e543d57SLisa Du {
219599d0c95SMel Gorman 	unsigned long nr;
220599d0c95SMel Gorman 
221599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
222599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
223599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
224599d0c95SMel Gorman 
225599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
226599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
227599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
228599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
229599d0c95SMel Gorman 
230599d0c95SMel Gorman 	return nr;
231599d0c95SMel Gorman }
232599d0c95SMel Gorman 
233fd538803SMichal Hocko /**
234fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
235fd538803SMichal Hocko  * @lruvec: lru vector
236fd538803SMichal Hocko  * @lru: lru to use
237fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
238fd538803SMichal Hocko  */
239fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
240c9f299d9SKOSAKI Motohiro {
241fd538803SMichal Hocko 	unsigned long lru_size;
242fd538803SMichal Hocko 	int zid;
243a3d8e054SKOSAKI Motohiro 
244fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
245fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
246fd538803SMichal Hocko 	else
247fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
248fd538803SMichal Hocko 
249fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
250fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
251fd538803SMichal Hocko 		unsigned long size;
252fd538803SMichal Hocko 
253fd538803SMichal Hocko 		if (!managed_zone(zone))
254fd538803SMichal Hocko 			continue;
255fd538803SMichal Hocko 
256fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
257fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
258fd538803SMichal Hocko 		else
259fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
260fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
261fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
262c9f299d9SKOSAKI Motohiro 	}
263c9f299d9SKOSAKI Motohiro 
264fd538803SMichal Hocko 	return lru_size;
265b4536f0cSMichal Hocko 
266b4536f0cSMichal Hocko }
267b4536f0cSMichal Hocko 
2681da177e4SLinus Torvalds /*
2691d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2701da177e4SLinus Torvalds  */
2711d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2721da177e4SLinus Torvalds {
2731d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2741d3d4437SGlauber Costa 
2751d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2761d3d4437SGlauber Costa 		size *= nr_node_ids;
2771d3d4437SGlauber Costa 
2781d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2791d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2801d3d4437SGlauber Costa 		return -ENOMEM;
2811d3d4437SGlauber Costa 
2821da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2831da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2841da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2851d3d4437SGlauber Costa 	return 0;
2861da177e4SLinus Torvalds }
2878e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2881da177e4SLinus Torvalds 
2891da177e4SLinus Torvalds /*
2901da177e4SLinus Torvalds  * Remove one
2911da177e4SLinus Torvalds  */
2928e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2931da177e4SLinus Torvalds {
2941da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2951da177e4SLinus Torvalds 	list_del(&shrinker->list);
2961da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
297ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2981da177e4SLinus Torvalds }
2998e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
3001da177e4SLinus Torvalds 
3011da177e4SLinus Torvalds #define SHRINK_BATCH 128
3021d3d4437SGlauber Costa 
303cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
3046b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
3056b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
3066b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
3071da177e4SLinus Torvalds {
30824f7c6b9SDave Chinner 	unsigned long freed = 0;
3091da177e4SLinus Torvalds 	unsigned long long delta;
310635697c6SKonstantin Khlebnikov 	long total_scan;
311d5bc5fd3SVladimir Davydov 	long freeable;
312acf92b48SDave Chinner 	long nr;
313acf92b48SDave Chinner 	long new_nr;
3141d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
315e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
316e9299f50SDave Chinner 					  : SHRINK_BATCH;
3175f33a080SShaohua Li 	long scanned = 0, next_deferred;
3181da177e4SLinus Torvalds 
319d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
320d5bc5fd3SVladimir Davydov 	if (freeable == 0)
3211d3d4437SGlauber Costa 		return 0;
322635697c6SKonstantin Khlebnikov 
323acf92b48SDave Chinner 	/*
324acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
325acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
326acf92b48SDave Chinner 	 * don't also do this scanning work.
327acf92b48SDave Chinner 	 */
3281d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
329acf92b48SDave Chinner 
330acf92b48SDave Chinner 	total_scan = nr;
3316b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
332d5bc5fd3SVladimir Davydov 	delta *= freeable;
3336b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
334acf92b48SDave Chinner 	total_scan += delta;
335acf92b48SDave Chinner 	if (total_scan < 0) {
3368612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
337a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
338d5bc5fd3SVladimir Davydov 		total_scan = freeable;
3395f33a080SShaohua Li 		next_deferred = nr;
3405f33a080SShaohua Li 	} else
3415f33a080SShaohua Li 		next_deferred = total_scan;
342ea164d73SAndrea Arcangeli 
343ea164d73SAndrea Arcangeli 	/*
3443567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3453567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3463567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3473567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3483567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
349d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3503567b59aSDave Chinner 	 * memory.
3513567b59aSDave Chinner 	 *
3523567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3533567b59aSDave Chinner 	 * a large delta change is calculated directly.
3543567b59aSDave Chinner 	 */
355d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
356d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3573567b59aSDave Chinner 
3583567b59aSDave Chinner 	/*
359ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
360ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
361ea164d73SAndrea Arcangeli 	 * freeable entries.
362ea164d73SAndrea Arcangeli 	 */
363d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
364d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3651da177e4SLinus Torvalds 
36624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3676b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
368d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
36909576073SDave Chinner 
3700b1fb40aSVladimir Davydov 	/*
3710b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3720b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3730b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3740b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3750b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3760b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3770b1fb40aSVladimir Davydov 	 * batch_size.
3780b1fb40aSVladimir Davydov 	 *
3790b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3800b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
381d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3820b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3830b1fb40aSVladimir Davydov 	 * possible.
3840b1fb40aSVladimir Davydov 	 */
3850b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
386d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
38724f7c6b9SDave Chinner 		unsigned long ret;
3880b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3891da177e4SLinus Torvalds 
3900b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
39124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
39224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3931da177e4SLinus Torvalds 			break;
39424f7c6b9SDave Chinner 		freed += ret;
39524f7c6b9SDave Chinner 
3960b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3970b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3985f33a080SShaohua Li 		scanned += nr_to_scan;
3991da177e4SLinus Torvalds 
4001da177e4SLinus Torvalds 		cond_resched();
4011da177e4SLinus Torvalds 	}
4021da177e4SLinus Torvalds 
4035f33a080SShaohua Li 	if (next_deferred >= scanned)
4045f33a080SShaohua Li 		next_deferred -= scanned;
4055f33a080SShaohua Li 	else
4065f33a080SShaohua Li 		next_deferred = 0;
407acf92b48SDave Chinner 	/*
408acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
409acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
410acf92b48SDave Chinner 	 * scan, there is no need to do an update.
411acf92b48SDave Chinner 	 */
4125f33a080SShaohua Li 	if (next_deferred > 0)
4135f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
4141d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
41583aeeadaSKonstantin Khlebnikov 	else
4161d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
417acf92b48SDave Chinner 
418df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
4191d3d4437SGlauber Costa 	return freed;
4201d3d4437SGlauber Costa }
4211d3d4437SGlauber Costa 
4226b4f7799SJohannes Weiner /**
423cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
4246b4f7799SJohannes Weiner  * @gfp_mask: allocation context
4256b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
426cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
4276b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
4286b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
4291d3d4437SGlauber Costa  *
4306b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4311d3d4437SGlauber Costa  *
4326b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4336b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4341d3d4437SGlauber Costa  *
435cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
436cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4370fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4380fc9f58aSVladimir Davydov  * shrinkers are called.
439cb731d6cSVladimir Davydov  *
4406b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4416b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4426b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4436b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4446b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4456b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4466b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4471d3d4437SGlauber Costa  *
4486b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4491d3d4437SGlauber Costa  */
450cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
451cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4526b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4536b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4541d3d4437SGlauber Costa {
4551d3d4437SGlauber Costa 	struct shrinker *shrinker;
4561d3d4437SGlauber Costa 	unsigned long freed = 0;
4571d3d4437SGlauber Costa 
4580fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
459cb731d6cSVladimir Davydov 		return 0;
460cb731d6cSVladimir Davydov 
4616b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4626b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4631d3d4437SGlauber Costa 
4641d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4651d3d4437SGlauber Costa 		/*
4661d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4671d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4681d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4691d3d4437SGlauber Costa 		 * time.
4701d3d4437SGlauber Costa 		 */
4711d3d4437SGlauber Costa 		freed = 1;
4721d3d4437SGlauber Costa 		goto out;
4731d3d4437SGlauber Costa 	}
4741d3d4437SGlauber Costa 
4751d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4766b4f7799SJohannes Weiner 		struct shrink_control sc = {
4776b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4786b4f7799SJohannes Weiner 			.nid = nid,
479cb731d6cSVladimir Davydov 			.memcg = memcg,
4806b4f7799SJohannes Weiner 		};
4816b4f7799SJohannes Weiner 
4820fc9f58aSVladimir Davydov 		/*
4830fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4840fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4850fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4860fc9f58aSVladimir Davydov 		 */
4870fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4880fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
489cb731d6cSVladimir Davydov 			continue;
490cb731d6cSVladimir Davydov 
4916b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4926b4f7799SJohannes Weiner 			sc.nid = 0;
4936b4f7799SJohannes Weiner 
494cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
495ec97097bSVladimir Davydov 	}
4961d3d4437SGlauber Costa 
4971da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
498f06590bdSMinchan Kim out:
499f06590bdSMinchan Kim 	cond_resched();
50024f7c6b9SDave Chinner 	return freed;
5011da177e4SLinus Torvalds }
5021da177e4SLinus Torvalds 
503cb731d6cSVladimir Davydov void drop_slab_node(int nid)
504cb731d6cSVladimir Davydov {
505cb731d6cSVladimir Davydov 	unsigned long freed;
506cb731d6cSVladimir Davydov 
507cb731d6cSVladimir Davydov 	do {
508cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
509cb731d6cSVladimir Davydov 
510cb731d6cSVladimir Davydov 		freed = 0;
511cb731d6cSVladimir Davydov 		do {
512cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
513cb731d6cSVladimir Davydov 					     1000, 1000);
514cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
515cb731d6cSVladimir Davydov 	} while (freed > 10);
516cb731d6cSVladimir Davydov }
517cb731d6cSVladimir Davydov 
518cb731d6cSVladimir Davydov void drop_slab(void)
519cb731d6cSVladimir Davydov {
520cb731d6cSVladimir Davydov 	int nid;
521cb731d6cSVladimir Davydov 
522cb731d6cSVladimir Davydov 	for_each_online_node(nid)
523cb731d6cSVladimir Davydov 		drop_slab_node(nid);
524cb731d6cSVladimir Davydov }
525cb731d6cSVladimir Davydov 
5261da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5271da177e4SLinus Torvalds {
528ceddc3a5SJohannes Weiner 	/*
529ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
530ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
531ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
532ceddc3a5SJohannes Weiner 	 */
533edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5341da177e4SLinus Torvalds }
5351da177e4SLinus Torvalds 
536703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5371da177e4SLinus Torvalds {
538930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5391da177e4SLinus Torvalds 		return 1;
540703c2708STejun Heo 	if (!inode_write_congested(inode))
5411da177e4SLinus Torvalds 		return 1;
542703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5431da177e4SLinus Torvalds 		return 1;
5441da177e4SLinus Torvalds 	return 0;
5451da177e4SLinus Torvalds }
5461da177e4SLinus Torvalds 
5471da177e4SLinus Torvalds /*
5481da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5491da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5501da177e4SLinus Torvalds  * fsync(), msync() or close().
5511da177e4SLinus Torvalds  *
5521da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5531da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5541da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5551da177e4SLinus Torvalds  *
5561da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5571da177e4SLinus Torvalds  * __GFP_FS.
5581da177e4SLinus Torvalds  */
5591da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5601da177e4SLinus Torvalds 				struct page *page, int error)
5611da177e4SLinus Torvalds {
5627eaceaccSJens Axboe 	lock_page(page);
5633e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5643e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5651da177e4SLinus Torvalds 	unlock_page(page);
5661da177e4SLinus Torvalds }
5671da177e4SLinus Torvalds 
56804e62a29SChristoph Lameter /* possible outcome of pageout() */
56904e62a29SChristoph Lameter typedef enum {
57004e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
57104e62a29SChristoph Lameter 	PAGE_KEEP,
57204e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
57304e62a29SChristoph Lameter 	PAGE_ACTIVATE,
57404e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
57504e62a29SChristoph Lameter 	PAGE_SUCCESS,
57604e62a29SChristoph Lameter 	/* page is clean and locked */
57704e62a29SChristoph Lameter 	PAGE_CLEAN,
57804e62a29SChristoph Lameter } pageout_t;
57904e62a29SChristoph Lameter 
5801da177e4SLinus Torvalds /*
5811742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5821742f19fSAndrew Morton  * Calls ->writepage().
5831da177e4SLinus Torvalds  */
584c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5857d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5861da177e4SLinus Torvalds {
5871da177e4SLinus Torvalds 	/*
5881da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5891da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5901da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5911da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5921da177e4SLinus Torvalds 	 * PagePrivate for that.
5931da177e4SLinus Torvalds 	 *
5948174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5951da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5961da177e4SLinus Torvalds 	 * will block.
5971da177e4SLinus Torvalds 	 *
5981da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5991da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
6001da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
6011da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
6021da177e4SLinus Torvalds 	 */
6031da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
6041da177e4SLinus Torvalds 		return PAGE_KEEP;
6051da177e4SLinus Torvalds 	if (!mapping) {
6061da177e4SLinus Torvalds 		/*
6071da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
6081da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
6091da177e4SLinus Torvalds 		 */
610266cf658SDavid Howells 		if (page_has_private(page)) {
6111da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
6121da177e4SLinus Torvalds 				ClearPageDirty(page);
613b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
6141da177e4SLinus Torvalds 				return PAGE_CLEAN;
6151da177e4SLinus Torvalds 			}
6161da177e4SLinus Torvalds 		}
6171da177e4SLinus Torvalds 		return PAGE_KEEP;
6181da177e4SLinus Torvalds 	}
6191da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6201da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
621703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6221da177e4SLinus Torvalds 		return PAGE_KEEP;
6231da177e4SLinus Torvalds 
6241da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6251da177e4SLinus Torvalds 		int res;
6261da177e4SLinus Torvalds 		struct writeback_control wbc = {
6271da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6281da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
629111ebb6eSOGAWA Hirofumi 			.range_start = 0,
630111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6311da177e4SLinus Torvalds 			.for_reclaim = 1,
6321da177e4SLinus Torvalds 		};
6331da177e4SLinus Torvalds 
6341da177e4SLinus Torvalds 		SetPageReclaim(page);
6351da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6361da177e4SLinus Torvalds 		if (res < 0)
6371da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
638994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6391da177e4SLinus Torvalds 			ClearPageReclaim(page);
6401da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6411da177e4SLinus Torvalds 		}
642c661b078SAndy Whitcroft 
6431da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6441da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6451da177e4SLinus Torvalds 			ClearPageReclaim(page);
6461da177e4SLinus Torvalds 		}
6473aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
648c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6491da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6501da177e4SLinus Torvalds 	}
6511da177e4SLinus Torvalds 
6521da177e4SLinus Torvalds 	return PAGE_CLEAN;
6531da177e4SLinus Torvalds }
6541da177e4SLinus Torvalds 
655a649fd92SAndrew Morton /*
656e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
657e286781dSNick Piggin  * gets returned with a refcount of 0.
658a649fd92SAndrew Morton  */
659a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
660a528910eSJohannes Weiner 			    bool reclaimed)
66149d2e9ccSChristoph Lameter {
662c4843a75SGreg Thelen 	unsigned long flags;
663c4843a75SGreg Thelen 
66428e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
66528e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
66649d2e9ccSChristoph Lameter 
667c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
66849d2e9ccSChristoph Lameter 	/*
6690fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6700fd0e6b0SNick Piggin 	 *
6710fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6720fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6730fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6740fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6750fd0e6b0SNick Piggin 	 *
6760fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6770fd0e6b0SNick Piggin 	 * [user mapping goes away]
6780fd0e6b0SNick Piggin 	 * write_to(page);
6790fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6800fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6810fd0e6b0SNick Piggin 	 * put_page(page);
6820fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6830fd0e6b0SNick Piggin 	 *
6840fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6850fd0e6b0SNick Piggin 	 *
6860fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6870fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6880139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6890fd0e6b0SNick Piggin 	 *
6900fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6910fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
69249d2e9ccSChristoph Lameter 	 */
693fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
69449d2e9ccSChristoph Lameter 		goto cannot_free;
695e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
696e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
697fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
69849d2e9ccSChristoph Lameter 		goto cannot_free;
699e286781dSNick Piggin 	}
70049d2e9ccSChristoph Lameter 
70149d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
70249d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
7030a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
70449d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
705c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7060a31bc97SJohannes Weiner 		swapcache_free(swap);
707e286781dSNick Piggin 	} else {
7086072d13cSLinus Torvalds 		void (*freepage)(struct page *);
709a528910eSJohannes Weiner 		void *shadow = NULL;
7106072d13cSLinus Torvalds 
7116072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
712a528910eSJohannes Weiner 		/*
713a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
714a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
715a528910eSJohannes Weiner 		 *
716a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
717a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
718a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
719a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
720a528910eSJohannes Weiner 		 * back.
721f9fe48beSRoss Zwisler 		 *
722f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
723f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
724f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
725f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
726f9fe48beSRoss Zwisler 		 * same page_tree.
727a528910eSJohannes Weiner 		 */
728a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
729f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
730a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
73162cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
732c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7336072d13cSLinus Torvalds 
7346072d13cSLinus Torvalds 		if (freepage != NULL)
7356072d13cSLinus Torvalds 			freepage(page);
736e286781dSNick Piggin 	}
737e286781dSNick Piggin 
73849d2e9ccSChristoph Lameter 	return 1;
73949d2e9ccSChristoph Lameter 
74049d2e9ccSChristoph Lameter cannot_free:
741c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
74249d2e9ccSChristoph Lameter 	return 0;
74349d2e9ccSChristoph Lameter }
74449d2e9ccSChristoph Lameter 
7451da177e4SLinus Torvalds /*
746e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
747e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
748e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
749e286781dSNick Piggin  * this page.
750e286781dSNick Piggin  */
751e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
752e286781dSNick Piggin {
753a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
754e286781dSNick Piggin 		/*
755e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
756e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
757e286781dSNick Piggin 		 * atomic operation.
758e286781dSNick Piggin 		 */
759fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
760e286781dSNick Piggin 		return 1;
761e286781dSNick Piggin 	}
762e286781dSNick Piggin 	return 0;
763e286781dSNick Piggin }
764e286781dSNick Piggin 
765894bc310SLee Schermerhorn /**
766894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
767894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
768894bc310SLee Schermerhorn  *
769894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
770894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
771894bc310SLee Schermerhorn  *
772894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
773894bc310SLee Schermerhorn  */
774894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
775894bc310SLee Schermerhorn {
7760ec3b74cSVlastimil Babka 	bool is_unevictable;
777bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
778894bc310SLee Schermerhorn 
779309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
780894bc310SLee Schermerhorn 
781894bc310SLee Schermerhorn redo:
782894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
783894bc310SLee Schermerhorn 
78439b5f29aSHugh Dickins 	if (page_evictable(page)) {
785894bc310SLee Schermerhorn 		/*
786894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
787894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
788894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
789894bc310SLee Schermerhorn 		 * We know how to handle that.
790894bc310SLee Schermerhorn 		 */
7910ec3b74cSVlastimil Babka 		is_unevictable = false;
792c53954a0SMel Gorman 		lru_cache_add(page);
793894bc310SLee Schermerhorn 	} else {
794894bc310SLee Schermerhorn 		/*
795894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
796894bc310SLee Schermerhorn 		 * list.
797894bc310SLee Schermerhorn 		 */
7980ec3b74cSVlastimil Babka 		is_unevictable = true;
799894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
8006a7b9548SJohannes Weiner 		/*
80121ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
80221ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
80321ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
80424513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
80521ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
8066a7b9548SJohannes Weiner 		 * the page back to the evictable list.
8076a7b9548SJohannes Weiner 		 *
80821ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
8096a7b9548SJohannes Weiner 		 */
8106a7b9548SJohannes Weiner 		smp_mb();
811894bc310SLee Schermerhorn 	}
812894bc310SLee Schermerhorn 
813894bc310SLee Schermerhorn 	/*
814894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
815894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
816894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
817894bc310SLee Schermerhorn 	 */
8180ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
819894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
820894bc310SLee Schermerhorn 			put_page(page);
821894bc310SLee Schermerhorn 			goto redo;
822894bc310SLee Schermerhorn 		}
823894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
824894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
825894bc310SLee Schermerhorn 		 * nothing to do here.
826894bc310SLee Schermerhorn 		 */
827894bc310SLee Schermerhorn 	}
828894bc310SLee Schermerhorn 
8290ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
830bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8310ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
832bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
833bbfd28eeSLee Schermerhorn 
834894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
835894bc310SLee Schermerhorn }
836894bc310SLee Schermerhorn 
837dfc8d636SJohannes Weiner enum page_references {
838dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
839dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
84064574746SJohannes Weiner 	PAGEREF_KEEP,
841dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
842dfc8d636SJohannes Weiner };
843dfc8d636SJohannes Weiner 
844dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
845dfc8d636SJohannes Weiner 						  struct scan_control *sc)
846dfc8d636SJohannes Weiner {
84764574746SJohannes Weiner 	int referenced_ptes, referenced_page;
848dfc8d636SJohannes Weiner 	unsigned long vm_flags;
849dfc8d636SJohannes Weiner 
850c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
851c3ac9a8aSJohannes Weiner 					  &vm_flags);
85264574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
853dfc8d636SJohannes Weiner 
854dfc8d636SJohannes Weiner 	/*
855dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
856dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
857dfc8d636SJohannes Weiner 	 */
858dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
859dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
860dfc8d636SJohannes Weiner 
86164574746SJohannes Weiner 	if (referenced_ptes) {
862e4898273SMichal Hocko 		if (PageSwapBacked(page))
86364574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
86464574746SJohannes Weiner 		/*
86564574746SJohannes Weiner 		 * All mapped pages start out with page table
86664574746SJohannes Weiner 		 * references from the instantiating fault, so we need
86764574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
86864574746SJohannes Weiner 		 * than once.
86964574746SJohannes Weiner 		 *
87064574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
87164574746SJohannes Weiner 		 * inactive list.  Another page table reference will
87264574746SJohannes Weiner 		 * lead to its activation.
87364574746SJohannes Weiner 		 *
87464574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
87564574746SJohannes Weiner 		 * so that recently deactivated but used pages are
87664574746SJohannes Weiner 		 * quickly recovered.
87764574746SJohannes Weiner 		 */
87864574746SJohannes Weiner 		SetPageReferenced(page);
87964574746SJohannes Weiner 
88034dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
881dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
882dfc8d636SJohannes Weiner 
883c909e993SKonstantin Khlebnikov 		/*
884c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
885c909e993SKonstantin Khlebnikov 		 */
886c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
887c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
888c909e993SKonstantin Khlebnikov 
88964574746SJohannes Weiner 		return PAGEREF_KEEP;
89064574746SJohannes Weiner 	}
89164574746SJohannes Weiner 
892dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8932e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
894dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
89564574746SJohannes Weiner 
89664574746SJohannes Weiner 	return PAGEREF_RECLAIM;
897dfc8d636SJohannes Weiner }
898dfc8d636SJohannes Weiner 
899e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
900e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
901e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
902e2be15f6SMel Gorman {
903b4597226SMel Gorman 	struct address_space *mapping;
904b4597226SMel Gorman 
905e2be15f6SMel Gorman 	/*
906e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
907e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
908e2be15f6SMel Gorman 	 */
909e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
910e2be15f6SMel Gorman 		*dirty = false;
911e2be15f6SMel Gorman 		*writeback = false;
912e2be15f6SMel Gorman 		return;
913e2be15f6SMel Gorman 	}
914e2be15f6SMel Gorman 
915e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
916e2be15f6SMel Gorman 	*dirty = PageDirty(page);
917e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
918b4597226SMel Gorman 
919b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
920b4597226SMel Gorman 	if (!page_has_private(page))
921b4597226SMel Gorman 		return;
922b4597226SMel Gorman 
923b4597226SMel Gorman 	mapping = page_mapping(page);
924b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
925b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
926e2be15f6SMel Gorman }
927e2be15f6SMel Gorman 
9283c710c1aSMichal Hocko struct reclaim_stat {
9293c710c1aSMichal Hocko 	unsigned nr_dirty;
9303c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty;
9313c710c1aSMichal Hocko 	unsigned nr_congested;
9323c710c1aSMichal Hocko 	unsigned nr_writeback;
9333c710c1aSMichal Hocko 	unsigned nr_immediate;
9345bccd166SMichal Hocko 	unsigned nr_activate;
9355bccd166SMichal Hocko 	unsigned nr_ref_keep;
9365bccd166SMichal Hocko 	unsigned nr_unmap_fail;
9373c710c1aSMichal Hocko };
9383c710c1aSMichal Hocko 
939e286781dSNick Piggin /*
9401742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
9411da177e4SLinus Torvalds  */
9421742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
943599d0c95SMel Gorman 				      struct pglist_data *pgdat,
944f84f6e2bSMel Gorman 				      struct scan_control *sc,
94502c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9463c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
94702c6de8dSMinchan Kim 				      bool force_reclaim)
9481da177e4SLinus Torvalds {
9491da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
950abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9511da177e4SLinus Torvalds 	int pgactivate = 0;
9523c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
9533c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
9543c710c1aSMichal Hocko 	unsigned nr_congested = 0;
9553c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
9563c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
9573c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
9585bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
9595bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
9601da177e4SLinus Torvalds 
9611da177e4SLinus Torvalds 	cond_resched();
9621da177e4SLinus Torvalds 
9631da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9641da177e4SLinus Torvalds 		struct address_space *mapping;
9651da177e4SLinus Torvalds 		struct page *page;
9661da177e4SLinus Torvalds 		int may_enter_fs;
96702c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
968e2be15f6SMel Gorman 		bool dirty, writeback;
969854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9701da177e4SLinus Torvalds 
9711da177e4SLinus Torvalds 		cond_resched();
9721da177e4SLinus Torvalds 
9731da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9741da177e4SLinus Torvalds 		list_del(&page->lru);
9751da177e4SLinus Torvalds 
976529ae9aaSNick Piggin 		if (!trylock_page(page))
9771da177e4SLinus Torvalds 			goto keep;
9781da177e4SLinus Torvalds 
979309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9801da177e4SLinus Torvalds 
9811da177e4SLinus Torvalds 		sc->nr_scanned++;
98280e43426SChristoph Lameter 
98339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
984b291f000SNick Piggin 			goto cull_mlocked;
985894bc310SLee Schermerhorn 
986a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
98780e43426SChristoph Lameter 			goto keep_locked;
98880e43426SChristoph Lameter 
9891da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9901da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9911da177e4SLinus Torvalds 			sc->nr_scanned++;
9921da177e4SLinus Torvalds 
993c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
994c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
995c661b078SAndy Whitcroft 
996e62e384eSMichal Hocko 		/*
997e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
998e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
999e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1000e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1001e2be15f6SMel Gorman 		 */
1002e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1003e2be15f6SMel Gorman 		if (dirty || writeback)
1004e2be15f6SMel Gorman 			nr_dirty++;
1005e2be15f6SMel Gorman 
1006e2be15f6SMel Gorman 		if (dirty && !writeback)
1007e2be15f6SMel Gorman 			nr_unqueued_dirty++;
1008e2be15f6SMel Gorman 
1009d04e8acdSMel Gorman 		/*
1010d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1011d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1012d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1013d04e8acdSMel Gorman 		 * end of the LRU a second time.
1014d04e8acdSMel Gorman 		 */
1015e2be15f6SMel Gorman 		mapping = page_mapping(page);
10161da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1017703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1018d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1019e2be15f6SMel Gorman 			nr_congested++;
1020e2be15f6SMel Gorman 
1021e2be15f6SMel Gorman 		/*
1022283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1023283aba9fSMel Gorman 		 * are three cases to consider.
1024e62e384eSMichal Hocko 		 *
1025283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1026283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1027283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1028283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1029283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1030283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1031283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1032b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1033b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1034c3b94f44SHugh Dickins 		 *
103597c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1036ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1037ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1038ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
103997c9341fSTejun Heo 		 *    reclaim and continue scanning.
1040283aba9fSMel Gorman 		 *
1041ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1042ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1043283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1044283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1045283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1046283aba9fSMel Gorman 		 *    would probably show more reasons.
1047283aba9fSMel Gorman 		 *
10487fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1049283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1050283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1051283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1052283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1053c55e8d03SJohannes Weiner 		 *
1054c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1055c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1056c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1057c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1058c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1059c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1060c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1061c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1062e62e384eSMichal Hocko 		 */
1063283aba9fSMel Gorman 		if (PageWriteback(page)) {
1064283aba9fSMel Gorman 			/* Case 1 above */
1065283aba9fSMel Gorman 			if (current_is_kswapd() &&
1066283aba9fSMel Gorman 			    PageReclaim(page) &&
1067599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1068b1a6f21eSMel Gorman 				nr_immediate++;
1069c55e8d03SJohannes Weiner 				goto activate_locked;
1070283aba9fSMel Gorman 
1071283aba9fSMel Gorman 			/* Case 2 above */
107297c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1073ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1074c3b94f44SHugh Dickins 				/*
1075c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1076c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1077c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1078c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1079c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1080c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1081c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1082c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1083c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1084c3b94f44SHugh Dickins 				 */
1085c3b94f44SHugh Dickins 				SetPageReclaim(page);
108692df3a72SMel Gorman 				nr_writeback++;
1087c55e8d03SJohannes Weiner 				goto activate_locked;
1088283aba9fSMel Gorman 
1089283aba9fSMel Gorman 			/* Case 3 above */
1090283aba9fSMel Gorman 			} else {
10917fadc820SHugh Dickins 				unlock_page(page);
1092c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10937fadc820SHugh Dickins 				/* then go back and try same page again */
10947fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10957fadc820SHugh Dickins 				continue;
1096e62e384eSMichal Hocko 			}
1097283aba9fSMel Gorman 		}
10981da177e4SLinus Torvalds 
109902c6de8dSMinchan Kim 		if (!force_reclaim)
11006a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
110102c6de8dSMinchan Kim 
1102dfc8d636SJohannes Weiner 		switch (references) {
1103dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
11041da177e4SLinus Torvalds 			goto activate_locked;
110564574746SJohannes Weiner 		case PAGEREF_KEEP:
11065bccd166SMichal Hocko 			nr_ref_keep++;
110764574746SJohannes Weiner 			goto keep_locked;
1108dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1109dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1110dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1111dfc8d636SJohannes Weiner 		}
11121da177e4SLinus Torvalds 
11131da177e4SLinus Torvalds 		/*
11141da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
11151da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
11161da177e4SLinus Torvalds 		 */
1117b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
111863eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
111963eb6b93SHugh Dickins 				goto keep_locked;
11205bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
11211da177e4SLinus Torvalds 				goto activate_locked;
112263eb6b93SHugh Dickins 			may_enter_fs = 1;
11231da177e4SLinus Torvalds 
1124e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
11251da177e4SLinus Torvalds 			mapping = page_mapping(page);
11267751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
11277751b2daSKirill A. Shutemov 			/* Split file THP */
11287751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
11297751b2daSKirill A. Shutemov 				goto keep_locked;
1130e2be15f6SMel Gorman 		}
11311da177e4SLinus Torvalds 
11327751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
11337751b2daSKirill A. Shutemov 
11341da177e4SLinus Torvalds 		/*
11351da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
11361da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
11371da177e4SLinus Torvalds 		 */
11381da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1139*a128ca71SShaohua Li 			switch (ret = try_to_unmap(page,
1140*a128ca71SShaohua Li 				ttu_flags | TTU_BATCH_FLUSH)) {
11411da177e4SLinus Torvalds 			case SWAP_FAIL:
11425bccd166SMichal Hocko 				nr_unmap_fail++;
11431da177e4SLinus Torvalds 				goto activate_locked;
11441da177e4SLinus Torvalds 			case SWAP_AGAIN:
11451da177e4SLinus Torvalds 				goto keep_locked;
1146b291f000SNick Piggin 			case SWAP_MLOCK:
1147b291f000SNick Piggin 				goto cull_mlocked;
1148854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1149854e9ed0SMinchan Kim 				goto lazyfree;
11501da177e4SLinus Torvalds 			case SWAP_SUCCESS:
11511da177e4SLinus Torvalds 				; /* try to free the page below */
11521da177e4SLinus Torvalds 			}
11531da177e4SLinus Torvalds 		}
11541da177e4SLinus Torvalds 
11551da177e4SLinus Torvalds 		if (PageDirty(page)) {
1156ee72886dSMel Gorman 			/*
11574eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
11584eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
11594eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
11604eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
11614eda4823SJohannes Weiner 			 * write pages when we've encountered many
11624eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
11634eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
11644eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1165ee72886dSMel Gorman 			 */
1166f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11674eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1168599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
116949ea7eb6SMel Gorman 				/*
117049ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
117149ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
117249ea7eb6SMel Gorman 				 * except we already have the page isolated
117349ea7eb6SMel Gorman 				 * and know it's dirty
117449ea7eb6SMel Gorman 				 */
1175c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
117649ea7eb6SMel Gorman 				SetPageReclaim(page);
117749ea7eb6SMel Gorman 
1178c55e8d03SJohannes Weiner 				goto activate_locked;
1179ee72886dSMel Gorman 			}
1180ee72886dSMel Gorman 
1181dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11821da177e4SLinus Torvalds 				goto keep_locked;
11834dd4b920SAndrew Morton 			if (!may_enter_fs)
11841da177e4SLinus Torvalds 				goto keep_locked;
118552a8363eSChristoph Lameter 			if (!sc->may_writepage)
11861da177e4SLinus Torvalds 				goto keep_locked;
11871da177e4SLinus Torvalds 
1188d950c947SMel Gorman 			/*
1189d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1190d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1191d950c947SMel Gorman 			 * starts and then write it out here.
1192d950c947SMel Gorman 			 */
1193d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11947d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11951da177e4SLinus Torvalds 			case PAGE_KEEP:
11961da177e4SLinus Torvalds 				goto keep_locked;
11971da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11981da177e4SLinus Torvalds 				goto activate_locked;
11991da177e4SLinus Torvalds 			case PAGE_SUCCESS:
12007d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
120141ac1999SMel Gorman 					goto keep;
12027d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
12031da177e4SLinus Torvalds 					goto keep;
12047d3579e8SKOSAKI Motohiro 
12051da177e4SLinus Torvalds 				/*
12061da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
12071da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
12081da177e4SLinus Torvalds 				 */
1209529ae9aaSNick Piggin 				if (!trylock_page(page))
12101da177e4SLinus Torvalds 					goto keep;
12111da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
12121da177e4SLinus Torvalds 					goto keep_locked;
12131da177e4SLinus Torvalds 				mapping = page_mapping(page);
12141da177e4SLinus Torvalds 			case PAGE_CLEAN:
12151da177e4SLinus Torvalds 				; /* try to free the page below */
12161da177e4SLinus Torvalds 			}
12171da177e4SLinus Torvalds 		}
12181da177e4SLinus Torvalds 
12191da177e4SLinus Torvalds 		/*
12201da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
12211da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
12221da177e4SLinus Torvalds 		 * the page as well.
12231da177e4SLinus Torvalds 		 *
12241da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
12251da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
12261da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
12271da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
12281da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
12291da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
12301da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
12311da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
12321da177e4SLinus Torvalds 		 *
12331da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
12341da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
12351da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
12361da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
12371da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
12381da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
12391da177e4SLinus Torvalds 		 */
1240266cf658SDavid Howells 		if (page_has_private(page)) {
12411da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
12421da177e4SLinus Torvalds 				goto activate_locked;
1243e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1244e286781dSNick Piggin 				unlock_page(page);
1245e286781dSNick Piggin 				if (put_page_testzero(page))
12461da177e4SLinus Torvalds 					goto free_it;
1247e286781dSNick Piggin 				else {
1248e286781dSNick Piggin 					/*
1249e286781dSNick Piggin 					 * rare race with speculative reference.
1250e286781dSNick Piggin 					 * the speculative reference will free
1251e286781dSNick Piggin 					 * this page shortly, so we may
1252e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1253e286781dSNick Piggin 					 * leave it off the LRU).
1254e286781dSNick Piggin 					 */
1255e286781dSNick Piggin 					nr_reclaimed++;
1256e286781dSNick Piggin 					continue;
1257e286781dSNick Piggin 				}
1258e286781dSNick Piggin 			}
12591da177e4SLinus Torvalds 		}
12601da177e4SLinus Torvalds 
1261854e9ed0SMinchan Kim lazyfree:
1262a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
126349d2e9ccSChristoph Lameter 			goto keep_locked;
12641da177e4SLinus Torvalds 
1265a978d6f5SNick Piggin 		/*
1266a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1267a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1268a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1269a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1270a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1271a978d6f5SNick Piggin 		 */
127248c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1273e286781dSNick Piggin free_it:
1274854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1275854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1276854e9ed0SMinchan Kim 
127705ff5137SAndrew Morton 		nr_reclaimed++;
1278abe4c3b5SMel Gorman 
1279abe4c3b5SMel Gorman 		/*
1280abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1281abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1282abe4c3b5SMel Gorman 		 */
1283abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12841da177e4SLinus Torvalds 		continue;
12851da177e4SLinus Torvalds 
1286b291f000SNick Piggin cull_mlocked:
128763d6c5adSHugh Dickins 		if (PageSwapCache(page))
128863d6c5adSHugh Dickins 			try_to_free_swap(page);
1289b291f000SNick Piggin 		unlock_page(page);
1290c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1291b291f000SNick Piggin 		continue;
1292b291f000SNick Piggin 
12931da177e4SLinus Torvalds activate_locked:
129468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12955ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1296a2c43eedSHugh Dickins 			try_to_free_swap(page);
1297309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12981da177e4SLinus Torvalds 		SetPageActive(page);
12991da177e4SLinus Torvalds 		pgactivate++;
13001da177e4SLinus Torvalds keep_locked:
13011da177e4SLinus Torvalds 		unlock_page(page);
13021da177e4SLinus Torvalds keep:
13031da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1304309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
13051da177e4SLinus Torvalds 	}
1306abe4c3b5SMel Gorman 
1307747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
130872b252aeSMel Gorman 	try_to_unmap_flush();
1309b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1310abe4c3b5SMel Gorman 
13111da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1312f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
13130a31bc97SJohannes Weiner 
13143c710c1aSMichal Hocko 	if (stat) {
13153c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
13163c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
13173c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
13183c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
13193c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
13205bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
13215bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
13225bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
13233c710c1aSMichal Hocko 	}
132405ff5137SAndrew Morton 	return nr_reclaimed;
13251da177e4SLinus Torvalds }
13261da177e4SLinus Torvalds 
132702c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
132802c6de8dSMinchan Kim 					    struct list_head *page_list)
132902c6de8dSMinchan Kim {
133002c6de8dSMinchan Kim 	struct scan_control sc = {
133102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
133202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
133302c6de8dSMinchan Kim 		.may_unmap = 1,
133402c6de8dSMinchan Kim 	};
13353c710c1aSMichal Hocko 	unsigned long ret;
133602c6de8dSMinchan Kim 	struct page *page, *next;
133702c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
133802c6de8dSMinchan Kim 
133902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1340117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1341b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
134202c6de8dSMinchan Kim 			ClearPageActive(page);
134302c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
134402c6de8dSMinchan Kim 		}
134502c6de8dSMinchan Kim 	}
134602c6de8dSMinchan Kim 
1347599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1348*a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
134902c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1350599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
135102c6de8dSMinchan Kim 	return ret;
135202c6de8dSMinchan Kim }
135302c6de8dSMinchan Kim 
13545ad333ebSAndy Whitcroft /*
13555ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13565ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13575ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13585ad333ebSAndy Whitcroft  *
13595ad333ebSAndy Whitcroft  * page:	page to consider
13605ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13615ad333ebSAndy Whitcroft  *
13625ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13635ad333ebSAndy Whitcroft  */
1364f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13655ad333ebSAndy Whitcroft {
13665ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13675ad333ebSAndy Whitcroft 
13685ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13695ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13705ad333ebSAndy Whitcroft 		return ret;
13715ad333ebSAndy Whitcroft 
1372e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1373e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1374894bc310SLee Schermerhorn 		return ret;
1375894bc310SLee Schermerhorn 
13765ad333ebSAndy Whitcroft 	ret = -EBUSY;
137708e552c6SKAMEZAWA Hiroyuki 
1378c8244935SMel Gorman 	/*
1379c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1380c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1381c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1382c8244935SMel Gorman 	 *
1383c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1384c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1385c8244935SMel Gorman 	 */
13861276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1387c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1388c8244935SMel Gorman 		if (PageWriteback(page))
138939deaf85SMinchan Kim 			return ret;
139039deaf85SMinchan Kim 
1391c8244935SMel Gorman 		if (PageDirty(page)) {
1392c8244935SMel Gorman 			struct address_space *mapping;
1393c8244935SMel Gorman 
1394c8244935SMel Gorman 			/*
1395c8244935SMel Gorman 			 * Only pages without mappings or that have a
1396c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1397c8244935SMel Gorman 			 * without blocking
1398c8244935SMel Gorman 			 */
1399c8244935SMel Gorman 			mapping = page_mapping(page);
1400c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1401c8244935SMel Gorman 				return ret;
1402c8244935SMel Gorman 		}
1403c8244935SMel Gorman 	}
1404c8244935SMel Gorman 
1405f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1406f80c0673SMinchan Kim 		return ret;
1407f80c0673SMinchan Kim 
14085ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
14095ad333ebSAndy Whitcroft 		/*
14105ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
14115ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
14125ad333ebSAndy Whitcroft 		 * page release code relies on it.
14135ad333ebSAndy Whitcroft 		 */
14145ad333ebSAndy Whitcroft 		ClearPageLRU(page);
14155ad333ebSAndy Whitcroft 		ret = 0;
14165ad333ebSAndy Whitcroft 	}
14175ad333ebSAndy Whitcroft 
14185ad333ebSAndy Whitcroft 	return ret;
14195ad333ebSAndy Whitcroft }
14205ad333ebSAndy Whitcroft 
14217ee36a14SMel Gorman 
14227ee36a14SMel Gorman /*
14237ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
14247ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
14257ee36a14SMel Gorman  */
14267ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1427b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
14287ee36a14SMel Gorman {
14297ee36a14SMel Gorman 	int zid;
14307ee36a14SMel Gorman 
14317ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14327ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14337ee36a14SMel Gorman 			continue;
14347ee36a14SMel Gorman 
14357ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1436b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1437b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1438b4536f0cSMichal Hocko #endif
14397ee36a14SMel Gorman 	}
14407ee36a14SMel Gorman 
14417ee36a14SMel Gorman }
14427ee36a14SMel Gorman 
144349d2e9ccSChristoph Lameter /*
1444a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14451da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14461da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14471da177e4SLinus Torvalds  *
14481da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14491da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14501da177e4SLinus Torvalds  *
14511da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14521da177e4SLinus Torvalds  *
14531da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
14545dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14551da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1456f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1457fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14585ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14593cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14601da177e4SLinus Torvalds  *
14611da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14621da177e4SLinus Torvalds  */
146369e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14645dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1465fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14663cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14671da177e4SLinus Torvalds {
146875b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
146969e05944SAndrew Morton 	unsigned long nr_taken = 0;
1470599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14717cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
14723db65812SJohannes Weiner 	unsigned long skipped = 0;
1473599d0c95SMel Gorman 	unsigned long scan, nr_pages;
1474b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14751da177e4SLinus Torvalds 
14760b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
14773db65812SJohannes Weiner 					!list_empty(src); scan++) {
14785ad333ebSAndy Whitcroft 		struct page *page;
14795ad333ebSAndy Whitcroft 
14801da177e4SLinus Torvalds 		page = lru_to_page(src);
14811da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14821da177e4SLinus Torvalds 
1483309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14848d438f96SNick Piggin 
1485b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1486b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
14877cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1488b2e18757SMel Gorman 			continue;
1489b2e18757SMel Gorman 		}
1490b2e18757SMel Gorman 
1491f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14925ad333ebSAndy Whitcroft 		case 0:
1493599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1494599d0c95SMel Gorman 			nr_taken += nr_pages;
1495599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14965ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14975ad333ebSAndy Whitcroft 			break;
14987c8ee9a8SNick Piggin 
14995ad333ebSAndy Whitcroft 		case -EBUSY:
15005ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
15015ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
15025ad333ebSAndy Whitcroft 			continue;
15035ad333ebSAndy Whitcroft 
15045ad333ebSAndy Whitcroft 		default:
15055ad333ebSAndy Whitcroft 			BUG();
15065ad333ebSAndy Whitcroft 		}
15075ad333ebSAndy Whitcroft 	}
15081da177e4SLinus Torvalds 
1509b2e18757SMel Gorman 	/*
1510b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1511b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1512b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1513b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1514b2e18757SMel Gorman 	 * system at risk of premature OOM.
1515b2e18757SMel Gorman 	 */
15167cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
15177cc30fcfSMel Gorman 		int zid;
15187cc30fcfSMel Gorman 
15193db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
15207cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15217cc30fcfSMel Gorman 			if (!nr_skipped[zid])
15227cc30fcfSMel Gorman 				continue;
15237cc30fcfSMel Gorman 
15247cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
15251265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
15267cc30fcfSMel Gorman 		}
15277cc30fcfSMel Gorman 	}
15283db65812SJohannes Weiner 	*nr_scanned = scan;
15291265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
153032b3f297SMichal Hocko 				    scan, skipped, nr_taken, mode, lru);
1531b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15321da177e4SLinus Torvalds 	return nr_taken;
15331da177e4SLinus Torvalds }
15341da177e4SLinus Torvalds 
153562695a84SNick Piggin /**
153662695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
153762695a84SNick Piggin  * @page: page to isolate from its LRU list
153862695a84SNick Piggin  *
153962695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
154062695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
154162695a84SNick Piggin  *
154262695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
154362695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
154462695a84SNick Piggin  *
154562695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1546894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1547894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1548894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
154962695a84SNick Piggin  *
155062695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
155162695a84SNick Piggin  * found will be decremented.
155262695a84SNick Piggin  *
155362695a84SNick Piggin  * Restrictions:
155462695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
155562695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
155662695a84SNick Piggin  *     without a stable reference).
155762695a84SNick Piggin  * (2) the lru_lock must not be held.
155862695a84SNick Piggin  * (3) interrupts must be enabled.
155962695a84SNick Piggin  */
156062695a84SNick Piggin int isolate_lru_page(struct page *page)
156162695a84SNick Piggin {
156262695a84SNick Piggin 	int ret = -EBUSY;
156362695a84SNick Piggin 
1564309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1565cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15660c917313SKonstantin Khlebnikov 
156762695a84SNick Piggin 	if (PageLRU(page)) {
156862695a84SNick Piggin 		struct zone *zone = page_zone(page);
1569fa9add64SHugh Dickins 		struct lruvec *lruvec;
157062695a84SNick Piggin 
1571a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1572599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
15730c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1574894bc310SLee Schermerhorn 			int lru = page_lru(page);
15750c917313SKonstantin Khlebnikov 			get_page(page);
157662695a84SNick Piggin 			ClearPageLRU(page);
1577fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1578fa9add64SHugh Dickins 			ret = 0;
157962695a84SNick Piggin 		}
1580a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
158162695a84SNick Piggin 	}
158262695a84SNick Piggin 	return ret;
158362695a84SNick Piggin }
158462695a84SNick Piggin 
15855ad333ebSAndy Whitcroft /*
1586d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1587d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1588d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1589d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1590d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
159135cd7815SRik van Riel  */
1592599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
159335cd7815SRik van Riel 		struct scan_control *sc)
159435cd7815SRik van Riel {
159535cd7815SRik van Riel 	unsigned long inactive, isolated;
159635cd7815SRik van Riel 
159735cd7815SRik van Riel 	if (current_is_kswapd())
159835cd7815SRik van Riel 		return 0;
159935cd7815SRik van Riel 
160097c9341fSTejun Heo 	if (!sane_reclaim(sc))
160135cd7815SRik van Riel 		return 0;
160235cd7815SRik van Riel 
160335cd7815SRik van Riel 	if (file) {
1604599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1605599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
160635cd7815SRik van Riel 	} else {
1607599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1608599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
160935cd7815SRik van Riel 	}
161035cd7815SRik van Riel 
16113cf23841SFengguang Wu 	/*
16123cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
16133cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
16143cf23841SFengguang Wu 	 * deadlock.
16153cf23841SFengguang Wu 	 */
1616d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
16173cf23841SFengguang Wu 		inactive >>= 3;
16183cf23841SFengguang Wu 
161935cd7815SRik van Riel 	return isolated > inactive;
162035cd7815SRik van Riel }
162135cd7815SRik van Riel 
162266635629SMel Gorman static noinline_for_stack void
162375b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
162466635629SMel Gorman {
162527ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1626599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16273f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
162866635629SMel Gorman 
162966635629SMel Gorman 	/*
163066635629SMel Gorman 	 * Put back any unfreeable pages.
163166635629SMel Gorman 	 */
163266635629SMel Gorman 	while (!list_empty(page_list)) {
16333f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
163466635629SMel Gorman 		int lru;
16353f79768fSHugh Dickins 
1636309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
163766635629SMel Gorman 		list_del(&page->lru);
163839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1639599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
164066635629SMel Gorman 			putback_lru_page(page);
1641599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
164266635629SMel Gorman 			continue;
164366635629SMel Gorman 		}
1644fa9add64SHugh Dickins 
1645599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1646fa9add64SHugh Dickins 
16477a608572SLinus Torvalds 		SetPageLRU(page);
164866635629SMel Gorman 		lru = page_lru(page);
1649fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1650fa9add64SHugh Dickins 
165166635629SMel Gorman 		if (is_active_lru(lru)) {
165266635629SMel Gorman 			int file = is_file_lru(lru);
16539992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16549992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
165566635629SMel Gorman 		}
16562bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16572bcf8879SHugh Dickins 			__ClearPageLRU(page);
16582bcf8879SHugh Dickins 			__ClearPageActive(page);
1659fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16602bcf8879SHugh Dickins 
16612bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1662599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1663747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16642bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1665599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16662bcf8879SHugh Dickins 			} else
16672bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
166866635629SMel Gorman 		}
166966635629SMel Gorman 	}
167066635629SMel Gorman 
16713f79768fSHugh Dickins 	/*
16723f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
16733f79768fSHugh Dickins 	 */
16743f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
167566635629SMel Gorman }
167666635629SMel Gorman 
167766635629SMel Gorman /*
1678399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1679399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1680399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1681399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1682399ba0b9SNeilBrown  */
1683399ba0b9SNeilBrown static int current_may_throttle(void)
1684399ba0b9SNeilBrown {
1685399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1686399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1687399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1688399ba0b9SNeilBrown }
1689399ba0b9SNeilBrown 
1690399ba0b9SNeilBrown /*
1691b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16921742f19fSAndrew Morton  * of reclaimed pages
16931da177e4SLinus Torvalds  */
169466635629SMel Gorman static noinline_for_stack unsigned long
16951a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
16969e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
16971da177e4SLinus Torvalds {
16981da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1699e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
170005ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1701e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
17023c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1703f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17043cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1705599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17061a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
170778dc583dSKOSAKI Motohiro 
1708599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
170958355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
171035cd7815SRik van Riel 
171135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
171235cd7815SRik van Riel 		if (fatal_signal_pending(current))
171335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
171435cd7815SRik van Riel 	}
171535cd7815SRik van Riel 
17161da177e4SLinus Torvalds 	lru_add_drain();
1717f80c0673SMinchan Kim 
1718f80c0673SMinchan Kim 	if (!sc->may_unmap)
171961317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1720f80c0673SMinchan Kim 
1721599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17221da177e4SLinus Torvalds 
17235dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17245dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
172595d918fcSKonstantin Khlebnikov 
1726599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17279d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
172895d918fcSKonstantin Khlebnikov 
172989b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1730b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1731599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
1732b35ea17bSKOSAKI Motohiro 		else
1733599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
1734b35ea17bSKOSAKI Motohiro 	}
1735599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1736d563c050SHillf Danton 
1737d563c050SHillf Danton 	if (nr_taken == 0)
173866635629SMel Gorman 		return 0;
1739b35ea17bSKOSAKI Motohiro 
1740*a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
17413c710c1aSMichal Hocko 				&stat, false);
1742c661b078SAndy Whitcroft 
1743599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17443f79768fSHugh Dickins 
1745904249aaSYing Han 	if (global_reclaim(sc)) {
1746b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1747599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
1748904249aaSYing Han 		else
1749599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
1750904249aaSYing Han 	}
1751a74609faSNick Piggin 
175227ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
17533f79768fSHugh Dickins 
1754599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
17553f79768fSHugh Dickins 
1756599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
17573f79768fSHugh Dickins 
1758747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1759b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1760e11da5b4SMel Gorman 
176192df3a72SMel Gorman 	/*
176292df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
176392df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
176492df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
176592df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
176692df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
176792df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
176892df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
176992df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
177092df3a72SMel Gorman 	 *
17718e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
17728e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17738e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
177492df3a72SMel Gorman 	 */
17753c710c1aSMichal Hocko 	if (stat.nr_writeback && stat.nr_writeback == nr_taken)
1776599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
177792df3a72SMel Gorman 
1778d43006d5SMel Gorman 	/*
177997c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
178097c9341fSTejun Heo 	 * stalling here.
1781d43006d5SMel Gorman 	 */
178297c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1783b1a6f21eSMel Gorman 		/*
17848e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
17858e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
17868e950282SMel Gorman 		 */
17873c710c1aSMichal Hocko 		if (stat.nr_dirty && stat.nr_dirty == stat.nr_congested)
1788599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
17898e950282SMel Gorman 
17908e950282SMel Gorman 		/*
1791b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1792726d061fSJohannes Weiner 		 * implies that flushers are not doing their job. This can
1793726d061fSJohannes Weiner 		 * happen when memory pressure pushes dirty pages to the end of
1794726d061fSJohannes Weiner 		 * the LRU before the dirty limits are breached and the dirty
1795726d061fSJohannes Weiner 		 * data has expired. It can also happen when the proportion of
1796726d061fSJohannes Weiner 		 * dirty pages grows not through writes but through memory
1797726d061fSJohannes Weiner 		 * pressure reclaiming all the clean cache. And in some cases,
1798726d061fSJohannes Weiner 		 * the flushers simply cannot keep up with the allocation
1799726d061fSJohannes Weiner 		 * rate. Nudge the flusher threads in case they are asleep, but
1800726d061fSJohannes Weiner 		 * also allow kswapd to start writing pages during reclaim.
1801b1a6f21eSMel Gorman 		 */
1802726d061fSJohannes Weiner 		if (stat.nr_unqueued_dirty == nr_taken) {
1803726d061fSJohannes Weiner 			wakeup_flusher_threads(0, WB_REASON_VMSCAN);
1804599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1805726d061fSJohannes Weiner 		}
1806b1a6f21eSMel Gorman 
1807b1a6f21eSMel Gorman 		/*
1808b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1809b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1810b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1811b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1812b1a6f21eSMel Gorman 		 */
18133c710c1aSMichal Hocko 		if (stat.nr_immediate && current_may_throttle())
1814b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1815e2be15f6SMel Gorman 	}
1816d43006d5SMel Gorman 
18178e950282SMel Gorman 	/*
18188e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
18198e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18208e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18218e950282SMel Gorman 	 */
1822399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1823399ba0b9SNeilBrown 	    current_may_throttle())
1824599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18258e950282SMel Gorman 
1826599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1827599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
18285bccd166SMichal Hocko 			stat.nr_dirty,  stat.nr_writeback,
18295bccd166SMichal Hocko 			stat.nr_congested, stat.nr_immediate,
18305bccd166SMichal Hocko 			stat.nr_activate, stat.nr_ref_keep,
18315bccd166SMichal Hocko 			stat.nr_unmap_fail,
1832ba5e9579Syalin wang 			sc->priority, file);
183305ff5137SAndrew Morton 	return nr_reclaimed;
18341da177e4SLinus Torvalds }
18351da177e4SLinus Torvalds 
18363bb1a852SMartin Bligh /*
18371cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18381cfb419bSKAMEZAWA Hiroyuki  *
18391cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18401cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18411cfb419bSKAMEZAWA Hiroyuki  *
18421cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1843a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18441cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1845a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18461cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18471cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18481cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18491cfb419bSKAMEZAWA Hiroyuki  *
18500139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18511cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
18529d998b4fSMichal Hocko  *
18539d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
18541cfb419bSKAMEZAWA Hiroyuki  */
18551cfb419bSKAMEZAWA Hiroyuki 
18569d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
18573eb4140fSWu Fengguang 				     struct list_head *list,
18582bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18593eb4140fSWu Fengguang 				     enum lru_list lru)
18603eb4140fSWu Fengguang {
1861599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18623eb4140fSWu Fengguang 	struct page *page;
1863fa9add64SHugh Dickins 	int nr_pages;
18649d998b4fSMichal Hocko 	int nr_moved = 0;
18653eb4140fSWu Fengguang 
18663eb4140fSWu Fengguang 	while (!list_empty(list)) {
18673eb4140fSWu Fengguang 		page = lru_to_page(list);
1868599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18693eb4140fSWu Fengguang 
1870309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18713eb4140fSWu Fengguang 		SetPageLRU(page);
18723eb4140fSWu Fengguang 
1873fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1874599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1875925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
18763eb4140fSWu Fengguang 
18772bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18782bcf8879SHugh Dickins 			__ClearPageLRU(page);
18792bcf8879SHugh Dickins 			__ClearPageActive(page);
1880fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18812bcf8879SHugh Dickins 
18822bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1883599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1884747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18852bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1886599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18872bcf8879SHugh Dickins 			} else
18882bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18899d998b4fSMichal Hocko 		} else {
18909d998b4fSMichal Hocko 			nr_moved += nr_pages;
18913eb4140fSWu Fengguang 		}
18923eb4140fSWu Fengguang 	}
18939d5e6a9fSHugh Dickins 
18943eb4140fSWu Fengguang 	if (!is_active_lru(lru))
1895f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
18969d998b4fSMichal Hocko 
18979d998b4fSMichal Hocko 	return nr_moved;
18983eb4140fSWu Fengguang }
18991cfb419bSKAMEZAWA Hiroyuki 
1900f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19011a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1902f16015fbSJohannes Weiner 			       struct scan_control *sc,
19039e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19041cfb419bSKAMEZAWA Hiroyuki {
190544c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1906f626012dSHugh Dickins 	unsigned long nr_scanned;
19076fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19081cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19098cab4754SWu Fengguang 	LIST_HEAD(l_active);
1910b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19111cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19121a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19139d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
19149d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
1915f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19163cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1917599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19181cfb419bSKAMEZAWA Hiroyuki 
19191da177e4SLinus Torvalds 	lru_add_drain();
1920f80c0673SMinchan Kim 
1921f80c0673SMinchan Kim 	if (!sc->may_unmap)
192261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1923f80c0673SMinchan Kim 
1924599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1925925b7673SJohannes Weiner 
19265dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19275dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
192889b5fae5SJohannes Weiner 
1929599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1930b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19311cfb419bSKAMEZAWA Hiroyuki 
1932599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19339d5e6a9fSHugh Dickins 
1934599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19351da177e4SLinus Torvalds 
19361da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19371da177e4SLinus Torvalds 		cond_resched();
19381da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19391da177e4SLinus Torvalds 		list_del(&page->lru);
19407e9cd484SRik van Riel 
194139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1942894bc310SLee Schermerhorn 			putback_lru_page(page);
1943894bc310SLee Schermerhorn 			continue;
1944894bc310SLee Schermerhorn 		}
1945894bc310SLee Schermerhorn 
1946cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1947cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1948cc715d99SMel Gorman 				if (page_has_private(page))
1949cc715d99SMel Gorman 					try_to_release_page(page, 0);
1950cc715d99SMel Gorman 				unlock_page(page);
1951cc715d99SMel Gorman 			}
1952cc715d99SMel Gorman 		}
1953cc715d99SMel Gorman 
1954c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1955c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19569992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19578cab4754SWu Fengguang 			/*
19588cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19598cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19608cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19618cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19628cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19638cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19648cab4754SWu Fengguang 			 * so we ignore them here.
19658cab4754SWu Fengguang 			 */
196641e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19678cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19688cab4754SWu Fengguang 				continue;
19698cab4754SWu Fengguang 			}
19708cab4754SWu Fengguang 		}
19717e9cd484SRik van Riel 
19725205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19731da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19741da177e4SLinus Torvalds 	}
19751da177e4SLinus Torvalds 
1976b555749aSAndrew Morton 	/*
19778cab4754SWu Fengguang 	 * Move pages back to the lru list.
1978b555749aSAndrew Morton 	 */
1979599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19804f98a2feSRik van Riel 	/*
19818cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19828cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19838cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19847c0db9e9SJerome Marchand 	 * get_scan_count.
1985556adecbSRik van Riel 	 */
1986b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1987556adecbSRik van Riel 
19889d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
19899d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1990599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1991599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19922bcf8879SHugh Dickins 
1993747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1994b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
19959d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
19969d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
19971da177e4SLinus Torvalds }
19981da177e4SLinus Torvalds 
199959dc76b0SRik van Riel /*
200059dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
200159dc76b0SRik van Riel  * to do too much work.
200214797e23SKOSAKI Motohiro  *
200359dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
200459dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
200559dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
200659dc76b0SRik van Riel  *
200759dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
200859dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
200959dc76b0SRik van Riel  *
201059dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
201159dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
201259dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
201359dc76b0SRik van Riel  *
201459dc76b0SRik van Riel  * total     target    max
201559dc76b0SRik van Riel  * memory    ratio     inactive
201659dc76b0SRik van Riel  * -------------------------------------
201759dc76b0SRik van Riel  *   10MB       1         5MB
201859dc76b0SRik van Riel  *  100MB       1        50MB
201959dc76b0SRik van Riel  *    1GB       3       250MB
202059dc76b0SRik van Riel  *   10GB      10       0.9GB
202159dc76b0SRik van Riel  *  100GB      31         3GB
202259dc76b0SRik van Riel  *    1TB     101        10GB
202359dc76b0SRik van Riel  *   10TB     320        32GB
202414797e23SKOSAKI Motohiro  */
2025f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
2026dcec0b60SMichal Hocko 						struct scan_control *sc, bool trace)
202714797e23SKOSAKI Motohiro {
202859dc76b0SRik van Riel 	unsigned long inactive_ratio;
2029fd538803SMichal Hocko 	unsigned long inactive, active;
2030fd538803SMichal Hocko 	enum lru_list inactive_lru = file * LRU_FILE;
2031fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
203259dc76b0SRik van Riel 	unsigned long gb;
203359dc76b0SRik van Riel 
203474e3f3c3SMinchan Kim 	/*
203574e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
203674e3f3c3SMinchan Kim 	 * is pointless.
203774e3f3c3SMinchan Kim 	 */
203859dc76b0SRik van Riel 	if (!file && !total_swap_pages)
203942e2e457SYaowei Bai 		return false;
204074e3f3c3SMinchan Kim 
2041fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2042fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2043f8d1a311SMel Gorman 
204459dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
204559dc76b0SRik van Riel 	if (gb)
204659dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2047b39415b2SRik van Riel 	else
204859dc76b0SRik van Riel 		inactive_ratio = 1;
204959dc76b0SRik van Riel 
2050dcec0b60SMichal Hocko 	if (trace)
2051fd538803SMichal Hocko 		trace_mm_vmscan_inactive_list_is_low(lruvec_pgdat(lruvec)->node_id,
2052dcec0b60SMichal Hocko 				sc->reclaim_idx,
2053fd538803SMichal Hocko 				lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2054fd538803SMichal Hocko 				lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2055fd538803SMichal Hocko 				inactive_ratio, file);
2056fd538803SMichal Hocko 
205759dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2058b39415b2SRik van Riel }
2059b39415b2SRik van Riel 
20604f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
20611a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
2062b69408e8SChristoph Lameter {
2063b39415b2SRik van Riel 	if (is_active_lru(lru)) {
2064dcec0b60SMichal Hocko 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc, true))
20651a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2066556adecbSRik van Riel 		return 0;
2067556adecbSRik van Riel 	}
2068556adecbSRik van Riel 
20691a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2070b69408e8SChristoph Lameter }
2071b69408e8SChristoph Lameter 
20729a265114SJohannes Weiner enum scan_balance {
20739a265114SJohannes Weiner 	SCAN_EQUAL,
20749a265114SJohannes Weiner 	SCAN_FRACT,
20759a265114SJohannes Weiner 	SCAN_ANON,
20769a265114SJohannes Weiner 	SCAN_FILE,
20779a265114SJohannes Weiner };
20789a265114SJohannes Weiner 
20791da177e4SLinus Torvalds /*
20804f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
20814f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
20824f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
20834f98a2feSRik van Riel  * onto the active list instead of evict.
20844f98a2feSRik van Riel  *
2085be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2086be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
20874f98a2feSRik van Riel  */
208833377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
20896b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
20906b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
20914f98a2feSRik van Riel {
209233377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
209390126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20949a265114SJohannes Weiner 	u64 fraction[2];
20959a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2096599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20979a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
20989a265114SJohannes Weiner 	enum scan_balance scan_balance;
20990bf1457fSJohannes Weiner 	unsigned long anon, file;
21009a265114SJohannes Weiner 	unsigned long ap, fp;
21019a265114SJohannes Weiner 	enum lru_list lru;
210276a33fc3SShaohua Li 
210376a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2104d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21059a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
210676a33fc3SShaohua Li 		goto out;
210776a33fc3SShaohua Li 	}
21084f98a2feSRik van Riel 
210910316b31SJohannes Weiner 	/*
211010316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
211110316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
211210316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
211310316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
211410316b31SJohannes Weiner 	 * too expensive.
211510316b31SJohannes Weiner 	 */
211602695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21179a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
211810316b31SJohannes Weiner 		goto out;
211910316b31SJohannes Weiner 	}
212010316b31SJohannes Weiner 
212110316b31SJohannes Weiner 	/*
212210316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
212310316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
212410316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
212510316b31SJohannes Weiner 	 */
212602695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21279a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
212810316b31SJohannes Weiner 		goto out;
212910316b31SJohannes Weiner 	}
213010316b31SJohannes Weiner 
213111d16c25SJohannes Weiner 	/*
213262376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
213362376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
213462376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
213562376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
213662376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
213762376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
213862376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
213962376251SJohannes Weiner 	 */
214062376251SJohannes Weiner 	if (global_reclaim(sc)) {
2141599d0c95SMel Gorman 		unsigned long pgdatfile;
2142599d0c95SMel Gorman 		unsigned long pgdatfree;
2143599d0c95SMel Gorman 		int z;
2144599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
214562376251SJohannes Weiner 
2146599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2147599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2148599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21492ab051e1SJerome Marchand 
2150599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2151599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
21526aa303deSMel Gorman 			if (!managed_zone(zone))
2153599d0c95SMel Gorman 				continue;
2154599d0c95SMel Gorman 
2155599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2156599d0c95SMel Gorman 		}
2157599d0c95SMel Gorman 
2158599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
215962376251SJohannes Weiner 			scan_balance = SCAN_ANON;
216062376251SJohannes Weiner 			goto out;
216162376251SJohannes Weiner 		}
216262376251SJohannes Weiner 	}
216362376251SJohannes Weiner 
216462376251SJohannes Weiner 	/*
2165316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2166316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2167316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2168316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2169316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2170316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2171316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2172e9868505SRik van Riel 	 */
2173dcec0b60SMichal Hocko 	if (!inactive_list_is_low(lruvec, true, sc, false) &&
217471ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
21759a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2176e9868505SRik van Riel 		goto out;
21774f98a2feSRik van Riel 	}
21784f98a2feSRik van Riel 
21799a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
21809a265114SJohannes Weiner 
21814f98a2feSRik van Riel 	/*
218258c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
218358c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
218458c37f6eSKOSAKI Motohiro 	 */
218502695175SJohannes Weiner 	anon_prio = swappiness;
218675b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
218758c37f6eSKOSAKI Motohiro 
218858c37f6eSKOSAKI Motohiro 	/*
21894f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
21904f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
21914f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
21924f98a2feSRik van Riel 	 *
21934f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
21944f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
21954f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
21964f98a2feSRik van Riel 	 *
21974f98a2feSRik van Riel 	 * anon in [0], file in [1]
21984f98a2feSRik van Riel 	 */
21992ab051e1SJerome Marchand 
2200fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2201fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2202fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2203fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
22042ab051e1SJerome Marchand 
2205599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
220658c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22076e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22086e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22094f98a2feSRik van Riel 	}
22104f98a2feSRik van Riel 
22116e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22126e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22136e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22144f98a2feSRik van Riel 	}
22154f98a2feSRik van Riel 
22164f98a2feSRik van Riel 	/*
221700d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
221800d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
221900d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22204f98a2feSRik van Riel 	 */
2221fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22226e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22234f98a2feSRik van Riel 
2224fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22256e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2226599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22274f98a2feSRik van Riel 
222876a33fc3SShaohua Li 	fraction[0] = ap;
222976a33fc3SShaohua Li 	fraction[1] = fp;
223076a33fc3SShaohua Li 	denominator = ap + fp + 1;
223176a33fc3SShaohua Li out:
22326b4f7799SJohannes Weiner 	*lru_pages = 0;
22334111304dSHugh Dickins 	for_each_evictable_lru(lru) {
22344111304dSHugh Dickins 		int file = is_file_lru(lru);
2235d778df51SJohannes Weiner 		unsigned long size;
223676a33fc3SShaohua Li 		unsigned long scan;
223776a33fc3SShaohua Li 
223871ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2239d778df51SJohannes Weiner 		scan = size >> sc->priority;
2240688035f7SJohannes Weiner 		/*
2241688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2242688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2243688035f7SJohannes Weiner 		 */
2244688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2245d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
22469a265114SJohannes Weiner 
22479a265114SJohannes Weiner 		switch (scan_balance) {
22489a265114SJohannes Weiner 		case SCAN_EQUAL:
22499a265114SJohannes Weiner 			/* Scan lists relative to size */
22509a265114SJohannes Weiner 			break;
22519a265114SJohannes Weiner 		case SCAN_FRACT:
22529a265114SJohannes Weiner 			/*
22539a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
22549a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
22559a265114SJohannes Weiner 			 */
22566f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
22576f04f48dSSuleiman Souhlal 					 denominator);
22589a265114SJohannes Weiner 			break;
22599a265114SJohannes Weiner 		case SCAN_FILE:
22609a265114SJohannes Weiner 		case SCAN_ANON:
22619a265114SJohannes Weiner 			/* Scan one type exclusively */
22626b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
22636b4f7799SJohannes Weiner 				size = 0;
22649a265114SJohannes Weiner 				scan = 0;
22656b4f7799SJohannes Weiner 			}
22669a265114SJohannes Weiner 			break;
22679a265114SJohannes Weiner 		default:
22689a265114SJohannes Weiner 			/* Look ma, no brain */
22699a265114SJohannes Weiner 			BUG();
22709a265114SJohannes Weiner 		}
22716b4f7799SJohannes Weiner 
22726b4f7799SJohannes Weiner 		*lru_pages += size;
22734111304dSHugh Dickins 		nr[lru] = scan;
227476a33fc3SShaohua Li 	}
22756e08a369SWu Fengguang }
22764f98a2feSRik van Riel 
22779b4f98cdSJohannes Weiner /*
2278a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
22799b4f98cdSJohannes Weiner  */
2280a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
22816b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
22829b4f98cdSJohannes Weiner {
2283ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
22849b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2285e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
22869b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
22879b4f98cdSJohannes Weiner 	enum lru_list lru;
22889b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
22899b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
22909b4f98cdSJohannes Weiner 	struct blk_plug plug;
22911a501907SMel Gorman 	bool scan_adjusted;
22929b4f98cdSJohannes Weiner 
229333377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
22949b4f98cdSJohannes Weiner 
2295e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2296e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2297e82e0561SMel Gorman 
22981a501907SMel Gorman 	/*
22991a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23001a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23011a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23021a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23031a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23041a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23051a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23061a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23071a501907SMel Gorman 	 * dropped to zero at the first pass.
23081a501907SMel Gorman 	 */
23091a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23101a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23111a501907SMel Gorman 
23129b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23139b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23149b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2315e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2316e82e0561SMel Gorman 		unsigned long nr_scanned;
2317e82e0561SMel Gorman 
23189b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23199b4f98cdSJohannes Weiner 			if (nr[lru]) {
23209b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23219b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23229b4f98cdSJohannes Weiner 
23239b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23249b4f98cdSJohannes Weiner 							    lruvec, sc);
23259b4f98cdSJohannes Weiner 			}
23269b4f98cdSJohannes Weiner 		}
2327e82e0561SMel Gorman 
2328bd041733SMichal Hocko 		cond_resched();
2329bd041733SMichal Hocko 
2330e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2331e82e0561SMel Gorman 			continue;
2332e82e0561SMel Gorman 
23339b4f98cdSJohannes Weiner 		/*
2334e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23351a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2336e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2337e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2338e82e0561SMel Gorman 		 * proportional to the original scan target.
2339e82e0561SMel Gorman 		 */
2340e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2341e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2342e82e0561SMel Gorman 
23431a501907SMel Gorman 		/*
23441a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23451a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23461a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23471a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23481a501907SMel Gorman 		 */
23491a501907SMel Gorman 		if (!nr_file || !nr_anon)
23501a501907SMel Gorman 			break;
23511a501907SMel Gorman 
2352e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2353e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2354e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2355e82e0561SMel Gorman 			lru = LRU_BASE;
2356e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2357e82e0561SMel Gorman 		} else {
2358e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2359e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2360e82e0561SMel Gorman 			lru = LRU_FILE;
2361e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2362e82e0561SMel Gorman 		}
2363e82e0561SMel Gorman 
2364e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2365e82e0561SMel Gorman 		nr[lru] = 0;
2366e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2367e82e0561SMel Gorman 
2368e82e0561SMel Gorman 		/*
2369e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2370e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2371e82e0561SMel Gorman 		 */
2372e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2373e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2374e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2375e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2376e82e0561SMel Gorman 
2377e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2378e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2379e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2380e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2381e82e0561SMel Gorman 
2382e82e0561SMel Gorman 		scan_adjusted = true;
23839b4f98cdSJohannes Weiner 	}
23849b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
23859b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
23869b4f98cdSJohannes Weiner 
23879b4f98cdSJohannes Weiner 	/*
23889b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
23899b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
23909b4f98cdSJohannes Weiner 	 */
2391dcec0b60SMichal Hocko 	if (inactive_list_is_low(lruvec, false, sc, true))
23929b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
23939b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
23949b4f98cdSJohannes Weiner }
23959b4f98cdSJohannes Weiner 
239623b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
23979e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
239823b9da55SMel Gorman {
2399d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
240023b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24019e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
240223b9da55SMel Gorman 		return true;
240323b9da55SMel Gorman 
240423b9da55SMel Gorman 	return false;
240523b9da55SMel Gorman }
240623b9da55SMel Gorman 
24074f98a2feSRik van Riel /*
240823b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
240923b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
241023b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
241123b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
241223b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24133e7d3449SMel Gorman  */
2414a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24153e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24163e7d3449SMel Gorman 					unsigned long nr_scanned,
24173e7d3449SMel Gorman 					struct scan_control *sc)
24183e7d3449SMel Gorman {
24193e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24203e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2421a9dd0a83SMel Gorman 	int z;
24223e7d3449SMel Gorman 
24233e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24249e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24253e7d3449SMel Gorman 		return false;
24263e7d3449SMel Gorman 
24272876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
24282876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
24293e7d3449SMel Gorman 		/*
24302876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
24312876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24322876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
24332876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
24343e7d3449SMel Gorman 		 */
24353e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24363e7d3449SMel Gorman 			return false;
24372876592fSMel Gorman 	} else {
24382876592fSMel Gorman 		/*
24392876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
24402876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24412876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24422876592fSMel Gorman 		 * pages that were scanned. This will return to the
24432876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24442876592fSMel Gorman 		 * the resulting allocation attempt fails
24452876592fSMel Gorman 		 */
24462876592fSMel Gorman 		if (!nr_reclaimed)
24472876592fSMel Gorman 			return false;
24482876592fSMel Gorman 	}
24493e7d3449SMel Gorman 
24503e7d3449SMel Gorman 	/*
24513e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24523e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24533e7d3449SMel Gorman 	 */
24549861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2455a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2456ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2457a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
24583e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24593e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24603e7d3449SMel Gorman 		return true;
24613e7d3449SMel Gorman 
24623e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2463a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2464a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
24656aa303deSMel Gorman 		if (!managed_zone(zone))
2466a9dd0a83SMel Gorman 			continue;
2467a9dd0a83SMel Gorman 
2468a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2469cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
24703e7d3449SMel Gorman 		case COMPACT_CONTINUE:
24713e7d3449SMel Gorman 			return false;
24723e7d3449SMel Gorman 		default:
2473a9dd0a83SMel Gorman 			/* check next zone */
2474a9dd0a83SMel Gorman 			;
24753e7d3449SMel Gorman 		}
24763e7d3449SMel Gorman 	}
2477a9dd0a83SMel Gorman 	return true;
2478a9dd0a83SMel Gorman }
24793e7d3449SMel Gorman 
2480970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2481f16015fbSJohannes Weiner {
2482cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
24839b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
24842344d7e4SJohannes Weiner 	bool reclaimable = false;
24859b4f98cdSJohannes Weiner 
24869b4f98cdSJohannes Weiner 	do {
24875660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
24885660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2489ef8f2327SMel Gorman 			.pgdat = pgdat,
24909e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
24915660048cSJohannes Weiner 		};
2492a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2493694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
24945660048cSJohannes Weiner 
24959b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
24969b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
24979b4f98cdSJohannes Weiner 
2498694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2499694fbc0fSAndrew Morton 		do {
25006b4f7799SJohannes Weiner 			unsigned long lru_pages;
25018e8ae645SJohannes Weiner 			unsigned long reclaimed;
2502cb731d6cSVladimir Davydov 			unsigned long scanned;
25039b4f98cdSJohannes Weiner 
2504241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2505241994edSJohannes Weiner 				if (!sc->may_thrash)
2506241994edSJohannes Weiner 					continue;
2507241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2508241994edSJohannes Weiner 			}
2509241994edSJohannes Weiner 
25108e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2511cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
25125660048cSJohannes Weiner 
2513a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2514a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2515f9be23d6SKonstantin Khlebnikov 
2516b5afba29SVladimir Davydov 			if (memcg)
2517a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
2518cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2519cb731d6cSVladimir Davydov 					    lru_pages);
2520cb731d6cSVladimir Davydov 
25218e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25228e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25238e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25248e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25258e8ae645SJohannes Weiner 
25265660048cSJohannes Weiner 			/*
2527a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2528a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2529a9dd0a83SMel Gorman 			 * node.
2530a394cb8eSMichal Hocko 			 *
2531a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2532a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2533a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2534a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25355660048cSJohannes Weiner 			 */
2536a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2537a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25385660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25395660048cSJohannes Weiner 				break;
25405660048cSJohannes Weiner 			}
2541241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
254270ddf637SAnton Vorontsov 
25436b4f7799SJohannes Weiner 		/*
25446b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
25456b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
25466b4f7799SJohannes Weiner 		 */
2547b2e18757SMel Gorman 		if (global_reclaim(sc))
2548a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25496b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
2550a9dd0a83SMel Gorman 				    node_lru_pages);
25516b4f7799SJohannes Weiner 
25526b4f7799SJohannes Weiner 		if (reclaim_state) {
2553cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25546b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25556b4f7799SJohannes Weiner 		}
25566b4f7799SJohannes Weiner 
25578e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25588e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
255970ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
256070ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
256170ddf637SAnton Vorontsov 
25622344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
25632344d7e4SJohannes Weiner 			reclaimable = true;
25642344d7e4SJohannes Weiner 
2565a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
25669b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
25672344d7e4SJohannes Weiner 
2568c73322d0SJohannes Weiner 	/*
2569c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2570c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2571c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2572c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2573c73322d0SJohannes Weiner 	 */
2574c73322d0SJohannes Weiner 	if (reclaimable)
2575c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2576c73322d0SJohannes Weiner 
25772344d7e4SJohannes Weiner 	return reclaimable;
2578f16015fbSJohannes Weiner }
2579f16015fbSJohannes Weiner 
258053853e2dSVlastimil Babka /*
2581fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2582fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2583fdd4c614SVlastimil Babka  * should reclaim first.
258453853e2dSVlastimil Babka  */
25854f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2586fe4b1b24SMel Gorman {
258731483b6aSMel Gorman 	unsigned long watermark;
2588fdd4c614SVlastimil Babka 	enum compact_result suitable;
2589fe4b1b24SMel Gorman 
2590fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2591fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2592fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2593fdd4c614SVlastimil Babka 		return true;
2594fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2595fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2596fe4b1b24SMel Gorman 		return false;
2597fe4b1b24SMel Gorman 
2598fdd4c614SVlastimil Babka 	/*
2599fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2600fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2601fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2602fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2603fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2604fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2605fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2606fdd4c614SVlastimil Babka 	 */
2607fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2608fdd4c614SVlastimil Babka 
2609fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2610fe4b1b24SMel Gorman }
2611fe4b1b24SMel Gorman 
26121da177e4SLinus Torvalds /*
26131da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
26141da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
26151da177e4SLinus Torvalds  * request.
26161da177e4SLinus Torvalds  *
26171da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
26181da177e4SLinus Torvalds  * scan then give up on it.
26191da177e4SLinus Torvalds  */
26200a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
26211da177e4SLinus Torvalds {
2622dd1a239fSMel Gorman 	struct zoneref *z;
262354a6eb5cSMel Gorman 	struct zone *zone;
26240608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26250608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2626619d0d76SWeijie Yang 	gfp_t orig_mask;
262779dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
26281cfb419bSKAMEZAWA Hiroyuki 
2629cc715d99SMel Gorman 	/*
2630cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2631cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2632cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2633cc715d99SMel Gorman 	 */
2634619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2635b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2636cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
26374f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2638b2e18757SMel Gorman 	}
2639cc715d99SMel Gorman 
2640d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2641b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2642b2e18757SMel Gorman 		/*
26431cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26441cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26451cfb419bSKAMEZAWA Hiroyuki 		 */
264689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2647344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2648344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26491da177e4SLinus Torvalds 				continue;
265065ec02cbSVladimir Davydov 
2651e0887c19SRik van Riel 			/*
2652e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2653e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2654e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2655e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2656e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2657c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2658c7cfa37bSCopot Alexandru 			 * page allocations.
2659e0887c19SRik van Riel 			 */
26600b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
26610b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
26624f588331SMel Gorman 			    compaction_ready(zone, sc)) {
26630b06496aSJohannes Weiner 				sc->compaction_ready = true;
2664e0887c19SRik van Riel 				continue;
2665e0887c19SRik van Riel 			}
26660b06496aSJohannes Weiner 
26670608f43dSAndrew Morton 			/*
266879dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
266979dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
267079dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
267179dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
267279dafcdcSMel Gorman 			 */
267379dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
267479dafcdcSMel Gorman 				continue;
267579dafcdcSMel Gorman 
267679dafcdcSMel Gorman 			/*
26770608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
26780608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
26790608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
26800608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
26810608f43dSAndrew Morton 			 */
26820608f43dSAndrew Morton 			nr_soft_scanned = 0;
2683ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
26840608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
26850608f43dSAndrew Morton 						&nr_soft_scanned);
26860608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
26870608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2688ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2689ac34a1a3SKAMEZAWA Hiroyuki 		}
2690d149e3b2SYing Han 
269179dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
269279dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
269379dafcdcSMel Gorman 			continue;
269479dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2695970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
26961da177e4SLinus Torvalds 	}
2697e0c23279SMel Gorman 
269865ec02cbSVladimir Davydov 	/*
2699619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2700619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2701619d0d76SWeijie Yang 	 */
2702619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27031da177e4SLinus Torvalds }
27041da177e4SLinus Torvalds 
27051da177e4SLinus Torvalds /*
27061da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
27071da177e4SLinus Torvalds  *
27081da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
27091da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
27101da177e4SLinus Torvalds  *
27111da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
27121da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
27135b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
27145b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
27155b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
27165b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2717a41f24eaSNishanth Aravamudan  *
2718a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2719a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
27201da177e4SLinus Torvalds  */
2721dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
27223115cd91SVladimir Davydov 					  struct scan_control *sc)
27231da177e4SLinus Torvalds {
2724241994edSJohannes Weiner 	int initial_priority = sc->priority;
2725241994edSJohannes Weiner retry:
2726873b4771SKeika Kobayashi 	delayacct_freepages_start();
2727873b4771SKeika Kobayashi 
272889b5fae5SJohannes Weiner 	if (global_reclaim(sc))
27297cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
27301da177e4SLinus Torvalds 
27319e3b2f8cSKonstantin Khlebnikov 	do {
273270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
273370ddf637SAnton Vorontsov 				sc->priority);
273466e1707bSBalbir Singh 		sc->nr_scanned = 0;
27350a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2736e0c23279SMel Gorman 
2737bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
27380b06496aSJohannes Weiner 			break;
27390b06496aSJohannes Weiner 
27400b06496aSJohannes Weiner 		if (sc->compaction_ready)
27410b06496aSJohannes Weiner 			break;
27421da177e4SLinus Torvalds 
27431da177e4SLinus Torvalds 		/*
27440e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27450e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27460e50ce3bSMinchan Kim 		 */
27470e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27480e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27490b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2750bb21c7ceSKOSAKI Motohiro 
2751873b4771SKeika Kobayashi 	delayacct_freepages_end();
2752873b4771SKeika Kobayashi 
2753bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2754bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2755bb21c7ceSKOSAKI Motohiro 
27560cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
27570b06496aSJohannes Weiner 	if (sc->compaction_ready)
27587335084dSMel Gorman 		return 1;
27597335084dSMel Gorman 
2760241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2761241994edSJohannes Weiner 	if (!sc->may_thrash) {
2762241994edSJohannes Weiner 		sc->priority = initial_priority;
2763241994edSJohannes Weiner 		sc->may_thrash = 1;
2764241994edSJohannes Weiner 		goto retry;
2765241994edSJohannes Weiner 	}
2766241994edSJohannes Weiner 
2767bb21c7ceSKOSAKI Motohiro 	return 0;
27681da177e4SLinus Torvalds }
27691da177e4SLinus Torvalds 
2770c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
27715515061dSMel Gorman {
27725515061dSMel Gorman 	struct zone *zone;
27735515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
27745515061dSMel Gorman 	unsigned long free_pages = 0;
27755515061dSMel Gorman 	int i;
27765515061dSMel Gorman 	bool wmark_ok;
27775515061dSMel Gorman 
2778c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
2779c73322d0SJohannes Weiner 		return true;
2780c73322d0SJohannes Weiner 
27815515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
27825515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2783d450abd8SJohannes Weiner 		if (!managed_zone(zone))
2784d450abd8SJohannes Weiner 			continue;
2785d450abd8SJohannes Weiner 
2786d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
2787675becceSMel Gorman 			continue;
2788675becceSMel Gorman 
27895515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
27905515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
27915515061dSMel Gorman 	}
27925515061dSMel Gorman 
2793675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2794675becceSMel Gorman 	if (!pfmemalloc_reserve)
2795675becceSMel Gorman 		return true;
2796675becceSMel Gorman 
27975515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
27985515061dSMel Gorman 
27995515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
28005515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
280138087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
28025515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
28035515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
28045515061dSMel Gorman 	}
28055515061dSMel Gorman 
28065515061dSMel Gorman 	return wmark_ok;
28075515061dSMel Gorman }
28085515061dSMel Gorman 
28095515061dSMel Gorman /*
28105515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
28115515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
28125515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
281350694c28SMel Gorman  * when the low watermark is reached.
281450694c28SMel Gorman  *
281550694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
281650694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
28175515061dSMel Gorman  */
281850694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
28195515061dSMel Gorman 					nodemask_t *nodemask)
28205515061dSMel Gorman {
2821675becceSMel Gorman 	struct zoneref *z;
28225515061dSMel Gorman 	struct zone *zone;
2823675becceSMel Gorman 	pg_data_t *pgdat = NULL;
28245515061dSMel Gorman 
28255515061dSMel Gorman 	/*
28265515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
28275515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
28285515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
28295515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
28305515061dSMel Gorman 	 * processes to block on log_wait_commit().
28315515061dSMel Gorman 	 */
28325515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
283350694c28SMel Gorman 		goto out;
283450694c28SMel Gorman 
283550694c28SMel Gorman 	/*
283650694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
283750694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
283850694c28SMel Gorman 	 */
283950694c28SMel Gorman 	if (fatal_signal_pending(current))
284050694c28SMel Gorman 		goto out;
28415515061dSMel Gorman 
2842675becceSMel Gorman 	/*
2843675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2844675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2845675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2846675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2847675becceSMel Gorman 	 *
2848675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2849675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2850675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2851675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2852675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2853675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2854675becceSMel Gorman 	 * should make reasonable progress.
2855675becceSMel Gorman 	 */
2856675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
285717636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2858675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2859675becceSMel Gorman 			continue;
2860675becceSMel Gorman 
2861675becceSMel Gorman 		/* Throttle based on the first usable node */
28625515061dSMel Gorman 		pgdat = zone->zone_pgdat;
2863c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
286450694c28SMel Gorman 			goto out;
2865675becceSMel Gorman 		break;
2866675becceSMel Gorman 	}
2867675becceSMel Gorman 
2868675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2869675becceSMel Gorman 	if (!pgdat)
2870675becceSMel Gorman 		goto out;
28715515061dSMel Gorman 
287268243e76SMel Gorman 	/* Account for the throttling */
287368243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
287468243e76SMel Gorman 
28755515061dSMel Gorman 	/*
28765515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
28775515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
28785515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
28795515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
28805515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
28815515061dSMel Gorman 	 * second before continuing.
28825515061dSMel Gorman 	 */
28835515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
28845515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2885c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
288650694c28SMel Gorman 
288750694c28SMel Gorman 		goto check_pending;
28885515061dSMel Gorman 	}
28895515061dSMel Gorman 
28905515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
28915515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2892c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
289350694c28SMel Gorman 
289450694c28SMel Gorman check_pending:
289550694c28SMel Gorman 	if (fatal_signal_pending(current))
289650694c28SMel Gorman 		return true;
289750694c28SMel Gorman 
289850694c28SMel Gorman out:
289950694c28SMel Gorman 	return false;
29005515061dSMel Gorman }
29015515061dSMel Gorman 
2902dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2903327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
290466e1707bSBalbir Singh {
290533906bc5SMel Gorman 	unsigned long nr_reclaimed;
290666e1707bSBalbir Singh 	struct scan_control sc = {
290722fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2908ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2909b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2910ee814fe2SJohannes Weiner 		.order = order,
2911ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2912ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2913ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2914a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29152e2e4259SKOSAKI Motohiro 		.may_swap = 1,
291666e1707bSBalbir Singh 	};
291766e1707bSBalbir Singh 
29185515061dSMel Gorman 	/*
291950694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
292050694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
292150694c28SMel Gorman 	 * point.
29225515061dSMel Gorman 	 */
292350694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
29245515061dSMel Gorman 		return 1;
29255515061dSMel Gorman 
292633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
292733906bc5SMel Gorman 				sc.may_writepage,
2928e5146b12SMel Gorman 				gfp_mask,
2929e5146b12SMel Gorman 				sc.reclaim_idx);
293033906bc5SMel Gorman 
29313115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
293233906bc5SMel Gorman 
293333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
293433906bc5SMel Gorman 
293533906bc5SMel Gorman 	return nr_reclaimed;
293666e1707bSBalbir Singh }
293766e1707bSBalbir Singh 
2938c255a458SAndrew Morton #ifdef CONFIG_MEMCG
293966e1707bSBalbir Singh 
2940a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
29414e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
2942ef8f2327SMel Gorman 						pg_data_t *pgdat,
29430ae5e89cSYing Han 						unsigned long *nr_scanned)
29444e416953SBalbir Singh {
29454e416953SBalbir Singh 	struct scan_control sc = {
2946b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2947ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
29484e416953SBalbir Singh 		.may_writepage = !laptop_mode,
29494e416953SBalbir Singh 		.may_unmap = 1,
2950b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
29514e416953SBalbir Singh 		.may_swap = !noswap,
29524e416953SBalbir Singh 	};
29536b4f7799SJohannes Weiner 	unsigned long lru_pages;
29540ae5e89cSYing Han 
29554e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
29564e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2957bdce6d9eSKOSAKI Motohiro 
29589e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2959bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
2960e5146b12SMel Gorman 						      sc.gfp_mask,
2961e5146b12SMel Gorman 						      sc.reclaim_idx);
2962bdce6d9eSKOSAKI Motohiro 
29634e416953SBalbir Singh 	/*
29644e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
29654e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
2966a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
29674e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
29684e416953SBalbir Singh 	 * the priority and make it zero.
29694e416953SBalbir Singh 	 */
2970ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
2971bdce6d9eSKOSAKI Motohiro 
2972bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2973bdce6d9eSKOSAKI Motohiro 
29740ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
29754e416953SBalbir Singh 	return sc.nr_reclaimed;
29764e416953SBalbir Singh }
29774e416953SBalbir Singh 
297872835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2979b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
29808c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
2981b70a2a21SJohannes Weiner 					   bool may_swap)
298266e1707bSBalbir Singh {
29834e416953SBalbir Singh 	struct zonelist *zonelist;
2984bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
2985889976dbSYing Han 	int nid;
298666e1707bSBalbir Singh 	struct scan_control sc = {
2987b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
2988ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2989ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2990b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
2991ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
2992ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
299366e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
2994a6dc60f8SJohannes Weiner 		.may_unmap = 1,
2995b70a2a21SJohannes Weiner 		.may_swap = may_swap,
2996a09ed5e0SYing Han 	};
299766e1707bSBalbir Singh 
2998889976dbSYing Han 	/*
2999889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3000889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3001889976dbSYing Han 	 * scan does not need to be the current node.
3002889976dbSYing Han 	 */
300372835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3004889976dbSYing Han 
3005c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3006bdce6d9eSKOSAKI Motohiro 
3007bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3008bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3009e5146b12SMel Gorman 					    sc.gfp_mask,
3010e5146b12SMel Gorman 					    sc.reclaim_idx);
3011bdce6d9eSKOSAKI Motohiro 
301289a28483SJohannes Weiner 	current->flags |= PF_MEMALLOC;
30133115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
301489a28483SJohannes Weiner 	current->flags &= ~PF_MEMALLOC;
3015bdce6d9eSKOSAKI Motohiro 
3016bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3017bdce6d9eSKOSAKI Motohiro 
3018bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
301966e1707bSBalbir Singh }
302066e1707bSBalbir Singh #endif
302166e1707bSBalbir Singh 
30221d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3023ef8f2327SMel Gorman 				struct scan_control *sc)
3024f16015fbSJohannes Weiner {
3025b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3026b95a2f2dSJohannes Weiner 
3027b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3028b95a2f2dSJohannes Weiner 		return;
3029b95a2f2dSJohannes Weiner 
3030b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3031b95a2f2dSJohannes Weiner 	do {
3032ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3033f16015fbSJohannes Weiner 
3034dcec0b60SMichal Hocko 		if (inactive_list_is_low(lruvec, false, sc, true))
30351a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30369e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3037b95a2f2dSJohannes Weiner 
3038b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3039b95a2f2dSJohannes Weiner 	} while (memcg);
3040f16015fbSJohannes Weiner }
3041f16015fbSJohannes Weiner 
304231483b6aSMel Gorman static bool zone_balanced(struct zone *zone, int order, int classzone_idx)
304360cefed4SJohannes Weiner {
304431483b6aSMel Gorman 	unsigned long mark = high_wmark_pages(zone);
304560cefed4SJohannes Weiner 
30466256c6b4SMel Gorman 	if (!zone_watermark_ok_safe(zone, order, mark, classzone_idx))
30476256c6b4SMel Gorman 		return false;
30486256c6b4SMel Gorman 
30496256c6b4SMel Gorman 	/*
30506256c6b4SMel Gorman 	 * If any eligible zone is balanced then the node is not considered
30516256c6b4SMel Gorman 	 * to be congested or dirty
30526256c6b4SMel Gorman 	 */
30536256c6b4SMel Gorman 	clear_bit(PGDAT_CONGESTED, &zone->zone_pgdat->flags);
30546256c6b4SMel Gorman 	clear_bit(PGDAT_DIRTY, &zone->zone_pgdat->flags);
3055c2f83143SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &zone->zone_pgdat->flags);
30566256c6b4SMel Gorman 
30576256c6b4SMel Gorman 	return true;
305860cefed4SJohannes Weiner }
305960cefed4SJohannes Weiner 
30601741c877SMel Gorman /*
30615515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
30625515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
30635515061dSMel Gorman  *
30645515061dSMel Gorman  * Returns true if kswapd is ready to sleep
30655515061dSMel Gorman  */
3066d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3067f50de2d3SMel Gorman {
30681d82de61SMel Gorman 	int i;
30691d82de61SMel Gorman 
30705515061dSMel Gorman 	/*
30719e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3072c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
30739e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
30749e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
30759e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
30769e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
30779e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
30789e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
30799e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
30809e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
30819e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
30825515061dSMel Gorman 	 */
30839e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
30849e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3085f50de2d3SMel Gorman 
3086c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3087c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3088c73322d0SJohannes Weiner 		return true;
3089c73322d0SJohannes Weiner 
30901d82de61SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
30911d82de61SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
30921d82de61SMel Gorman 
30936aa303deSMel Gorman 		if (!managed_zone(zone))
30941d82de61SMel Gorman 			continue;
30951d82de61SMel Gorman 
309638087d9bSMel Gorman 		if (!zone_balanced(zone, order, classzone_idx))
309738087d9bSMel Gorman 			return false;
30981d82de61SMel Gorman 	}
30991d82de61SMel Gorman 
310038087d9bSMel Gorman 	return true;
3101f50de2d3SMel Gorman }
3102f50de2d3SMel Gorman 
31031da177e4SLinus Torvalds /*
31041d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
31051d82de61SMel Gorman  * zone that is currently unbalanced.
3106b8e83b94SMel Gorman  *
3107b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3108283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3109283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
311075485363SMel Gorman  */
31111d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3112accf6242SVlastimil Babka 			       struct scan_control *sc)
311375485363SMel Gorman {
31141d82de61SMel Gorman 	struct zone *zone;
31151d82de61SMel Gorman 	int z;
311675485363SMel Gorman 
31171d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
31181d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3119970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
31201d82de61SMel Gorman 		zone = pgdat->node_zones + z;
31216aa303deSMel Gorman 		if (!managed_zone(zone))
31221d82de61SMel Gorman 			continue;
31237c954f6dSMel Gorman 
31241d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
31257c954f6dSMel Gorman 	}
31267c954f6dSMel Gorman 
31271d82de61SMel Gorman 	/*
31281d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
31291d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
31301d82de61SMel Gorman 	 */
3131970a39a3SMel Gorman 	shrink_node(pgdat, sc);
31321d82de61SMel Gorman 
31331d82de61SMel Gorman 	/*
31341d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
31351d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
31361d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
31371d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
31381d82de61SMel Gorman 	 * can direct reclaim/compact.
31391d82de61SMel Gorman 	 */
31409861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
31411d82de61SMel Gorman 		sc->order = 0;
31421d82de61SMel Gorman 
3143b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
314475485363SMel Gorman }
314575485363SMel Gorman 
314675485363SMel Gorman /*
31471d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
31481d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
31491d82de61SMel Gorman  * balanced.
31501da177e4SLinus Torvalds  *
31511d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
31521da177e4SLinus Torvalds  *
31531da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
315441858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
31551d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
31561d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
31571d82de61SMel Gorman  * balanced.
31581da177e4SLinus Torvalds  */
3159accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
31601da177e4SLinus Torvalds {
31611da177e4SLinus Torvalds 	int i;
31620608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
31630608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
31641d82de61SMel Gorman 	struct zone *zone;
3165179e9639SAndrew Morton 	struct scan_control sc = {
3166179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3167ee814fe2SJohannes Weiner 		.order = order,
3168b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3169ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3170a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31712e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3172179e9639SAndrew Morton 	};
3173f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
31741da177e4SLinus Torvalds 
31759e3b2f8cSKonstantin Khlebnikov 	do {
3176c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3177b8e83b94SMel Gorman 		bool raise_priority = true;
3178b8e83b94SMel Gorman 
317984c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
31801da177e4SLinus Torvalds 
318186c79f6bSMel Gorman 		/*
318284c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
318384c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
318484c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
318584c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
318684c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
318784c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
318884c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
318984c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
319086c79f6bSMel Gorman 		 */
319186c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
319286c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
319386c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
31946aa303deSMel Gorman 				if (!managed_zone(zone))
319586c79f6bSMel Gorman 					continue;
319686c79f6bSMel Gorman 
3197970a39a3SMel Gorman 				sc.reclaim_idx = i;
319886c79f6bSMel Gorman 				break;
319986c79f6bSMel Gorman 			}
320086c79f6bSMel Gorman 		}
320186c79f6bSMel Gorman 
320286c79f6bSMel Gorman 		/*
320386c79f6bSMel Gorman 		 * Only reclaim if there are no eligible zones. Check from
320486c79f6bSMel Gorman 		 * high to low zone as allocations prefer higher zones.
320586c79f6bSMel Gorman 		 * Scanning from low to high zone would allow congestion to be
320686c79f6bSMel Gorman 		 * cleared during a very small window when a small low
320786c79f6bSMel Gorman 		 * zone was balanced even under extreme pressure when the
320884c7a777SMel Gorman 		 * overall node may be congested. Note that sc.reclaim_idx
320984c7a777SMel Gorman 		 * is not used as buffer_heads_over_limit may have adjusted
321084c7a777SMel Gorman 		 * it.
321186c79f6bSMel Gorman 		 */
321284c7a777SMel Gorman 		for (i = classzone_idx; i >= 0; i--) {
32131d82de61SMel Gorman 			zone = pgdat->node_zones + i;
32146aa303deSMel Gorman 			if (!managed_zone(zone))
32151da177e4SLinus Torvalds 				continue;
32161da177e4SLinus Torvalds 
321784c7a777SMel Gorman 			if (zone_balanced(zone, sc.order, classzone_idx))
32181da177e4SLinus Torvalds 				goto out;
321986c79f6bSMel Gorman 		}
3220e1dbeda6SAndrew Morton 
32211da177e4SLinus Torvalds 		/*
32221d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
32231d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
32241d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
32251d82de61SMel Gorman 		 * about consistent aging.
32261d82de61SMel Gorman 		 */
3227ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
32281d82de61SMel Gorman 
32291d82de61SMel Gorman 		/*
3230b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3231b7ea3c41SMel Gorman 		 * even in laptop mode.
3232b7ea3c41SMel Gorman 		 */
3233047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3234b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3235b7ea3c41SMel Gorman 
32361d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
32371da177e4SLinus Torvalds 		sc.nr_scanned = 0;
32380608f43dSAndrew Morton 		nr_soft_scanned = 0;
3239ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
32401d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
32410608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
32420608f43dSAndrew Morton 
324332a4330dSRik van Riel 		/*
32441d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
32451d82de61SMel Gorman 		 * enough pages are already being scanned that that high
32461d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
324732a4330dSRik van Riel 		 */
3248970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3249b8e83b94SMel Gorman 			raise_priority = false;
3250d7868daeSMel Gorman 
32515515061dSMel Gorman 		/*
32525515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32535515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
32545515061dSMel Gorman 		 * able to safely make forward progress. Wake them
32555515061dSMel Gorman 		 */
32565515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3257c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3258cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
32595515061dSMel Gorman 
3260b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3261b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3262b8e83b94SMel Gorman 			break;
3263b8e83b94SMel Gorman 
3264b8e83b94SMel Gorman 		/*
3265b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3266b8e83b94SMel Gorman 		 * progress in reclaiming pages
3267b8e83b94SMel Gorman 		 */
3268c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3269c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3270b8e83b94SMel Gorman 			sc.priority--;
32711d82de61SMel Gorman 	} while (sc.priority >= 1);
32721da177e4SLinus Torvalds 
3273c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3274c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3275c73322d0SJohannes Weiner 
3276b8e83b94SMel Gorman out:
32770abdee2bSMel Gorman 	/*
32781d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
32791d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
32801d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
32811d82de61SMel Gorman 	 * remain at the higher level.
32820abdee2bSMel Gorman 	 */
32831d82de61SMel Gorman 	return sc.order;
32841da177e4SLinus Torvalds }
32851da177e4SLinus Torvalds 
328638087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
328738087d9bSMel Gorman 				unsigned int classzone_idx)
3288f0bc0a60SKOSAKI Motohiro {
3289f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3290f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3291f0bc0a60SKOSAKI Motohiro 
3292f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3293f0bc0a60SKOSAKI Motohiro 		return;
3294f0bc0a60SKOSAKI Motohiro 
3295f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3296f0bc0a60SKOSAKI Motohiro 
3297f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3298d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3299fd901c95SVlastimil Babka 		/*
3300fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3301fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3302fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3303fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3304fd901c95SVlastimil Babka 		 */
3305fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3306fd901c95SVlastimil Babka 
3307fd901c95SVlastimil Babka 		/*
3308fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3309fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3310fd901c95SVlastimil Babka 		 */
331138087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3312fd901c95SVlastimil Babka 
3313f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
331438087d9bSMel Gorman 
331538087d9bSMel Gorman 		/*
331638087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
331738087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
331838087d9bSMel Gorman 		 * the previous request that slept prematurely.
331938087d9bSMel Gorman 		 */
332038087d9bSMel Gorman 		if (remaining) {
332138087d9bSMel Gorman 			pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
332238087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
332338087d9bSMel Gorman 		}
332438087d9bSMel Gorman 
3325f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3326f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3327f0bc0a60SKOSAKI Motohiro 	}
3328f0bc0a60SKOSAKI Motohiro 
3329f0bc0a60SKOSAKI Motohiro 	/*
3330f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3331f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3332f0bc0a60SKOSAKI Motohiro 	 */
3333d9f21d42SMel Gorman 	if (!remaining &&
3334d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3335f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3336f0bc0a60SKOSAKI Motohiro 
3337f0bc0a60SKOSAKI Motohiro 		/*
3338f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3339f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3340f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3341f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3342f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3343f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3344f0bc0a60SKOSAKI Motohiro 		 */
3345f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33461c7e7f6cSAaditya Kumar 
33471c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3348f0bc0a60SKOSAKI Motohiro 			schedule();
33491c7e7f6cSAaditya Kumar 
3350f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3351f0bc0a60SKOSAKI Motohiro 	} else {
3352f0bc0a60SKOSAKI Motohiro 		if (remaining)
3353f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3354f0bc0a60SKOSAKI Motohiro 		else
3355f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3356f0bc0a60SKOSAKI Motohiro 	}
3357f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3358f0bc0a60SKOSAKI Motohiro }
3359f0bc0a60SKOSAKI Motohiro 
33601da177e4SLinus Torvalds /*
33611da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
33621da177e4SLinus Torvalds  * from the init process.
33631da177e4SLinus Torvalds  *
33641da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
33651da177e4SLinus Torvalds  * free memory available even if there is no other activity
33661da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
33671da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
33681da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
33691da177e4SLinus Torvalds  *
33701da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
33711da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
33721da177e4SLinus Torvalds  */
33731da177e4SLinus Torvalds static int kswapd(void *p)
33741da177e4SLinus Torvalds {
337538087d9bSMel Gorman 	unsigned int alloc_order, reclaim_order, classzone_idx;
33761da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
33771da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3378f0bc0a60SKOSAKI Motohiro 
33791da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
33801da177e4SLinus Torvalds 		.reclaimed_slab = 0,
33811da177e4SLinus Torvalds 	};
3382a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
33831da177e4SLinus Torvalds 
3384cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3385cf40bd16SNick Piggin 
3386174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3387c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
33881da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
33891da177e4SLinus Torvalds 
33901da177e4SLinus Torvalds 	/*
33911da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
33921da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
33931da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
33941da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
33951da177e4SLinus Torvalds 	 *
33961da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
33971da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
33981da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
33991da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34001da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34011da177e4SLinus Torvalds 	 */
3402930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
340383144186SRafael J. Wysocki 	set_freezable();
34041da177e4SLinus Torvalds 
340538087d9bSMel Gorman 	pgdat->kswapd_order = alloc_order = reclaim_order = 0;
340638087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = classzone_idx = 0;
34071da177e4SLinus Torvalds 	for ( ; ; ) {
34086f6313d4SJeff Liu 		bool ret;
34093e1d1d28SChristoph Lameter 
341038087d9bSMel Gorman kswapd_try_sleep:
341138087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
341238087d9bSMel Gorman 					classzone_idx);
3413215ddd66SMel Gorman 
341438087d9bSMel Gorman 		/* Read the new order and classzone_idx */
341538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
341638087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
341738087d9bSMel Gorman 		pgdat->kswapd_order = 0;
341838087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = 0;
34191da177e4SLinus Torvalds 
34208fe23e05SDavid Rientjes 		ret = try_to_freeze();
34218fe23e05SDavid Rientjes 		if (kthread_should_stop())
34228fe23e05SDavid Rientjes 			break;
34238fe23e05SDavid Rientjes 
34248fe23e05SDavid Rientjes 		/*
34258fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34268fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3427b1296cc4SRafael J. Wysocki 		 */
342838087d9bSMel Gorman 		if (ret)
342938087d9bSMel Gorman 			continue;
34301d82de61SMel Gorman 
343138087d9bSMel Gorman 		/*
343238087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
343338087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
343438087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
343538087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
343638087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
343738087d9bSMel Gorman 		 * request (alloc_order).
343838087d9bSMel Gorman 		 */
3439e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3440e5146b12SMel Gorman 						alloc_order);
344138087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
344238087d9bSMel Gorman 		if (reclaim_order < alloc_order)
344338087d9bSMel Gorman 			goto kswapd_try_sleep;
344438087d9bSMel Gorman 
344538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
344638087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
344733906bc5SMel Gorman 	}
3448b0a8cc58STakamori Yamaguchi 
344971abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3450b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
345171abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
345271abdc15SJohannes Weiner 
34531da177e4SLinus Torvalds 	return 0;
34541da177e4SLinus Torvalds }
34551da177e4SLinus Torvalds 
34561da177e4SLinus Torvalds /*
34571da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
34581da177e4SLinus Torvalds  */
345999504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
34601da177e4SLinus Torvalds {
34611da177e4SLinus Torvalds 	pg_data_t *pgdat;
3462e1a55637SMel Gorman 	int z;
34631da177e4SLinus Torvalds 
34646aa303deSMel Gorman 	if (!managed_zone(zone))
34651da177e4SLinus Torvalds 		return;
34661da177e4SLinus Torvalds 
3467344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
34681da177e4SLinus Torvalds 		return;
346988f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
347038087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
347138087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
34728d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
34731da177e4SLinus Torvalds 		return;
3474e1a55637SMel Gorman 
3475c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3476c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3477c73322d0SJohannes Weiner 		return;
3478c73322d0SJohannes Weiner 
3479e1a55637SMel Gorman 	/* Only wake kswapd if all zones are unbalanced */
3480e1a55637SMel Gorman 	for (z = 0; z <= classzone_idx; z++) {
3481e1a55637SMel Gorman 		zone = pgdat->node_zones + z;
34826aa303deSMel Gorman 		if (!managed_zone(zone))
3483e1a55637SMel Gorman 			continue;
3484e1a55637SMel Gorman 
3485e1a55637SMel Gorman 		if (zone_balanced(zone, order, classzone_idx))
348688f5acf8SMel Gorman 			return;
3487e1a55637SMel Gorman 	}
348888f5acf8SMel Gorman 
348988f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
34908d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
34911da177e4SLinus Torvalds }
34921da177e4SLinus Torvalds 
3493c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
34941da177e4SLinus Torvalds /*
34957b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3496d6277db4SRafael J. Wysocki  * freed pages.
3497d6277db4SRafael J. Wysocki  *
3498d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3499d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3500d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35011da177e4SLinus Torvalds  */
35027b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35031da177e4SLinus Torvalds {
3504d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3505d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35067b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3507ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3508b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
35099e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3510ee814fe2SJohannes Weiner 		.may_writepage = 1,
3511ee814fe2SJohannes Weiner 		.may_unmap = 1,
3512ee814fe2SJohannes Weiner 		.may_swap = 1,
3513ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
35141da177e4SLinus Torvalds 	};
35157b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
35167b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
35177b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
35181da177e4SLinus Torvalds 
35197b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
35207b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3521d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
35227b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3523d6277db4SRafael J. Wysocki 
35243115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3525d6277db4SRafael J. Wysocki 
35267b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35277b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35287b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3529d6277db4SRafael J. Wysocki 
35307b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35311da177e4SLinus Torvalds }
3532c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35331da177e4SLinus Torvalds 
35341da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35351da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35361da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35371da177e4SLinus Torvalds    restore their cpu bindings. */
3538517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
35391da177e4SLinus Torvalds {
354058c0a4a7SYasunori Goto 	int nid;
35411da177e4SLinus Torvalds 
354248fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3543c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3544a70f7302SRusty Russell 		const struct cpumask *mask;
3545a70f7302SRusty Russell 
3546a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3547c5f59f08SMike Travis 
35483e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35491da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3550c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
35511da177e4SLinus Torvalds 	}
3552517bbed9SSebastian Andrzej Siewior 	return 0;
35531da177e4SLinus Torvalds }
35541da177e4SLinus Torvalds 
35553218ae14SYasunori Goto /*
35563218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35573218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35583218ae14SYasunori Goto  */
35593218ae14SYasunori Goto int kswapd_run(int nid)
35603218ae14SYasunori Goto {
35613218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
35623218ae14SYasunori Goto 	int ret = 0;
35633218ae14SYasunori Goto 
35643218ae14SYasunori Goto 	if (pgdat->kswapd)
35653218ae14SYasunori Goto 		return 0;
35663218ae14SYasunori Goto 
35673218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
35683218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
35693218ae14SYasunori Goto 		/* failure at boot is fatal */
35703218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3571d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3572d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3573d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
35743218ae14SYasunori Goto 	}
35753218ae14SYasunori Goto 	return ret;
35763218ae14SYasunori Goto }
35773218ae14SYasunori Goto 
35788fe23e05SDavid Rientjes /*
3579d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3580bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
35818fe23e05SDavid Rientjes  */
35828fe23e05SDavid Rientjes void kswapd_stop(int nid)
35838fe23e05SDavid Rientjes {
35848fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
35858fe23e05SDavid Rientjes 
3586d8adde17SJiang Liu 	if (kswapd) {
35878fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3588d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3589d8adde17SJiang Liu 	}
35908fe23e05SDavid Rientjes }
35918fe23e05SDavid Rientjes 
35921da177e4SLinus Torvalds static int __init kswapd_init(void)
35931da177e4SLinus Torvalds {
3594517bbed9SSebastian Andrzej Siewior 	int nid, ret;
359569e05944SAndrew Morton 
35961da177e4SLinus Torvalds 	swap_setup();
359748fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
35983218ae14SYasunori Goto  		kswapd_run(nid);
3599517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3600517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3601517bbed9SSebastian Andrzej Siewior 					NULL);
3602517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
36031da177e4SLinus Torvalds 	return 0;
36041da177e4SLinus Torvalds }
36051da177e4SLinus Torvalds 
36061da177e4SLinus Torvalds module_init(kswapd_init)
36079eeff239SChristoph Lameter 
36089eeff239SChristoph Lameter #ifdef CONFIG_NUMA
36099eeff239SChristoph Lameter /*
3610a5f5f91dSMel Gorman  * Node reclaim mode
36119eeff239SChristoph Lameter  *
3612a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
36139eeff239SChristoph Lameter  * the watermarks.
36149eeff239SChristoph Lameter  */
3615a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
36169eeff239SChristoph Lameter 
36171b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
36187d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
36191b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
362095bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
36211b2ffb78SChristoph Lameter 
36229eeff239SChristoph Lameter /*
3623a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3624a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3625a92f7126SChristoph Lameter  * a zone.
3626a92f7126SChristoph Lameter  */
3627a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3628a92f7126SChristoph Lameter 
36299eeff239SChristoph Lameter /*
3630a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
36319614634fSChristoph Lameter  * occur.
36329614634fSChristoph Lameter  */
36339614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36349614634fSChristoph Lameter 
36359614634fSChristoph Lameter /*
36360ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36370ff38490SChristoph Lameter  * slab reclaim needs to occur.
36380ff38490SChristoph Lameter  */
36390ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36400ff38490SChristoph Lameter 
364111fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
364290afa5deSMel Gorman {
364311fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
364411fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
364511fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
364690afa5deSMel Gorman 
364790afa5deSMel Gorman 	/*
364890afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
364990afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
365090afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
365190afa5deSMel Gorman 	 */
365290afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
365390afa5deSMel Gorman }
365490afa5deSMel Gorman 
365590afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3656a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
365790afa5deSMel Gorman {
3658d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3659d031a157SAlexandru Moise 	unsigned long delta = 0;
366090afa5deSMel Gorman 
366190afa5deSMel Gorman 	/*
366295bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
366390afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
366411fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
366590afa5deSMel Gorman 	 * a better estimate
366690afa5deSMel Gorman 	 */
3667a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3668a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
366990afa5deSMel Gorman 	else
3670a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
367190afa5deSMel Gorman 
367290afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3673a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3674a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
367590afa5deSMel Gorman 
367690afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
367790afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
367890afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
367990afa5deSMel Gorman 
368090afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
368190afa5deSMel Gorman }
368290afa5deSMel Gorman 
36830ff38490SChristoph Lameter /*
3684a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
36859eeff239SChristoph Lameter  */
3686a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
36879eeff239SChristoph Lameter {
36887fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
368969e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
36909eeff239SChristoph Lameter 	struct task_struct *p = current;
36919eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3692a5f5f91dSMel Gorman 	int classzone_idx = gfp_zone(gfp_mask);
3693179e9639SAndrew Morton 	struct scan_control sc = {
369462b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
369521caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3696bd2f6199SJohannes Weiner 		.order = order,
3697a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3698a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3699a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3700ee814fe2SJohannes Weiner 		.may_swap = 1,
3701a5f5f91dSMel Gorman 		.reclaim_idx = classzone_idx,
3702179e9639SAndrew Morton 	};
37039eeff239SChristoph Lameter 
37049eeff239SChristoph Lameter 	cond_resched();
3705d4f7796eSChristoph Lameter 	/*
370695bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3707d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
370895bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3709d4f7796eSChristoph Lameter 	 */
3710d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
371176ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
37129eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
37139eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3714c84db23cSChristoph Lameter 
3715a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3716a92f7126SChristoph Lameter 		/*
37170ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
37180ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3719a92f7126SChristoph Lameter 		 */
3720a92f7126SChristoph Lameter 		do {
3721970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
37229e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
37230ff38490SChristoph Lameter 	}
3724a92f7126SChristoph Lameter 
37259eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3726d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
372776ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3728a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37299eeff239SChristoph Lameter }
3730179e9639SAndrew Morton 
3731a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3732179e9639SAndrew Morton {
3733d773ed6bSDavid Rientjes 	int ret;
3734179e9639SAndrew Morton 
3735179e9639SAndrew Morton 	/*
3736a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
37370ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
373834aa1330SChristoph Lameter 	 *
37399614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37409614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3741a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3742a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
37439614634fSChristoph Lameter 	 * unmapped file backed pages.
3744179e9639SAndrew Morton 	 */
3745a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3746a5f5f91dSMel Gorman 	    sum_zone_node_page_state(pgdat->node_id, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3747a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3748179e9639SAndrew Morton 
3749179e9639SAndrew Morton 	/*
3750d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3751179e9639SAndrew Morton 	 */
3752d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3753a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3754179e9639SAndrew Morton 
3755179e9639SAndrew Morton 	/*
3756a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3757179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3758179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3759179e9639SAndrew Morton 	 * as wide as possible.
3760179e9639SAndrew Morton 	 */
3761a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3762a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3763d773ed6bSDavid Rientjes 
3764a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3765a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3766fa5e084eSMel Gorman 
3767a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3768a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3769d773ed6bSDavid Rientjes 
377024cf7251SMel Gorman 	if (!ret)
377124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
377224cf7251SMel Gorman 
3773d773ed6bSDavid Rientjes 	return ret;
3774179e9639SAndrew Morton }
37759eeff239SChristoph Lameter #endif
3776894bc310SLee Schermerhorn 
3777894bc310SLee Schermerhorn /*
3778894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3779894bc310SLee Schermerhorn  * @page: the page to test
3780894bc310SLee Schermerhorn  *
3781894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
378239b5f29aSHugh Dickins  * lists vs unevictable list.
3783894bc310SLee Schermerhorn  *
3784894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3785ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3786b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3787ba9ddf49SLee Schermerhorn  *
3788894bc310SLee Schermerhorn  */
378939b5f29aSHugh Dickins int page_evictable(struct page *page)
3790894bc310SLee Schermerhorn {
379139b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3792894bc310SLee Schermerhorn }
379389e004eaSLee Schermerhorn 
379485046579SHugh Dickins #ifdef CONFIG_SHMEM
379589e004eaSLee Schermerhorn /**
379624513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
379724513264SHugh Dickins  * @pages:	array of pages to check
379824513264SHugh Dickins  * @nr_pages:	number of pages to check
379989e004eaSLee Schermerhorn  *
380024513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
380185046579SHugh Dickins  *
380285046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
380389e004eaSLee Schermerhorn  */
380424513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
380589e004eaSLee Schermerhorn {
3806925b7673SJohannes Weiner 	struct lruvec *lruvec;
3807785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
380824513264SHugh Dickins 	int pgscanned = 0;
380924513264SHugh Dickins 	int pgrescued = 0;
381089e004eaSLee Schermerhorn 	int i;
381189e004eaSLee Schermerhorn 
381224513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
381324513264SHugh Dickins 		struct page *page = pages[i];
3814785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
381589e004eaSLee Schermerhorn 
381624513264SHugh Dickins 		pgscanned++;
3817785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3818785b99feSMel Gorman 			if (pgdat)
3819785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3820785b99feSMel Gorman 			pgdat = pagepgdat;
3821785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
382289e004eaSLee Schermerhorn 		}
3823785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
382489e004eaSLee Schermerhorn 
382524513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
382624513264SHugh Dickins 			continue;
382789e004eaSLee Schermerhorn 
382839b5f29aSHugh Dickins 		if (page_evictable(page)) {
382924513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
383024513264SHugh Dickins 
3831309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
383224513264SHugh Dickins 			ClearPageUnevictable(page);
3833fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3834fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
383524513264SHugh Dickins 			pgrescued++;
383689e004eaSLee Schermerhorn 		}
383789e004eaSLee Schermerhorn 	}
383824513264SHugh Dickins 
3839785b99feSMel Gorman 	if (pgdat) {
384024513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
384124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3842785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
384324513264SHugh Dickins 	}
384485046579SHugh Dickins }
384585046579SHugh Dickins #endif /* CONFIG_SHMEM */
3846