xref: /openbmc/linux/mm/vmscan.c (revision 385386cff4c6f047907655e05791d88198c4c523)
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 
100d6622f63SYisheng Xie 	/*
101d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
102d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
103d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
104d6622f63SYisheng Xie 	 */
105d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
106d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
107241994edSJohannes Weiner 
108ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
109ee814fe2SJohannes Weiner 
110ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
111ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
112ee814fe2SJohannes Weiner 
113ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
114ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
115ee814fe2SJohannes Weiner 
116ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
117ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1181da177e4SLinus Torvalds };
1191da177e4SLinus Torvalds 
1201da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1211da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1221da177e4SLinus Torvalds 	do {								\
1231da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1241da177e4SLinus Torvalds 			struct page *prev;				\
1251da177e4SLinus Torvalds 									\
1261da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1271da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1281da177e4SLinus Torvalds 		}							\
1291da177e4SLinus Torvalds 	} while (0)
1301da177e4SLinus Torvalds #else
1311da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1321da177e4SLinus Torvalds #endif
1331da177e4SLinus Torvalds 
1341da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1351da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1361da177e4SLinus Torvalds 	do {								\
1371da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1381da177e4SLinus Torvalds 			struct page *prev;				\
1391da177e4SLinus Torvalds 									\
1401da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1411da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1421da177e4SLinus Torvalds 		}							\
1431da177e4SLinus Torvalds 	} while (0)
1441da177e4SLinus Torvalds #else
1451da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1461da177e4SLinus Torvalds #endif
1471da177e4SLinus Torvalds 
1481da177e4SLinus Torvalds /*
1491da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1501da177e4SLinus Torvalds  */
1511da177e4SLinus Torvalds int vm_swappiness = 60;
152d0480be4SWang Sheng-Hui /*
153d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
154d0480be4SWang Sheng-Hui  * zones.
155d0480be4SWang Sheng-Hui  */
156d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1571da177e4SLinus Torvalds 
1581da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1591da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1601da177e4SLinus Torvalds 
161c255a458SAndrew Morton #ifdef CONFIG_MEMCG
16289b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
16389b5fae5SJohannes Weiner {
164f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
16589b5fae5SJohannes Weiner }
16697c9341fSTejun Heo 
16797c9341fSTejun Heo /**
16897c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
16997c9341fSTejun Heo  * @sc: scan_control in question
17097c9341fSTejun Heo  *
17197c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
17297c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
17397c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
17497c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
17597c9341fSTejun Heo  * allocation and configurability.
17697c9341fSTejun Heo  *
17797c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
17897c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
17997c9341fSTejun Heo  */
18097c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
18197c9341fSTejun Heo {
18297c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
18397c9341fSTejun Heo 
18497c9341fSTejun Heo 	if (!memcg)
18597c9341fSTejun Heo 		return true;
18697c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
18769234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
18897c9341fSTejun Heo 		return true;
18997c9341fSTejun Heo #endif
19097c9341fSTejun Heo 	return false;
19197c9341fSTejun Heo }
19291a45470SKAMEZAWA Hiroyuki #else
19389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
19489b5fae5SJohannes Weiner {
19589b5fae5SJohannes Weiner 	return true;
19689b5fae5SJohannes Weiner }
19797c9341fSTejun Heo 
19897c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19997c9341fSTejun Heo {
20097c9341fSTejun Heo 	return true;
20197c9341fSTejun Heo }
20291a45470SKAMEZAWA Hiroyuki #endif
20391a45470SKAMEZAWA Hiroyuki 
2045a1c84b4SMel Gorman /*
2055a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2065a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2075a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2085a1c84b4SMel Gorman  */
2095a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2105a1c84b4SMel Gorman {
2115a1c84b4SMel Gorman 	unsigned long nr;
2125a1c84b4SMel Gorman 
2135a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2145a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2155a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2165a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2175a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2185a1c84b4SMel Gorman 
2195a1c84b4SMel Gorman 	return nr;
2205a1c84b4SMel Gorman }
2215a1c84b4SMel Gorman 
222599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2236e543d57SLisa Du {
224599d0c95SMel Gorman 	unsigned long nr;
225599d0c95SMel Gorman 
226599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
227599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
228599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
229599d0c95SMel Gorman 
230599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
231599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
232599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
233599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
234599d0c95SMel Gorman 
235599d0c95SMel Gorman 	return nr;
236599d0c95SMel Gorman }
237599d0c95SMel Gorman 
238fd538803SMichal Hocko /**
239fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
240fd538803SMichal Hocko  * @lruvec: lru vector
241fd538803SMichal Hocko  * @lru: lru to use
242fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
243fd538803SMichal Hocko  */
244fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
245c9f299d9SKOSAKI Motohiro {
246fd538803SMichal Hocko 	unsigned long lru_size;
247fd538803SMichal Hocko 	int zid;
248a3d8e054SKOSAKI Motohiro 
249fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
250fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
251fd538803SMichal Hocko 	else
252fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
253fd538803SMichal Hocko 
254fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
255fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
256fd538803SMichal Hocko 		unsigned long size;
257fd538803SMichal Hocko 
258fd538803SMichal Hocko 		if (!managed_zone(zone))
259fd538803SMichal Hocko 			continue;
260fd538803SMichal Hocko 
261fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
262fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
263fd538803SMichal Hocko 		else
264fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
265fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
266fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
267c9f299d9SKOSAKI Motohiro 	}
268c9f299d9SKOSAKI Motohiro 
269fd538803SMichal Hocko 	return lru_size;
270b4536f0cSMichal Hocko 
271b4536f0cSMichal Hocko }
272b4536f0cSMichal Hocko 
2731da177e4SLinus Torvalds /*
2741d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2751da177e4SLinus Torvalds  */
2761d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2771da177e4SLinus Torvalds {
2781d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2791d3d4437SGlauber Costa 
2801d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2811d3d4437SGlauber Costa 		size *= nr_node_ids;
2821d3d4437SGlauber Costa 
2831d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2841d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2851d3d4437SGlauber Costa 		return -ENOMEM;
2861d3d4437SGlauber Costa 
2871da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2881da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2891da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2901d3d4437SGlauber Costa 	return 0;
2911da177e4SLinus Torvalds }
2928e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2931da177e4SLinus Torvalds 
2941da177e4SLinus Torvalds /*
2951da177e4SLinus Torvalds  * Remove one
2961da177e4SLinus Torvalds  */
2978e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2981da177e4SLinus Torvalds {
2991da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3001da177e4SLinus Torvalds 	list_del(&shrinker->list);
3011da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
302ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
3031da177e4SLinus Torvalds }
3048e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
3051da177e4SLinus Torvalds 
3061da177e4SLinus Torvalds #define SHRINK_BATCH 128
3071d3d4437SGlauber Costa 
308cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
3096b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
3106b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
3116b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
3121da177e4SLinus Torvalds {
31324f7c6b9SDave Chinner 	unsigned long freed = 0;
3141da177e4SLinus Torvalds 	unsigned long long delta;
315635697c6SKonstantin Khlebnikov 	long total_scan;
316d5bc5fd3SVladimir Davydov 	long freeable;
317acf92b48SDave Chinner 	long nr;
318acf92b48SDave Chinner 	long new_nr;
3191d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
320e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
321e9299f50SDave Chinner 					  : SHRINK_BATCH;
3225f33a080SShaohua Li 	long scanned = 0, next_deferred;
3231da177e4SLinus Torvalds 
324d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
325d5bc5fd3SVladimir Davydov 	if (freeable == 0)
3261d3d4437SGlauber Costa 		return 0;
327635697c6SKonstantin Khlebnikov 
328acf92b48SDave Chinner 	/*
329acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
330acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
331acf92b48SDave Chinner 	 * don't also do this scanning work.
332acf92b48SDave Chinner 	 */
3331d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
334acf92b48SDave Chinner 
335acf92b48SDave Chinner 	total_scan = nr;
3366b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
337d5bc5fd3SVladimir Davydov 	delta *= freeable;
3386b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
339acf92b48SDave Chinner 	total_scan += delta;
340acf92b48SDave Chinner 	if (total_scan < 0) {
3418612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
342a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
343d5bc5fd3SVladimir Davydov 		total_scan = freeable;
3445f33a080SShaohua Li 		next_deferred = nr;
3455f33a080SShaohua Li 	} else
3465f33a080SShaohua Li 		next_deferred = total_scan;
347ea164d73SAndrea Arcangeli 
348ea164d73SAndrea Arcangeli 	/*
3493567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3503567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3513567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3523567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3533567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
354d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3553567b59aSDave Chinner 	 * memory.
3563567b59aSDave Chinner 	 *
3573567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3583567b59aSDave Chinner 	 * a large delta change is calculated directly.
3593567b59aSDave Chinner 	 */
360d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
361d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3623567b59aSDave Chinner 
3633567b59aSDave Chinner 	/*
364ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
365ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
366ea164d73SAndrea Arcangeli 	 * freeable entries.
367ea164d73SAndrea Arcangeli 	 */
368d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
369d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3701da177e4SLinus Torvalds 
37124f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3726b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
373d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
37409576073SDave Chinner 
3750b1fb40aSVladimir Davydov 	/*
3760b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3770b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3780b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3790b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3800b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3810b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3820b1fb40aSVladimir Davydov 	 * batch_size.
3830b1fb40aSVladimir Davydov 	 *
3840b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3850b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
386d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3870b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3880b1fb40aSVladimir Davydov 	 * possible.
3890b1fb40aSVladimir Davydov 	 */
3900b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
391d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
39224f7c6b9SDave Chinner 		unsigned long ret;
3930b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3941da177e4SLinus Torvalds 
3950b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
39624f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
39724f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3981da177e4SLinus Torvalds 			break;
39924f7c6b9SDave Chinner 		freed += ret;
40024f7c6b9SDave Chinner 
4010b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
4020b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
4035f33a080SShaohua Li 		scanned += nr_to_scan;
4041da177e4SLinus Torvalds 
4051da177e4SLinus Torvalds 		cond_resched();
4061da177e4SLinus Torvalds 	}
4071da177e4SLinus Torvalds 
4085f33a080SShaohua Li 	if (next_deferred >= scanned)
4095f33a080SShaohua Li 		next_deferred -= scanned;
4105f33a080SShaohua Li 	else
4115f33a080SShaohua Li 		next_deferred = 0;
412acf92b48SDave Chinner 	/*
413acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
414acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
415acf92b48SDave Chinner 	 * scan, there is no need to do an update.
416acf92b48SDave Chinner 	 */
4175f33a080SShaohua Li 	if (next_deferred > 0)
4185f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
4191d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
42083aeeadaSKonstantin Khlebnikov 	else
4211d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
422acf92b48SDave Chinner 
423df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
4241d3d4437SGlauber Costa 	return freed;
4251d3d4437SGlauber Costa }
4261d3d4437SGlauber Costa 
4276b4f7799SJohannes Weiner /**
428cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
4296b4f7799SJohannes Weiner  * @gfp_mask: allocation context
4306b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
431cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
4326b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
4336b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
4341d3d4437SGlauber Costa  *
4356b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4361d3d4437SGlauber Costa  *
4376b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4386b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4391d3d4437SGlauber Costa  *
440cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
441cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4420fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4430fc9f58aSVladimir Davydov  * shrinkers are called.
444cb731d6cSVladimir Davydov  *
4456b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4466b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4476b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4486b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4496b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4506b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4516b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4521d3d4437SGlauber Costa  *
4536b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4541d3d4437SGlauber Costa  */
455cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
456cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4576b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4586b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4591d3d4437SGlauber Costa {
4601d3d4437SGlauber Costa 	struct shrinker *shrinker;
4611d3d4437SGlauber Costa 	unsigned long freed = 0;
4621d3d4437SGlauber Costa 
4630fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
464cb731d6cSVladimir Davydov 		return 0;
465cb731d6cSVladimir Davydov 
4666b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4676b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4681d3d4437SGlauber Costa 
4691d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4701d3d4437SGlauber Costa 		/*
4711d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4721d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4731d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4741d3d4437SGlauber Costa 		 * time.
4751d3d4437SGlauber Costa 		 */
4761d3d4437SGlauber Costa 		freed = 1;
4771d3d4437SGlauber Costa 		goto out;
4781d3d4437SGlauber Costa 	}
4791d3d4437SGlauber Costa 
4801d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4816b4f7799SJohannes Weiner 		struct shrink_control sc = {
4826b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4836b4f7799SJohannes Weiner 			.nid = nid,
484cb731d6cSVladimir Davydov 			.memcg = memcg,
4856b4f7799SJohannes Weiner 		};
4866b4f7799SJohannes Weiner 
4870fc9f58aSVladimir Davydov 		/*
4880fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4890fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4900fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4910fc9f58aSVladimir Davydov 		 */
4920fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4930fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
494cb731d6cSVladimir Davydov 			continue;
495cb731d6cSVladimir Davydov 
4966b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4976b4f7799SJohannes Weiner 			sc.nid = 0;
4986b4f7799SJohannes Weiner 
499cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
500ec97097bSVladimir Davydov 	}
5011d3d4437SGlauber Costa 
5021da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
503f06590bdSMinchan Kim out:
504f06590bdSMinchan Kim 	cond_resched();
50524f7c6b9SDave Chinner 	return freed;
5061da177e4SLinus Torvalds }
5071da177e4SLinus Torvalds 
508cb731d6cSVladimir Davydov void drop_slab_node(int nid)
509cb731d6cSVladimir Davydov {
510cb731d6cSVladimir Davydov 	unsigned long freed;
511cb731d6cSVladimir Davydov 
512cb731d6cSVladimir Davydov 	do {
513cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
514cb731d6cSVladimir Davydov 
515cb731d6cSVladimir Davydov 		freed = 0;
516cb731d6cSVladimir Davydov 		do {
517cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
518cb731d6cSVladimir Davydov 					     1000, 1000);
519cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
520cb731d6cSVladimir Davydov 	} while (freed > 10);
521cb731d6cSVladimir Davydov }
522cb731d6cSVladimir Davydov 
523cb731d6cSVladimir Davydov void drop_slab(void)
524cb731d6cSVladimir Davydov {
525cb731d6cSVladimir Davydov 	int nid;
526cb731d6cSVladimir Davydov 
527cb731d6cSVladimir Davydov 	for_each_online_node(nid)
528cb731d6cSVladimir Davydov 		drop_slab_node(nid);
529cb731d6cSVladimir Davydov }
530cb731d6cSVladimir Davydov 
5311da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5321da177e4SLinus Torvalds {
533ceddc3a5SJohannes Weiner 	/*
534ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
535ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
536ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
537ceddc3a5SJohannes Weiner 	 */
538edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5391da177e4SLinus Torvalds }
5401da177e4SLinus Torvalds 
541703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5421da177e4SLinus Torvalds {
543930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5441da177e4SLinus Torvalds 		return 1;
545703c2708STejun Heo 	if (!inode_write_congested(inode))
5461da177e4SLinus Torvalds 		return 1;
547703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5481da177e4SLinus Torvalds 		return 1;
5491da177e4SLinus Torvalds 	return 0;
5501da177e4SLinus Torvalds }
5511da177e4SLinus Torvalds 
5521da177e4SLinus Torvalds /*
5531da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5541da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5551da177e4SLinus Torvalds  * fsync(), msync() or close().
5561da177e4SLinus Torvalds  *
5571da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5581da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5591da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5601da177e4SLinus Torvalds  *
5611da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5621da177e4SLinus Torvalds  * __GFP_FS.
5631da177e4SLinus Torvalds  */
5641da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5651da177e4SLinus Torvalds 				struct page *page, int error)
5661da177e4SLinus Torvalds {
5677eaceaccSJens Axboe 	lock_page(page);
5683e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5693e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5701da177e4SLinus Torvalds 	unlock_page(page);
5711da177e4SLinus Torvalds }
5721da177e4SLinus Torvalds 
57304e62a29SChristoph Lameter /* possible outcome of pageout() */
57404e62a29SChristoph Lameter typedef enum {
57504e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
57604e62a29SChristoph Lameter 	PAGE_KEEP,
57704e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
57804e62a29SChristoph Lameter 	PAGE_ACTIVATE,
57904e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
58004e62a29SChristoph Lameter 	PAGE_SUCCESS,
58104e62a29SChristoph Lameter 	/* page is clean and locked */
58204e62a29SChristoph Lameter 	PAGE_CLEAN,
58304e62a29SChristoph Lameter } pageout_t;
58404e62a29SChristoph Lameter 
5851da177e4SLinus Torvalds /*
5861742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5871742f19fSAndrew Morton  * Calls ->writepage().
5881da177e4SLinus Torvalds  */
589c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5907d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5911da177e4SLinus Torvalds {
5921da177e4SLinus Torvalds 	/*
5931da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5941da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5951da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5961da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5971da177e4SLinus Torvalds 	 * PagePrivate for that.
5981da177e4SLinus Torvalds 	 *
5998174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
6001da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
6011da177e4SLinus Torvalds 	 * will block.
6021da177e4SLinus Torvalds 	 *
6031da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
6041da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
6051da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
6061da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
6071da177e4SLinus Torvalds 	 */
6081da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
6091da177e4SLinus Torvalds 		return PAGE_KEEP;
6101da177e4SLinus Torvalds 	if (!mapping) {
6111da177e4SLinus Torvalds 		/*
6121da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
6131da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
6141da177e4SLinus Torvalds 		 */
615266cf658SDavid Howells 		if (page_has_private(page)) {
6161da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
6171da177e4SLinus Torvalds 				ClearPageDirty(page);
618b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
6191da177e4SLinus Torvalds 				return PAGE_CLEAN;
6201da177e4SLinus Torvalds 			}
6211da177e4SLinus Torvalds 		}
6221da177e4SLinus Torvalds 		return PAGE_KEEP;
6231da177e4SLinus Torvalds 	}
6241da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6251da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
626703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6271da177e4SLinus Torvalds 		return PAGE_KEEP;
6281da177e4SLinus Torvalds 
6291da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6301da177e4SLinus Torvalds 		int res;
6311da177e4SLinus Torvalds 		struct writeback_control wbc = {
6321da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6331da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
634111ebb6eSOGAWA Hirofumi 			.range_start = 0,
635111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6361da177e4SLinus Torvalds 			.for_reclaim = 1,
6371da177e4SLinus Torvalds 		};
6381da177e4SLinus Torvalds 
6391da177e4SLinus Torvalds 		SetPageReclaim(page);
6401da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6411da177e4SLinus Torvalds 		if (res < 0)
6421da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
643994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6441da177e4SLinus Torvalds 			ClearPageReclaim(page);
6451da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6461da177e4SLinus Torvalds 		}
647c661b078SAndy Whitcroft 
6481da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6491da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6501da177e4SLinus Torvalds 			ClearPageReclaim(page);
6511da177e4SLinus Torvalds 		}
6523aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
653c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6541da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6551da177e4SLinus Torvalds 	}
6561da177e4SLinus Torvalds 
6571da177e4SLinus Torvalds 	return PAGE_CLEAN;
6581da177e4SLinus Torvalds }
6591da177e4SLinus Torvalds 
660a649fd92SAndrew Morton /*
661e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
662e286781dSNick Piggin  * gets returned with a refcount of 0.
663a649fd92SAndrew Morton  */
664a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
665a528910eSJohannes Weiner 			    bool reclaimed)
66649d2e9ccSChristoph Lameter {
667c4843a75SGreg Thelen 	unsigned long flags;
668c4843a75SGreg Thelen 
66928e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
67028e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
67149d2e9ccSChristoph Lameter 
672c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
67349d2e9ccSChristoph Lameter 	/*
6740fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6750fd0e6b0SNick Piggin 	 *
6760fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6770fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6780fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6790fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6800fd0e6b0SNick Piggin 	 *
6810fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6820fd0e6b0SNick Piggin 	 * [user mapping goes away]
6830fd0e6b0SNick Piggin 	 * write_to(page);
6840fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6850fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6860fd0e6b0SNick Piggin 	 * put_page(page);
6870fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6880fd0e6b0SNick Piggin 	 *
6890fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6900fd0e6b0SNick Piggin 	 *
6910fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6920fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6930139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6940fd0e6b0SNick Piggin 	 *
6950fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6960fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
69749d2e9ccSChristoph Lameter 	 */
698fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
69949d2e9ccSChristoph Lameter 		goto cannot_free;
700e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
701e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
702fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
70349d2e9ccSChristoph Lameter 		goto cannot_free;
704e286781dSNick Piggin 	}
70549d2e9ccSChristoph Lameter 
70649d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
70749d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
7080a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
70949d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
710c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
71175f6d6d2SMinchan Kim 		put_swap_page(page, swap);
712e286781dSNick Piggin 	} else {
7136072d13cSLinus Torvalds 		void (*freepage)(struct page *);
714a528910eSJohannes Weiner 		void *shadow = NULL;
7156072d13cSLinus Torvalds 
7166072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
717a528910eSJohannes Weiner 		/*
718a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
719a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
720a528910eSJohannes Weiner 		 *
721a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
722a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
723a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
724a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
725a528910eSJohannes Weiner 		 * back.
726f9fe48beSRoss Zwisler 		 *
727f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
728f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
729f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
730f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
731f9fe48beSRoss Zwisler 		 * same page_tree.
732a528910eSJohannes Weiner 		 */
733a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
734f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
735a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
73662cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
737c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7386072d13cSLinus Torvalds 
7396072d13cSLinus Torvalds 		if (freepage != NULL)
7406072d13cSLinus Torvalds 			freepage(page);
741e286781dSNick Piggin 	}
742e286781dSNick Piggin 
74349d2e9ccSChristoph Lameter 	return 1;
74449d2e9ccSChristoph Lameter 
74549d2e9ccSChristoph Lameter cannot_free:
746c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
74749d2e9ccSChristoph Lameter 	return 0;
74849d2e9ccSChristoph Lameter }
74949d2e9ccSChristoph Lameter 
7501da177e4SLinus Torvalds /*
751e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
752e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
753e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
754e286781dSNick Piggin  * this page.
755e286781dSNick Piggin  */
756e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
757e286781dSNick Piggin {
758a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
759e286781dSNick Piggin 		/*
760e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
761e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
762e286781dSNick Piggin 		 * atomic operation.
763e286781dSNick Piggin 		 */
764fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
765e286781dSNick Piggin 		return 1;
766e286781dSNick Piggin 	}
767e286781dSNick Piggin 	return 0;
768e286781dSNick Piggin }
769e286781dSNick Piggin 
770894bc310SLee Schermerhorn /**
771894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
772894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
773894bc310SLee Schermerhorn  *
774894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
775894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
776894bc310SLee Schermerhorn  *
777894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
778894bc310SLee Schermerhorn  */
779894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
780894bc310SLee Schermerhorn {
7810ec3b74cSVlastimil Babka 	bool is_unevictable;
782bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
783894bc310SLee Schermerhorn 
784309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
785894bc310SLee Schermerhorn 
786894bc310SLee Schermerhorn redo:
787894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
788894bc310SLee Schermerhorn 
78939b5f29aSHugh Dickins 	if (page_evictable(page)) {
790894bc310SLee Schermerhorn 		/*
791894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
792894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
793894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
794894bc310SLee Schermerhorn 		 * We know how to handle that.
795894bc310SLee Schermerhorn 		 */
7960ec3b74cSVlastimil Babka 		is_unevictable = false;
797c53954a0SMel Gorman 		lru_cache_add(page);
798894bc310SLee Schermerhorn 	} else {
799894bc310SLee Schermerhorn 		/*
800894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
801894bc310SLee Schermerhorn 		 * list.
802894bc310SLee Schermerhorn 		 */
8030ec3b74cSVlastimil Babka 		is_unevictable = true;
804894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
8056a7b9548SJohannes Weiner 		/*
80621ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
80721ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
80821ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
80924513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
81021ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
8116a7b9548SJohannes Weiner 		 * the page back to the evictable list.
8126a7b9548SJohannes Weiner 		 *
81321ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
8146a7b9548SJohannes Weiner 		 */
8156a7b9548SJohannes Weiner 		smp_mb();
816894bc310SLee Schermerhorn 	}
817894bc310SLee Schermerhorn 
818894bc310SLee Schermerhorn 	/*
819894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
820894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
821894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
822894bc310SLee Schermerhorn 	 */
8230ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
824894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
825894bc310SLee Schermerhorn 			put_page(page);
826894bc310SLee Schermerhorn 			goto redo;
827894bc310SLee Schermerhorn 		}
828894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
829894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
830894bc310SLee Schermerhorn 		 * nothing to do here.
831894bc310SLee Schermerhorn 		 */
832894bc310SLee Schermerhorn 	}
833894bc310SLee Schermerhorn 
8340ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
835bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8360ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
837bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
838bbfd28eeSLee Schermerhorn 
839894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
840894bc310SLee Schermerhorn }
841894bc310SLee Schermerhorn 
842dfc8d636SJohannes Weiner enum page_references {
843dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
844dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
84564574746SJohannes Weiner 	PAGEREF_KEEP,
846dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
847dfc8d636SJohannes Weiner };
848dfc8d636SJohannes Weiner 
849dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
850dfc8d636SJohannes Weiner 						  struct scan_control *sc)
851dfc8d636SJohannes Weiner {
85264574746SJohannes Weiner 	int referenced_ptes, referenced_page;
853dfc8d636SJohannes Weiner 	unsigned long vm_flags;
854dfc8d636SJohannes Weiner 
855c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
856c3ac9a8aSJohannes Weiner 					  &vm_flags);
85764574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
858dfc8d636SJohannes Weiner 
859dfc8d636SJohannes Weiner 	/*
860dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
861dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
862dfc8d636SJohannes Weiner 	 */
863dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
864dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
865dfc8d636SJohannes Weiner 
86664574746SJohannes Weiner 	if (referenced_ptes) {
867e4898273SMichal Hocko 		if (PageSwapBacked(page))
86864574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
86964574746SJohannes Weiner 		/*
87064574746SJohannes Weiner 		 * All mapped pages start out with page table
87164574746SJohannes Weiner 		 * references from the instantiating fault, so we need
87264574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
87364574746SJohannes Weiner 		 * than once.
87464574746SJohannes Weiner 		 *
87564574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
87664574746SJohannes Weiner 		 * inactive list.  Another page table reference will
87764574746SJohannes Weiner 		 * lead to its activation.
87864574746SJohannes Weiner 		 *
87964574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
88064574746SJohannes Weiner 		 * so that recently deactivated but used pages are
88164574746SJohannes Weiner 		 * quickly recovered.
88264574746SJohannes Weiner 		 */
88364574746SJohannes Weiner 		SetPageReferenced(page);
88464574746SJohannes Weiner 
88534dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
886dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
887dfc8d636SJohannes Weiner 
888c909e993SKonstantin Khlebnikov 		/*
889c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
890c909e993SKonstantin Khlebnikov 		 */
891c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
892c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
893c909e993SKonstantin Khlebnikov 
89464574746SJohannes Weiner 		return PAGEREF_KEEP;
89564574746SJohannes Weiner 	}
89664574746SJohannes Weiner 
897dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8982e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
899dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
90064574746SJohannes Weiner 
90164574746SJohannes Weiner 	return PAGEREF_RECLAIM;
902dfc8d636SJohannes Weiner }
903dfc8d636SJohannes Weiner 
904e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
905e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
906e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
907e2be15f6SMel Gorman {
908b4597226SMel Gorman 	struct address_space *mapping;
909b4597226SMel Gorman 
910e2be15f6SMel Gorman 	/*
911e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
912e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
913e2be15f6SMel Gorman 	 */
914802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
915802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
916e2be15f6SMel Gorman 		*dirty = false;
917e2be15f6SMel Gorman 		*writeback = false;
918e2be15f6SMel Gorman 		return;
919e2be15f6SMel Gorman 	}
920e2be15f6SMel Gorman 
921e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
922e2be15f6SMel Gorman 	*dirty = PageDirty(page);
923e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
924b4597226SMel Gorman 
925b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
926b4597226SMel Gorman 	if (!page_has_private(page))
927b4597226SMel Gorman 		return;
928b4597226SMel Gorman 
929b4597226SMel Gorman 	mapping = page_mapping(page);
930b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
931b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
932e2be15f6SMel Gorman }
933e2be15f6SMel Gorman 
9343c710c1aSMichal Hocko struct reclaim_stat {
9353c710c1aSMichal Hocko 	unsigned nr_dirty;
9363c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty;
9373c710c1aSMichal Hocko 	unsigned nr_congested;
9383c710c1aSMichal Hocko 	unsigned nr_writeback;
9393c710c1aSMichal Hocko 	unsigned nr_immediate;
9405bccd166SMichal Hocko 	unsigned nr_activate;
9415bccd166SMichal Hocko 	unsigned nr_ref_keep;
9425bccd166SMichal Hocko 	unsigned nr_unmap_fail;
9433c710c1aSMichal Hocko };
9443c710c1aSMichal Hocko 
945e286781dSNick Piggin /*
9461742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
9471da177e4SLinus Torvalds  */
9481742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
949599d0c95SMel Gorman 				      struct pglist_data *pgdat,
950f84f6e2bSMel Gorman 				      struct scan_control *sc,
95102c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9523c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
95302c6de8dSMinchan Kim 				      bool force_reclaim)
9541da177e4SLinus Torvalds {
9551da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
956abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9571da177e4SLinus Torvalds 	int pgactivate = 0;
9583c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
9593c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
9603c710c1aSMichal Hocko 	unsigned nr_congested = 0;
9613c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
9623c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
9633c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
9645bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
9655bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
9661da177e4SLinus Torvalds 
9671da177e4SLinus Torvalds 	cond_resched();
9681da177e4SLinus Torvalds 
9691da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9701da177e4SLinus Torvalds 		struct address_space *mapping;
9711da177e4SLinus Torvalds 		struct page *page;
9721da177e4SLinus Torvalds 		int may_enter_fs;
97302c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
974e2be15f6SMel Gorman 		bool dirty, writeback;
9751da177e4SLinus Torvalds 
9761da177e4SLinus Torvalds 		cond_resched();
9771da177e4SLinus Torvalds 
9781da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9791da177e4SLinus Torvalds 		list_del(&page->lru);
9801da177e4SLinus Torvalds 
981529ae9aaSNick Piggin 		if (!trylock_page(page))
9821da177e4SLinus Torvalds 			goto keep;
9831da177e4SLinus Torvalds 
984309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9851da177e4SLinus Torvalds 
9861da177e4SLinus Torvalds 		sc->nr_scanned++;
98780e43426SChristoph Lameter 
98839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
989ad6b6704SMinchan Kim 			goto activate_locked;
990894bc310SLee Schermerhorn 
991a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
99280e43426SChristoph Lameter 			goto keep_locked;
99380e43426SChristoph Lameter 
9941da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
995802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
996802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
9971da177e4SLinus Torvalds 			sc->nr_scanned++;
9981da177e4SLinus Torvalds 
999c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1000c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1001c661b078SAndy Whitcroft 
1002e62e384eSMichal Hocko 		/*
1003e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
1004e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1005e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1006e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1007e2be15f6SMel Gorman 		 */
1008e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1009e2be15f6SMel Gorman 		if (dirty || writeback)
1010e2be15f6SMel Gorman 			nr_dirty++;
1011e2be15f6SMel Gorman 
1012e2be15f6SMel Gorman 		if (dirty && !writeback)
1013e2be15f6SMel Gorman 			nr_unqueued_dirty++;
1014e2be15f6SMel Gorman 
1015d04e8acdSMel Gorman 		/*
1016d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1017d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1018d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1019d04e8acdSMel Gorman 		 * end of the LRU a second time.
1020d04e8acdSMel Gorman 		 */
1021e2be15f6SMel Gorman 		mapping = page_mapping(page);
10221da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1023703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1024d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1025e2be15f6SMel Gorman 			nr_congested++;
1026e2be15f6SMel Gorman 
1027e2be15f6SMel Gorman 		/*
1028283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1029283aba9fSMel Gorman 		 * are three cases to consider.
1030e62e384eSMichal Hocko 		 *
1031283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1032283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1033283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1034283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1035283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1036283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1037283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1038b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1039b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1040c3b94f44SHugh Dickins 		 *
104197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1042ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1043ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1044ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
104597c9341fSTejun Heo 		 *    reclaim and continue scanning.
1046283aba9fSMel Gorman 		 *
1047ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1048ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1049283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1050283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1051283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1052283aba9fSMel Gorman 		 *    would probably show more reasons.
1053283aba9fSMel Gorman 		 *
10547fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1055283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1056283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1057283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1058283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1059c55e8d03SJohannes Weiner 		 *
1060c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1061c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1062c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1063c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1064c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1065c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1066c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1067c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1068e62e384eSMichal Hocko 		 */
1069283aba9fSMel Gorman 		if (PageWriteback(page)) {
1070283aba9fSMel Gorman 			/* Case 1 above */
1071283aba9fSMel Gorman 			if (current_is_kswapd() &&
1072283aba9fSMel Gorman 			    PageReclaim(page) &&
1073599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1074b1a6f21eSMel Gorman 				nr_immediate++;
1075c55e8d03SJohannes Weiner 				goto activate_locked;
1076283aba9fSMel Gorman 
1077283aba9fSMel Gorman 			/* Case 2 above */
107897c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1079ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1080c3b94f44SHugh Dickins 				/*
1081c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1082c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1083c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1084c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1085c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1086c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1087c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1088c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1089c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1090c3b94f44SHugh Dickins 				 */
1091c3b94f44SHugh Dickins 				SetPageReclaim(page);
109292df3a72SMel Gorman 				nr_writeback++;
1093c55e8d03SJohannes Weiner 				goto activate_locked;
1094283aba9fSMel Gorman 
1095283aba9fSMel Gorman 			/* Case 3 above */
1096283aba9fSMel Gorman 			} else {
10977fadc820SHugh Dickins 				unlock_page(page);
1098c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10997fadc820SHugh Dickins 				/* then go back and try same page again */
11007fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
11017fadc820SHugh Dickins 				continue;
1102e62e384eSMichal Hocko 			}
1103283aba9fSMel Gorman 		}
11041da177e4SLinus Torvalds 
110502c6de8dSMinchan Kim 		if (!force_reclaim)
11066a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
110702c6de8dSMinchan Kim 
1108dfc8d636SJohannes Weiner 		switch (references) {
1109dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
11101da177e4SLinus Torvalds 			goto activate_locked;
111164574746SJohannes Weiner 		case PAGEREF_KEEP:
11125bccd166SMichal Hocko 			nr_ref_keep++;
111364574746SJohannes Weiner 			goto keep_locked;
1114dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1115dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1116dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1117dfc8d636SJohannes Weiner 		}
11181da177e4SLinus Torvalds 
11191da177e4SLinus Torvalds 		/*
11201da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
11211da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1122802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
11231da177e4SLinus Torvalds 		 */
1124802a3a92SShaohua Li 		if (PageAnon(page) && PageSwapBacked(page) &&
1125802a3a92SShaohua Li 		    !PageSwapCache(page)) {
112663eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
112763eb6b93SHugh Dickins 				goto keep_locked;
1128747552b1SHuang Ying 			if (PageTransHuge(page)) {
1129b8f593cdSHuang Ying 				/* cannot split THP, skip it */
1130747552b1SHuang Ying 				if (!can_split_huge_page(page, NULL))
1131b8f593cdSHuang Ying 					goto activate_locked;
1132747552b1SHuang Ying 				/*
1133747552b1SHuang Ying 				 * Split pages without a PMD map right
1134747552b1SHuang Ying 				 * away. Chances are some or all of the
1135747552b1SHuang Ying 				 * tail pages can be freed without IO.
1136747552b1SHuang Ying 				 */
1137747552b1SHuang Ying 				if (!compound_mapcount(page) &&
1138747552b1SHuang Ying 				    split_huge_page_to_list(page, page_list))
1139747552b1SHuang Ying 					goto activate_locked;
1140747552b1SHuang Ying 			}
11410f074658SMinchan Kim 			if (!add_to_swap(page)) {
11420f074658SMinchan Kim 				if (!PageTransHuge(page))
11431da177e4SLinus Torvalds 					goto activate_locked;
11440f074658SMinchan Kim 				/* Split THP and swap individual base pages */
11450f074658SMinchan Kim 				if (split_huge_page_to_list(page, page_list))
11460f074658SMinchan Kim 					goto activate_locked;
11470f074658SMinchan Kim 				if (!add_to_swap(page))
11480f074658SMinchan Kim 					goto activate_locked;
11490f074658SMinchan Kim 			}
11500f074658SMinchan Kim 
11510f074658SMinchan Kim 			/* XXX: We don't support THP writes */
11520f074658SMinchan Kim 			if (PageTransHuge(page) &&
11530f074658SMinchan Kim 				  split_huge_page_to_list(page, page_list)) {
11540f074658SMinchan Kim 				delete_from_swap_cache(page);
11550f074658SMinchan Kim 				goto activate_locked;
11560f074658SMinchan Kim 			}
11570f074658SMinchan Kim 
115863eb6b93SHugh Dickins 			may_enter_fs = 1;
11591da177e4SLinus Torvalds 
1160e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
11611da177e4SLinus Torvalds 			mapping = page_mapping(page);
11627751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
11637751b2daSKirill A. Shutemov 			/* Split file THP */
11647751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
11657751b2daSKirill A. Shutemov 				goto keep_locked;
1166e2be15f6SMel Gorman 		}
11671da177e4SLinus Torvalds 
11687751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
11697751b2daSKirill A. Shutemov 
11701da177e4SLinus Torvalds 		/*
11711da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
11721da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
11731da177e4SLinus Torvalds 		 */
1174802a3a92SShaohua Li 		if (page_mapped(page)) {
1175666e5a40SMinchan Kim 			if (!try_to_unmap(page, ttu_flags | TTU_BATCH_FLUSH)) {
11765bccd166SMichal Hocko 				nr_unmap_fail++;
11771da177e4SLinus Torvalds 				goto activate_locked;
11781da177e4SLinus Torvalds 			}
11791da177e4SLinus Torvalds 		}
11801da177e4SLinus Torvalds 
11811da177e4SLinus Torvalds 		if (PageDirty(page)) {
1182ee72886dSMel Gorman 			/*
11834eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
11844eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
11854eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
11864eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
11874eda4823SJohannes Weiner 			 * write pages when we've encountered many
11884eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
11894eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
11904eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1191ee72886dSMel Gorman 			 */
1192f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11934eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1194599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
119549ea7eb6SMel Gorman 				/*
119649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
119749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
119849ea7eb6SMel Gorman 				 * except we already have the page isolated
119949ea7eb6SMel Gorman 				 * and know it's dirty
120049ea7eb6SMel Gorman 				 */
1201c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
120249ea7eb6SMel Gorman 				SetPageReclaim(page);
120349ea7eb6SMel Gorman 
1204c55e8d03SJohannes Weiner 				goto activate_locked;
1205ee72886dSMel Gorman 			}
1206ee72886dSMel Gorman 
1207dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
12081da177e4SLinus Torvalds 				goto keep_locked;
12094dd4b920SAndrew Morton 			if (!may_enter_fs)
12101da177e4SLinus Torvalds 				goto keep_locked;
121152a8363eSChristoph Lameter 			if (!sc->may_writepage)
12121da177e4SLinus Torvalds 				goto keep_locked;
12131da177e4SLinus Torvalds 
1214d950c947SMel Gorman 			/*
1215d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1216d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1217d950c947SMel Gorman 			 * starts and then write it out here.
1218d950c947SMel Gorman 			 */
1219d950c947SMel Gorman 			try_to_unmap_flush_dirty();
12207d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
12211da177e4SLinus Torvalds 			case PAGE_KEEP:
12221da177e4SLinus Torvalds 				goto keep_locked;
12231da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
12241da177e4SLinus Torvalds 				goto activate_locked;
12251da177e4SLinus Torvalds 			case PAGE_SUCCESS:
12267d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
122741ac1999SMel Gorman 					goto keep;
12287d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
12291da177e4SLinus Torvalds 					goto keep;
12307d3579e8SKOSAKI Motohiro 
12311da177e4SLinus Torvalds 				/*
12321da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
12331da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
12341da177e4SLinus Torvalds 				 */
1235529ae9aaSNick Piggin 				if (!trylock_page(page))
12361da177e4SLinus Torvalds 					goto keep;
12371da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
12381da177e4SLinus Torvalds 					goto keep_locked;
12391da177e4SLinus Torvalds 				mapping = page_mapping(page);
12401da177e4SLinus Torvalds 			case PAGE_CLEAN:
12411da177e4SLinus Torvalds 				; /* try to free the page below */
12421da177e4SLinus Torvalds 			}
12431da177e4SLinus Torvalds 		}
12441da177e4SLinus Torvalds 
12451da177e4SLinus Torvalds 		/*
12461da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
12471da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
12481da177e4SLinus Torvalds 		 * the page as well.
12491da177e4SLinus Torvalds 		 *
12501da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
12511da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
12521da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
12531da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
12541da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
12551da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
12561da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
12571da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
12581da177e4SLinus Torvalds 		 *
12591da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
12601da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
12611da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
12621da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
12631da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
12641da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
12651da177e4SLinus Torvalds 		 */
1266266cf658SDavid Howells 		if (page_has_private(page)) {
12671da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
12681da177e4SLinus Torvalds 				goto activate_locked;
1269e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1270e286781dSNick Piggin 				unlock_page(page);
1271e286781dSNick Piggin 				if (put_page_testzero(page))
12721da177e4SLinus Torvalds 					goto free_it;
1273e286781dSNick Piggin 				else {
1274e286781dSNick Piggin 					/*
1275e286781dSNick Piggin 					 * rare race with speculative reference.
1276e286781dSNick Piggin 					 * the speculative reference will free
1277e286781dSNick Piggin 					 * this page shortly, so we may
1278e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1279e286781dSNick Piggin 					 * leave it off the LRU).
1280e286781dSNick Piggin 					 */
1281e286781dSNick Piggin 					nr_reclaimed++;
1282e286781dSNick Piggin 					continue;
1283e286781dSNick Piggin 				}
1284e286781dSNick Piggin 			}
12851da177e4SLinus Torvalds 		}
12861da177e4SLinus Torvalds 
1287802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1288802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1289802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
129049d2e9ccSChristoph Lameter 				goto keep_locked;
1291802a3a92SShaohua Li 			if (PageDirty(page)) {
1292802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1293802a3a92SShaohua Li 				goto keep_locked;
1294802a3a92SShaohua Li 			}
12951da177e4SLinus Torvalds 
1296802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
12972262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1298802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1299802a3a92SShaohua Li 			goto keep_locked;
1300a978d6f5SNick Piggin 		/*
1301a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1302a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1303a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1304a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1305a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1306a978d6f5SNick Piggin 		 */
130748c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1308e286781dSNick Piggin free_it:
130905ff5137SAndrew Morton 		nr_reclaimed++;
1310abe4c3b5SMel Gorman 
1311abe4c3b5SMel Gorman 		/*
1312abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1313abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1314abe4c3b5SMel Gorman 		 */
1315abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
13161da177e4SLinus Torvalds 		continue;
13171da177e4SLinus Torvalds 
13181da177e4SLinus Torvalds activate_locked:
131968a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1320ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1321ad6b6704SMinchan Kim 						PageMlocked(page)))
1322a2c43eedSHugh Dickins 			try_to_free_swap(page);
1323309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1324ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
13251da177e4SLinus Torvalds 			SetPageActive(page);
13261da177e4SLinus Torvalds 			pgactivate++;
13272262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1328ad6b6704SMinchan Kim 		}
13291da177e4SLinus Torvalds keep_locked:
13301da177e4SLinus Torvalds 		unlock_page(page);
13311da177e4SLinus Torvalds keep:
13321da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1333309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
13341da177e4SLinus Torvalds 	}
1335abe4c3b5SMel Gorman 
1336747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
133772b252aeSMel Gorman 	try_to_unmap_flush();
1338b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1339abe4c3b5SMel Gorman 
13401da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1341f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
13420a31bc97SJohannes Weiner 
13433c710c1aSMichal Hocko 	if (stat) {
13443c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
13453c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
13463c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
13473c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
13483c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
13495bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
13505bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
13515bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
13523c710c1aSMichal Hocko 	}
135305ff5137SAndrew Morton 	return nr_reclaimed;
13541da177e4SLinus Torvalds }
13551da177e4SLinus Torvalds 
135602c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
135702c6de8dSMinchan Kim 					    struct list_head *page_list)
135802c6de8dSMinchan Kim {
135902c6de8dSMinchan Kim 	struct scan_control sc = {
136002c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
136102c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
136202c6de8dSMinchan Kim 		.may_unmap = 1,
136302c6de8dSMinchan Kim 	};
13643c710c1aSMichal Hocko 	unsigned long ret;
136502c6de8dSMinchan Kim 	struct page *page, *next;
136602c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
136702c6de8dSMinchan Kim 
136802c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1369117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1370b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
137102c6de8dSMinchan Kim 			ClearPageActive(page);
137202c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
137302c6de8dSMinchan Kim 		}
137402c6de8dSMinchan Kim 	}
137502c6de8dSMinchan Kim 
1376599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1377a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
137802c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1379599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
138002c6de8dSMinchan Kim 	return ret;
138102c6de8dSMinchan Kim }
138202c6de8dSMinchan Kim 
13835ad333ebSAndy Whitcroft /*
13845ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13855ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13865ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13875ad333ebSAndy Whitcroft  *
13885ad333ebSAndy Whitcroft  * page:	page to consider
13895ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13905ad333ebSAndy Whitcroft  *
13915ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13925ad333ebSAndy Whitcroft  */
1393f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13945ad333ebSAndy Whitcroft {
13955ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13965ad333ebSAndy Whitcroft 
13975ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13985ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13995ad333ebSAndy Whitcroft 		return ret;
14005ad333ebSAndy Whitcroft 
1401e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1402e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1403894bc310SLee Schermerhorn 		return ret;
1404894bc310SLee Schermerhorn 
14055ad333ebSAndy Whitcroft 	ret = -EBUSY;
140608e552c6SKAMEZAWA Hiroyuki 
1407c8244935SMel Gorman 	/*
1408c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1409c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1410c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1411c8244935SMel Gorman 	 *
1412c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1413c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1414c8244935SMel Gorman 	 */
14151276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1416c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1417c8244935SMel Gorman 		if (PageWriteback(page))
141839deaf85SMinchan Kim 			return ret;
141939deaf85SMinchan Kim 
1420c8244935SMel Gorman 		if (PageDirty(page)) {
1421c8244935SMel Gorman 			struct address_space *mapping;
1422c8244935SMel Gorman 
1423c8244935SMel Gorman 			/*
1424c8244935SMel Gorman 			 * Only pages without mappings or that have a
1425c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1426c8244935SMel Gorman 			 * without blocking
1427c8244935SMel Gorman 			 */
1428c8244935SMel Gorman 			mapping = page_mapping(page);
1429c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1430c8244935SMel Gorman 				return ret;
1431c8244935SMel Gorman 		}
1432c8244935SMel Gorman 	}
1433c8244935SMel Gorman 
1434f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1435f80c0673SMinchan Kim 		return ret;
1436f80c0673SMinchan Kim 
14375ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
14385ad333ebSAndy Whitcroft 		/*
14395ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
14405ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
14415ad333ebSAndy Whitcroft 		 * page release code relies on it.
14425ad333ebSAndy Whitcroft 		 */
14435ad333ebSAndy Whitcroft 		ClearPageLRU(page);
14445ad333ebSAndy Whitcroft 		ret = 0;
14455ad333ebSAndy Whitcroft 	}
14465ad333ebSAndy Whitcroft 
14475ad333ebSAndy Whitcroft 	return ret;
14485ad333ebSAndy Whitcroft }
14495ad333ebSAndy Whitcroft 
14507ee36a14SMel Gorman 
14517ee36a14SMel Gorman /*
14527ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
14537ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
14547ee36a14SMel Gorman  */
14557ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1456b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
14577ee36a14SMel Gorman {
14587ee36a14SMel Gorman 	int zid;
14597ee36a14SMel Gorman 
14607ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14617ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14627ee36a14SMel Gorman 			continue;
14637ee36a14SMel Gorman 
14647ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1465b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1466b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1467b4536f0cSMichal Hocko #endif
14687ee36a14SMel Gorman 	}
14697ee36a14SMel Gorman 
14707ee36a14SMel Gorman }
14717ee36a14SMel Gorman 
147249d2e9ccSChristoph Lameter /*
1473a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14741da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14751da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14761da177e4SLinus Torvalds  *
14771da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14781da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14791da177e4SLinus Torvalds  *
14801da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14811da177e4SLinus Torvalds  *
1482791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
14835dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14841da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1485f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1486fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14875ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14883cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14891da177e4SLinus Torvalds  *
14901da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14911da177e4SLinus Torvalds  */
149269e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14935dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1494fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14953cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14961da177e4SLinus Torvalds {
149775b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
149869e05944SAndrew Morton 	unsigned long nr_taken = 0;
1499599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
15007cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
15013db65812SJohannes Weiner 	unsigned long skipped = 0;
1502791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1503b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
15041da177e4SLinus Torvalds 
1505791b48b6SMinchan Kim 	scan = 0;
1506791b48b6SMinchan Kim 	for (total_scan = 0;
1507791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1508791b48b6SMinchan Kim 	     total_scan++) {
15095ad333ebSAndy Whitcroft 		struct page *page;
15105ad333ebSAndy Whitcroft 
15111da177e4SLinus Torvalds 		page = lru_to_page(src);
15121da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
15131da177e4SLinus Torvalds 
1514309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
15158d438f96SNick Piggin 
1516b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1517b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
15187cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1519b2e18757SMel Gorman 			continue;
1520b2e18757SMel Gorman 		}
1521b2e18757SMel Gorman 
1522791b48b6SMinchan Kim 		/*
1523791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1524791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1525791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1526791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1527791b48b6SMinchan Kim 		 */
1528791b48b6SMinchan Kim 		scan++;
1529f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
15305ad333ebSAndy Whitcroft 		case 0:
1531599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1532599d0c95SMel Gorman 			nr_taken += nr_pages;
1533599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
15345ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
15355ad333ebSAndy Whitcroft 			break;
15367c8ee9a8SNick Piggin 
15375ad333ebSAndy Whitcroft 		case -EBUSY:
15385ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
15395ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
15405ad333ebSAndy Whitcroft 			continue;
15415ad333ebSAndy Whitcroft 
15425ad333ebSAndy Whitcroft 		default:
15435ad333ebSAndy Whitcroft 			BUG();
15445ad333ebSAndy Whitcroft 		}
15455ad333ebSAndy Whitcroft 	}
15461da177e4SLinus Torvalds 
1547b2e18757SMel Gorman 	/*
1548b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1549b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1550b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1551b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1552b2e18757SMel Gorman 	 * system at risk of premature OOM.
1553b2e18757SMel Gorman 	 */
15547cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
15557cc30fcfSMel Gorman 		int zid;
15567cc30fcfSMel Gorman 
15573db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
15587cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15597cc30fcfSMel Gorman 			if (!nr_skipped[zid])
15607cc30fcfSMel Gorman 				continue;
15617cc30fcfSMel Gorman 
15627cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
15631265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
15647cc30fcfSMel Gorman 		}
15657cc30fcfSMel Gorman 	}
1566791b48b6SMinchan Kim 	*nr_scanned = total_scan;
15671265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1568791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1569b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15701da177e4SLinus Torvalds 	return nr_taken;
15711da177e4SLinus Torvalds }
15721da177e4SLinus Torvalds 
157362695a84SNick Piggin /**
157462695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
157562695a84SNick Piggin  * @page: page to isolate from its LRU list
157662695a84SNick Piggin  *
157762695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
157862695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
157962695a84SNick Piggin  *
158062695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
158162695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
158262695a84SNick Piggin  *
158362695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1584894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1585894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1586894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
158762695a84SNick Piggin  *
158862695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
158962695a84SNick Piggin  * found will be decremented.
159062695a84SNick Piggin  *
159162695a84SNick Piggin  * Restrictions:
159262695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
159362695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
159462695a84SNick Piggin  *     without a stable reference).
159562695a84SNick Piggin  * (2) the lru_lock must not be held.
159662695a84SNick Piggin  * (3) interrupts must be enabled.
159762695a84SNick Piggin  */
159862695a84SNick Piggin int isolate_lru_page(struct page *page)
159962695a84SNick Piggin {
160062695a84SNick Piggin 	int ret = -EBUSY;
160162695a84SNick Piggin 
1602309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1603cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
16040c917313SKonstantin Khlebnikov 
160562695a84SNick Piggin 	if (PageLRU(page)) {
160662695a84SNick Piggin 		struct zone *zone = page_zone(page);
1607fa9add64SHugh Dickins 		struct lruvec *lruvec;
160862695a84SNick Piggin 
1609a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1610599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
16110c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1612894bc310SLee Schermerhorn 			int lru = page_lru(page);
16130c917313SKonstantin Khlebnikov 			get_page(page);
161462695a84SNick Piggin 			ClearPageLRU(page);
1615fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1616fa9add64SHugh Dickins 			ret = 0;
161762695a84SNick Piggin 		}
1618a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
161962695a84SNick Piggin 	}
162062695a84SNick Piggin 	return ret;
162162695a84SNick Piggin }
162262695a84SNick Piggin 
16235ad333ebSAndy Whitcroft /*
1624d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1625d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1626d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1627d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1628d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
162935cd7815SRik van Riel  */
1630599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
163135cd7815SRik van Riel 		struct scan_control *sc)
163235cd7815SRik van Riel {
163335cd7815SRik van Riel 	unsigned long inactive, isolated;
163435cd7815SRik van Riel 
163535cd7815SRik van Riel 	if (current_is_kswapd())
163635cd7815SRik van Riel 		return 0;
163735cd7815SRik van Riel 
163897c9341fSTejun Heo 	if (!sane_reclaim(sc))
163935cd7815SRik van Riel 		return 0;
164035cd7815SRik van Riel 
164135cd7815SRik van Riel 	if (file) {
1642599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1643599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
164435cd7815SRik van Riel 	} else {
1645599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1646599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
164735cd7815SRik van Riel 	}
164835cd7815SRik van Riel 
16493cf23841SFengguang Wu 	/*
16503cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
16513cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
16523cf23841SFengguang Wu 	 * deadlock.
16533cf23841SFengguang Wu 	 */
1654d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
16553cf23841SFengguang Wu 		inactive >>= 3;
16563cf23841SFengguang Wu 
165735cd7815SRik van Riel 	return isolated > inactive;
165835cd7815SRik van Riel }
165935cd7815SRik van Riel 
166066635629SMel Gorman static noinline_for_stack void
166175b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
166266635629SMel Gorman {
166327ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1664599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16653f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
166666635629SMel Gorman 
166766635629SMel Gorman 	/*
166866635629SMel Gorman 	 * Put back any unfreeable pages.
166966635629SMel Gorman 	 */
167066635629SMel Gorman 	while (!list_empty(page_list)) {
16713f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
167266635629SMel Gorman 		int lru;
16733f79768fSHugh Dickins 
1674309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
167566635629SMel Gorman 		list_del(&page->lru);
167639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1677599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
167866635629SMel Gorman 			putback_lru_page(page);
1679599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
168066635629SMel Gorman 			continue;
168166635629SMel Gorman 		}
1682fa9add64SHugh Dickins 
1683599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1684fa9add64SHugh Dickins 
16857a608572SLinus Torvalds 		SetPageLRU(page);
168666635629SMel Gorman 		lru = page_lru(page);
1687fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1688fa9add64SHugh Dickins 
168966635629SMel Gorman 		if (is_active_lru(lru)) {
169066635629SMel Gorman 			int file = is_file_lru(lru);
16919992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16929992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
169366635629SMel Gorman 		}
16942bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16952bcf8879SHugh Dickins 			__ClearPageLRU(page);
16962bcf8879SHugh Dickins 			__ClearPageActive(page);
1697fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16982bcf8879SHugh Dickins 
16992bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1700599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1701747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
17022bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1703599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
17042bcf8879SHugh Dickins 			} else
17052bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
170666635629SMel Gorman 		}
170766635629SMel Gorman 	}
170866635629SMel Gorman 
17093f79768fSHugh Dickins 	/*
17103f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
17113f79768fSHugh Dickins 	 */
17123f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
171366635629SMel Gorman }
171466635629SMel Gorman 
171566635629SMel Gorman /*
1716399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1717399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1718399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1719399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1720399ba0b9SNeilBrown  */
1721399ba0b9SNeilBrown static int current_may_throttle(void)
1722399ba0b9SNeilBrown {
1723399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1724399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1725399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1726399ba0b9SNeilBrown }
1727399ba0b9SNeilBrown 
1728399ba0b9SNeilBrown /*
1729b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
17301742f19fSAndrew Morton  * of reclaimed pages
17311da177e4SLinus Torvalds  */
173266635629SMel Gorman static noinline_for_stack unsigned long
17331a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
17349e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
17351da177e4SLinus Torvalds {
17361da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1737e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
173805ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1739e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
17403c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1741f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17423cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1743599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17441a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
174578dc583dSKOSAKI Motohiro 
1746599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
174758355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
174835cd7815SRik van Riel 
174935cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
175035cd7815SRik van Riel 		if (fatal_signal_pending(current))
175135cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
175235cd7815SRik van Riel 	}
175335cd7815SRik van Riel 
17541da177e4SLinus Torvalds 	lru_add_drain();
1755f80c0673SMinchan Kim 
1756f80c0673SMinchan Kim 	if (!sc->may_unmap)
175761317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1758f80c0673SMinchan Kim 
1759599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17601da177e4SLinus Torvalds 
17615dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17625dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
176395d918fcSKonstantin Khlebnikov 
1764599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17659d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
176695d918fcSKonstantin Khlebnikov 
17672262185cSRoman Gushchin 	if (current_is_kswapd()) {
17682262185cSRoman Gushchin 		if (global_reclaim(sc))
1769599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
17702262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
17712262185cSRoman Gushchin 				   nr_scanned);
17722262185cSRoman Gushchin 	} else {
17732262185cSRoman Gushchin 		if (global_reclaim(sc))
1774599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
17752262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
17762262185cSRoman Gushchin 				   nr_scanned);
1777b35ea17bSKOSAKI Motohiro 	}
1778599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1779d563c050SHillf Danton 
1780d563c050SHillf Danton 	if (nr_taken == 0)
178166635629SMel Gorman 		return 0;
1782b35ea17bSKOSAKI Motohiro 
1783a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
17843c710c1aSMichal Hocko 				&stat, false);
1785c661b078SAndy Whitcroft 
1786599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17873f79768fSHugh Dickins 
17882262185cSRoman Gushchin 	if (current_is_kswapd()) {
17892262185cSRoman Gushchin 		if (global_reclaim(sc))
1790599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
17912262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
17922262185cSRoman Gushchin 				   nr_reclaimed);
17932262185cSRoman Gushchin 	} else {
17942262185cSRoman Gushchin 		if (global_reclaim(sc))
1795599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
17962262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
17972262185cSRoman Gushchin 				   nr_reclaimed);
1798904249aaSYing Han 	}
1799a74609faSNick Piggin 
180027ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
18013f79768fSHugh Dickins 
1802599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
18033f79768fSHugh Dickins 
1804599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
18053f79768fSHugh Dickins 
1806747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1807b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1808e11da5b4SMel Gorman 
180992df3a72SMel Gorman 	/*
181092df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
181192df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
181292df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
181392df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
181492df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
181592df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
181692df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
181792df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
181892df3a72SMel Gorman 	 *
18198e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
18208e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
18218e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
182292df3a72SMel Gorman 	 */
18233c710c1aSMichal Hocko 	if (stat.nr_writeback && stat.nr_writeback == nr_taken)
1824599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
182592df3a72SMel Gorman 
1826d43006d5SMel Gorman 	/*
182797c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
182897c9341fSTejun Heo 	 * stalling here.
1829d43006d5SMel Gorman 	 */
183097c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1831b1a6f21eSMel Gorman 		/*
18328e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
18338e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
18348e950282SMel Gorman 		 */
18353c710c1aSMichal Hocko 		if (stat.nr_dirty && stat.nr_dirty == stat.nr_congested)
1836599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
18378e950282SMel Gorman 
18388e950282SMel Gorman 		/*
1839b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1840726d061fSJohannes Weiner 		 * implies that flushers are not doing their job. This can
1841726d061fSJohannes Weiner 		 * happen when memory pressure pushes dirty pages to the end of
1842726d061fSJohannes Weiner 		 * the LRU before the dirty limits are breached and the dirty
1843726d061fSJohannes Weiner 		 * data has expired. It can also happen when the proportion of
1844726d061fSJohannes Weiner 		 * dirty pages grows not through writes but through memory
1845726d061fSJohannes Weiner 		 * pressure reclaiming all the clean cache. And in some cases,
1846726d061fSJohannes Weiner 		 * the flushers simply cannot keep up with the allocation
1847726d061fSJohannes Weiner 		 * rate. Nudge the flusher threads in case they are asleep, but
1848726d061fSJohannes Weiner 		 * also allow kswapd to start writing pages during reclaim.
1849b1a6f21eSMel Gorman 		 */
1850726d061fSJohannes Weiner 		if (stat.nr_unqueued_dirty == nr_taken) {
1851726d061fSJohannes Weiner 			wakeup_flusher_threads(0, WB_REASON_VMSCAN);
1852599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1853726d061fSJohannes Weiner 		}
1854b1a6f21eSMel Gorman 
1855b1a6f21eSMel Gorman 		/*
1856b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1857b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1858b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1859b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1860b1a6f21eSMel Gorman 		 */
18613c710c1aSMichal Hocko 		if (stat.nr_immediate && current_may_throttle())
1862b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1863e2be15f6SMel Gorman 	}
1864d43006d5SMel Gorman 
18658e950282SMel Gorman 	/*
18668e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
18678e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18688e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18698e950282SMel Gorman 	 */
1870399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1871399ba0b9SNeilBrown 	    current_may_throttle())
1872599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18738e950282SMel Gorman 
1874599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1875599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
18765bccd166SMichal Hocko 			stat.nr_dirty,  stat.nr_writeback,
18775bccd166SMichal Hocko 			stat.nr_congested, stat.nr_immediate,
18785bccd166SMichal Hocko 			stat.nr_activate, stat.nr_ref_keep,
18795bccd166SMichal Hocko 			stat.nr_unmap_fail,
1880ba5e9579Syalin wang 			sc->priority, file);
188105ff5137SAndrew Morton 	return nr_reclaimed;
18821da177e4SLinus Torvalds }
18831da177e4SLinus Torvalds 
18843bb1a852SMartin Bligh /*
18851cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18861cfb419bSKAMEZAWA Hiroyuki  *
18871cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18881cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18891cfb419bSKAMEZAWA Hiroyuki  *
18901cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1891a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18921cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1893a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18941cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18951cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18961cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18971cfb419bSKAMEZAWA Hiroyuki  *
18980139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18991cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
19009d998b4fSMichal Hocko  *
19019d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
19021cfb419bSKAMEZAWA Hiroyuki  */
19031cfb419bSKAMEZAWA Hiroyuki 
19049d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
19053eb4140fSWu Fengguang 				     struct list_head *list,
19062bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
19073eb4140fSWu Fengguang 				     enum lru_list lru)
19083eb4140fSWu Fengguang {
1909599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19103eb4140fSWu Fengguang 	struct page *page;
1911fa9add64SHugh Dickins 	int nr_pages;
19129d998b4fSMichal Hocko 	int nr_moved = 0;
19133eb4140fSWu Fengguang 
19143eb4140fSWu Fengguang 	while (!list_empty(list)) {
19153eb4140fSWu Fengguang 		page = lru_to_page(list);
1916599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
19173eb4140fSWu Fengguang 
1918309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
19193eb4140fSWu Fengguang 		SetPageLRU(page);
19203eb4140fSWu Fengguang 
1921fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1922599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1923925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
19243eb4140fSWu Fengguang 
19252bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
19262bcf8879SHugh Dickins 			__ClearPageLRU(page);
19272bcf8879SHugh Dickins 			__ClearPageActive(page);
1928fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
19292bcf8879SHugh Dickins 
19302bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1931599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1932747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
19332bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1934599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
19352bcf8879SHugh Dickins 			} else
19362bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
19379d998b4fSMichal Hocko 		} else {
19389d998b4fSMichal Hocko 			nr_moved += nr_pages;
19393eb4140fSWu Fengguang 		}
19403eb4140fSWu Fengguang 	}
19419d5e6a9fSHugh Dickins 
19422262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
1943f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
19442262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
19452262185cSRoman Gushchin 				   nr_moved);
19462262185cSRoman Gushchin 	}
19479d998b4fSMichal Hocko 
19489d998b4fSMichal Hocko 	return nr_moved;
19493eb4140fSWu Fengguang }
19501cfb419bSKAMEZAWA Hiroyuki 
1951f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19521a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1953f16015fbSJohannes Weiner 			       struct scan_control *sc,
19549e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19551cfb419bSKAMEZAWA Hiroyuki {
195644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1957f626012dSHugh Dickins 	unsigned long nr_scanned;
19586fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19591cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19608cab4754SWu Fengguang 	LIST_HEAD(l_active);
1961b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19621cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19631a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19649d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
19659d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
1966f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19673cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1968599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19691cfb419bSKAMEZAWA Hiroyuki 
19701da177e4SLinus Torvalds 	lru_add_drain();
1971f80c0673SMinchan Kim 
1972f80c0673SMinchan Kim 	if (!sc->may_unmap)
197361317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1974f80c0673SMinchan Kim 
1975599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1976925b7673SJohannes Weiner 
19775dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19785dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
197989b5fae5SJohannes Weiner 
1980599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1981b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19821cfb419bSKAMEZAWA Hiroyuki 
1983599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19842262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
19859d5e6a9fSHugh Dickins 
1986599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19871da177e4SLinus Torvalds 
19881da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19891da177e4SLinus Torvalds 		cond_resched();
19901da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19911da177e4SLinus Torvalds 		list_del(&page->lru);
19927e9cd484SRik van Riel 
199339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1994894bc310SLee Schermerhorn 			putback_lru_page(page);
1995894bc310SLee Schermerhorn 			continue;
1996894bc310SLee Schermerhorn 		}
1997894bc310SLee Schermerhorn 
1998cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1999cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2000cc715d99SMel Gorman 				if (page_has_private(page))
2001cc715d99SMel Gorman 					try_to_release_page(page, 0);
2002cc715d99SMel Gorman 				unlock_page(page);
2003cc715d99SMel Gorman 			}
2004cc715d99SMel Gorman 		}
2005cc715d99SMel Gorman 
2006c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2007c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20089992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20098cab4754SWu Fengguang 			/*
20108cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20118cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20128cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20138cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20148cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20158cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20168cab4754SWu Fengguang 			 * so we ignore them here.
20178cab4754SWu Fengguang 			 */
201841e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20198cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20208cab4754SWu Fengguang 				continue;
20218cab4754SWu Fengguang 			}
20228cab4754SWu Fengguang 		}
20237e9cd484SRik van Riel 
20245205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20251da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20261da177e4SLinus Torvalds 	}
20271da177e4SLinus Torvalds 
2028b555749aSAndrew Morton 	/*
20298cab4754SWu Fengguang 	 * Move pages back to the lru list.
2030b555749aSAndrew Morton 	 */
2031599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
20324f98a2feSRik van Riel 	/*
20338cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
20348cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
20358cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
20367c0db9e9SJerome Marchand 	 * get_scan_count.
2037556adecbSRik van Riel 	 */
2038b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2039556adecbSRik van Riel 
20409d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
20419d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
2042599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2043599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20442bcf8879SHugh Dickins 
2045747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
2046b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
20479d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
20489d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
20491da177e4SLinus Torvalds }
20501da177e4SLinus Torvalds 
205159dc76b0SRik van Riel /*
205259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
205359dc76b0SRik van Riel  * to do too much work.
205414797e23SKOSAKI Motohiro  *
205559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
205659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
205759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
205859dc76b0SRik van Riel  *
205959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
206059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
206159dc76b0SRik van Riel  *
20622a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
20632a2e4885SJohannes Weiner  *
206459dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
206559dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
206659dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
206759dc76b0SRik van Riel  *
206859dc76b0SRik van Riel  * total     target    max
206959dc76b0SRik van Riel  * memory    ratio     inactive
207059dc76b0SRik van Riel  * -------------------------------------
207159dc76b0SRik van Riel  *   10MB       1         5MB
207259dc76b0SRik van Riel  *  100MB       1        50MB
207359dc76b0SRik van Riel  *    1GB       3       250MB
207459dc76b0SRik van Riel  *   10GB      10       0.9GB
207559dc76b0SRik van Riel  *  100GB      31         3GB
207659dc76b0SRik van Riel  *    1TB     101        10GB
207759dc76b0SRik van Riel  *   10TB     320        32GB
207814797e23SKOSAKI Motohiro  */
2079f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
20802a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
20812a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
208214797e23SKOSAKI Motohiro {
2083fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
20842a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20852a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
20862a2e4885SJohannes Weiner 	unsigned long inactive, active;
20872a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
20882a2e4885SJohannes Weiner 	unsigned long refaults;
208959dc76b0SRik van Riel 	unsigned long gb;
209059dc76b0SRik van Riel 
209174e3f3c3SMinchan Kim 	/*
209274e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
209374e3f3c3SMinchan Kim 	 * is pointless.
209474e3f3c3SMinchan Kim 	 */
209559dc76b0SRik van Riel 	if (!file && !total_swap_pages)
209642e2e457SYaowei Bai 		return false;
209774e3f3c3SMinchan Kim 
2098fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2099fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2100f8d1a311SMel Gorman 
21012a2e4885SJohannes Weiner 	if (memcg)
2102ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
21032a2e4885SJohannes Weiner 	else
21042a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
21052a2e4885SJohannes Weiner 
21062a2e4885SJohannes Weiner 	/*
21072a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
21082a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
21092a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
21102a2e4885SJohannes Weiner 	 */
21112a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
21122a2e4885SJohannes Weiner 		inactive_ratio = 0;
21132a2e4885SJohannes Weiner 	} else {
211459dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
211559dc76b0SRik van Riel 		if (gb)
211659dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2117b39415b2SRik van Riel 		else
211859dc76b0SRik van Riel 			inactive_ratio = 1;
21192a2e4885SJohannes Weiner 	}
212059dc76b0SRik van Riel 
21212a2e4885SJohannes Weiner 	if (actual_reclaim)
21222a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2123fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2124fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2125fd538803SMichal Hocko 			inactive_ratio, file);
2126fd538803SMichal Hocko 
212759dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2128b39415b2SRik van Riel }
2129b39415b2SRik van Riel 
21304f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
21312a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
21322a2e4885SJohannes Weiner 				 struct scan_control *sc)
2133b69408e8SChristoph Lameter {
2134b39415b2SRik van Riel 	if (is_active_lru(lru)) {
21352a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
21362a2e4885SJohannes Weiner 					 memcg, sc, true))
21371a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2138556adecbSRik van Riel 		return 0;
2139556adecbSRik van Riel 	}
2140556adecbSRik van Riel 
21411a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2142b69408e8SChristoph Lameter }
2143b69408e8SChristoph Lameter 
21449a265114SJohannes Weiner enum scan_balance {
21459a265114SJohannes Weiner 	SCAN_EQUAL,
21469a265114SJohannes Weiner 	SCAN_FRACT,
21479a265114SJohannes Weiner 	SCAN_ANON,
21489a265114SJohannes Weiner 	SCAN_FILE,
21499a265114SJohannes Weiner };
21509a265114SJohannes Weiner 
21511da177e4SLinus Torvalds /*
21524f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
21534f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
21544f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
21554f98a2feSRik van Riel  * onto the active list instead of evict.
21564f98a2feSRik van Riel  *
2157be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2158be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
21594f98a2feSRik van Riel  */
216033377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
21616b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
21626b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
21634f98a2feSRik van Riel {
216433377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
216590126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
21669a265114SJohannes Weiner 	u64 fraction[2];
21679a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2168599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21699a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
21709a265114SJohannes Weiner 	enum scan_balance scan_balance;
21710bf1457fSJohannes Weiner 	unsigned long anon, file;
21729a265114SJohannes Weiner 	unsigned long ap, fp;
21739a265114SJohannes Weiner 	enum lru_list lru;
217476a33fc3SShaohua Li 
217576a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2176d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21779a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
217876a33fc3SShaohua Li 		goto out;
217976a33fc3SShaohua Li 	}
21804f98a2feSRik van Riel 
218110316b31SJohannes Weiner 	/*
218210316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
218310316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
218410316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
218510316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
218610316b31SJohannes Weiner 	 * too expensive.
218710316b31SJohannes Weiner 	 */
218802695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21899a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
219010316b31SJohannes Weiner 		goto out;
219110316b31SJohannes Weiner 	}
219210316b31SJohannes Weiner 
219310316b31SJohannes Weiner 	/*
219410316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
219510316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
219610316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
219710316b31SJohannes Weiner 	 */
219802695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21999a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
220010316b31SJohannes Weiner 		goto out;
220110316b31SJohannes Weiner 	}
220210316b31SJohannes Weiner 
220311d16c25SJohannes Weiner 	/*
220462376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
220562376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
220662376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
220762376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
220862376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
220962376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
221062376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
221162376251SJohannes Weiner 	 */
221262376251SJohannes Weiner 	if (global_reclaim(sc)) {
2213599d0c95SMel Gorman 		unsigned long pgdatfile;
2214599d0c95SMel Gorman 		unsigned long pgdatfree;
2215599d0c95SMel Gorman 		int z;
2216599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
221762376251SJohannes Weiner 
2218599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2219599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2220599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
22212ab051e1SJerome Marchand 
2222599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2223599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
22246aa303deSMel Gorman 			if (!managed_zone(zone))
2225599d0c95SMel Gorman 				continue;
2226599d0c95SMel Gorman 
2227599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2228599d0c95SMel Gorman 		}
2229599d0c95SMel Gorman 
2230599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
223162376251SJohannes Weiner 			scan_balance = SCAN_ANON;
223262376251SJohannes Weiner 			goto out;
223362376251SJohannes Weiner 		}
223462376251SJohannes Weiner 	}
223562376251SJohannes Weiner 
223662376251SJohannes Weiner 	/*
2237316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2238316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2239316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2240316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2241316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2242316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2243316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2244e9868505SRik van Riel 	 */
22452a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
224671ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
22479a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2248e9868505SRik van Riel 		goto out;
22494f98a2feSRik van Riel 	}
22504f98a2feSRik van Riel 
22519a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22529a265114SJohannes Weiner 
22534f98a2feSRik van Riel 	/*
225458c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
225558c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
225658c37f6eSKOSAKI Motohiro 	 */
225702695175SJohannes Weiner 	anon_prio = swappiness;
225875b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
225958c37f6eSKOSAKI Motohiro 
226058c37f6eSKOSAKI Motohiro 	/*
22614f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22624f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22634f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22644f98a2feSRik van Riel 	 *
22654f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22664f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22674f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22684f98a2feSRik van Riel 	 *
22694f98a2feSRik van Riel 	 * anon in [0], file in [1]
22704f98a2feSRik van Riel 	 */
22712ab051e1SJerome Marchand 
2272fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2273fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2274fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2275fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
22762ab051e1SJerome Marchand 
2277599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
227858c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22796e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22806e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22814f98a2feSRik van Riel 	}
22824f98a2feSRik van Riel 
22836e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22846e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22856e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22864f98a2feSRik van Riel 	}
22874f98a2feSRik van Riel 
22884f98a2feSRik van Riel 	/*
228900d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
229000d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
229100d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22924f98a2feSRik van Riel 	 */
2293fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22946e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22954f98a2feSRik van Riel 
2296fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22976e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2298599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22994f98a2feSRik van Riel 
230076a33fc3SShaohua Li 	fraction[0] = ap;
230176a33fc3SShaohua Li 	fraction[1] = fp;
230276a33fc3SShaohua Li 	denominator = ap + fp + 1;
230376a33fc3SShaohua Li out:
23046b4f7799SJohannes Weiner 	*lru_pages = 0;
23054111304dSHugh Dickins 	for_each_evictable_lru(lru) {
23064111304dSHugh Dickins 		int file = is_file_lru(lru);
2307d778df51SJohannes Weiner 		unsigned long size;
230876a33fc3SShaohua Li 		unsigned long scan;
230976a33fc3SShaohua Li 
231071ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2311d778df51SJohannes Weiner 		scan = size >> sc->priority;
2312688035f7SJohannes Weiner 		/*
2313688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2314688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2315688035f7SJohannes Weiner 		 */
2316688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2317d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
23189a265114SJohannes Weiner 
23199a265114SJohannes Weiner 		switch (scan_balance) {
23209a265114SJohannes Weiner 		case SCAN_EQUAL:
23219a265114SJohannes Weiner 			/* Scan lists relative to size */
23229a265114SJohannes Weiner 			break;
23239a265114SJohannes Weiner 		case SCAN_FRACT:
23249a265114SJohannes Weiner 			/*
23259a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
23269a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
23279a265114SJohannes Weiner 			 */
23286f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
23296f04f48dSSuleiman Souhlal 					 denominator);
23309a265114SJohannes Weiner 			break;
23319a265114SJohannes Weiner 		case SCAN_FILE:
23329a265114SJohannes Weiner 		case SCAN_ANON:
23339a265114SJohannes Weiner 			/* Scan one type exclusively */
23346b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
23356b4f7799SJohannes Weiner 				size = 0;
23369a265114SJohannes Weiner 				scan = 0;
23376b4f7799SJohannes Weiner 			}
23389a265114SJohannes Weiner 			break;
23399a265114SJohannes Weiner 		default:
23409a265114SJohannes Weiner 			/* Look ma, no brain */
23419a265114SJohannes Weiner 			BUG();
23429a265114SJohannes Weiner 		}
23436b4f7799SJohannes Weiner 
23446b4f7799SJohannes Weiner 		*lru_pages += size;
23454111304dSHugh Dickins 		nr[lru] = scan;
234676a33fc3SShaohua Li 	}
23476e08a369SWu Fengguang }
23484f98a2feSRik van Riel 
23499b4f98cdSJohannes Weiner /*
2350a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23519b4f98cdSJohannes Weiner  */
2352a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23536b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23549b4f98cdSJohannes Weiner {
2355ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23569b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2357e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23589b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23599b4f98cdSJohannes Weiner 	enum lru_list lru;
23609b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23619b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23629b4f98cdSJohannes Weiner 	struct blk_plug plug;
23631a501907SMel Gorman 	bool scan_adjusted;
23649b4f98cdSJohannes Weiner 
236533377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23669b4f98cdSJohannes Weiner 
2367e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2368e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2369e82e0561SMel Gorman 
23701a501907SMel Gorman 	/*
23711a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23721a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23731a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23741a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23751a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23761a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23771a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23781a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23791a501907SMel Gorman 	 * dropped to zero at the first pass.
23801a501907SMel Gorman 	 */
23811a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23821a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23831a501907SMel Gorman 
23849b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23859b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23869b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2387e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2388e82e0561SMel Gorman 		unsigned long nr_scanned;
2389e82e0561SMel Gorman 
23909b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23919b4f98cdSJohannes Weiner 			if (nr[lru]) {
23929b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23939b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23949b4f98cdSJohannes Weiner 
23959b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23962a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
23979b4f98cdSJohannes Weiner 			}
23989b4f98cdSJohannes Weiner 		}
2399e82e0561SMel Gorman 
2400bd041733SMichal Hocko 		cond_resched();
2401bd041733SMichal Hocko 
2402e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2403e82e0561SMel Gorman 			continue;
2404e82e0561SMel Gorman 
24059b4f98cdSJohannes Weiner 		/*
2406e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
24071a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2408e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2409e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2410e82e0561SMel Gorman 		 * proportional to the original scan target.
2411e82e0561SMel Gorman 		 */
2412e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2413e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2414e82e0561SMel Gorman 
24151a501907SMel Gorman 		/*
24161a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
24171a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
24181a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
24191a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
24201a501907SMel Gorman 		 */
24211a501907SMel Gorman 		if (!nr_file || !nr_anon)
24221a501907SMel Gorman 			break;
24231a501907SMel Gorman 
2424e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2425e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2426e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2427e82e0561SMel Gorman 			lru = LRU_BASE;
2428e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2429e82e0561SMel Gorman 		} else {
2430e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2431e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2432e82e0561SMel Gorman 			lru = LRU_FILE;
2433e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2434e82e0561SMel Gorman 		}
2435e82e0561SMel Gorman 
2436e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2437e82e0561SMel Gorman 		nr[lru] = 0;
2438e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2439e82e0561SMel Gorman 
2440e82e0561SMel Gorman 		/*
2441e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2442e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2443e82e0561SMel Gorman 		 */
2444e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2445e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2446e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2447e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2448e82e0561SMel Gorman 
2449e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2450e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2451e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2452e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2453e82e0561SMel Gorman 
2454e82e0561SMel Gorman 		scan_adjusted = true;
24559b4f98cdSJohannes Weiner 	}
24569b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24579b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24589b4f98cdSJohannes Weiner 
24599b4f98cdSJohannes Weiner 	/*
24609b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24619b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24629b4f98cdSJohannes Weiner 	 */
24632a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
24649b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24659b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24669b4f98cdSJohannes Weiner }
24679b4f98cdSJohannes Weiner 
246823b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24699e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
247023b9da55SMel Gorman {
2471d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
247223b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24739e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
247423b9da55SMel Gorman 		return true;
247523b9da55SMel Gorman 
247623b9da55SMel Gorman 	return false;
247723b9da55SMel Gorman }
247823b9da55SMel Gorman 
24794f98a2feSRik van Riel /*
248023b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
248123b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
248223b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
248323b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
248423b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24853e7d3449SMel Gorman  */
2486a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24873e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24883e7d3449SMel Gorman 					unsigned long nr_scanned,
24893e7d3449SMel Gorman 					struct scan_control *sc)
24903e7d3449SMel Gorman {
24913e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24923e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2493a9dd0a83SMel Gorman 	int z;
24943e7d3449SMel Gorman 
24953e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24969e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24973e7d3449SMel Gorman 		return false;
24983e7d3449SMel Gorman 
24992876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
25002876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
25013e7d3449SMel Gorman 		/*
25022876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
25032876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
25042876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
25052876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
25063e7d3449SMel Gorman 		 */
25073e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
25083e7d3449SMel Gorman 			return false;
25092876592fSMel Gorman 	} else {
25102876592fSMel Gorman 		/*
25112876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
25122876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
25132876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
25142876592fSMel Gorman 		 * pages that were scanned. This will return to the
25152876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
25162876592fSMel Gorman 		 * the resulting allocation attempt fails
25172876592fSMel Gorman 		 */
25182876592fSMel Gorman 		if (!nr_reclaimed)
25192876592fSMel Gorman 			return false;
25202876592fSMel Gorman 	}
25213e7d3449SMel Gorman 
25223e7d3449SMel Gorman 	/*
25233e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
25243e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
25253e7d3449SMel Gorman 	 */
25269861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2527a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2528ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2529a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
25303e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
25313e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
25323e7d3449SMel Gorman 		return true;
25333e7d3449SMel Gorman 
25343e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2535a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2536a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25376aa303deSMel Gorman 		if (!managed_zone(zone))
2538a9dd0a83SMel Gorman 			continue;
2539a9dd0a83SMel Gorman 
2540a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2541cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25423e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25433e7d3449SMel Gorman 			return false;
25443e7d3449SMel Gorman 		default:
2545a9dd0a83SMel Gorman 			/* check next zone */
2546a9dd0a83SMel Gorman 			;
25473e7d3449SMel Gorman 		}
25483e7d3449SMel Gorman 	}
2549a9dd0a83SMel Gorman 	return true;
2550a9dd0a83SMel Gorman }
25513e7d3449SMel Gorman 
2552970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2553f16015fbSJohannes Weiner {
2554cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25559b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25562344d7e4SJohannes Weiner 	bool reclaimable = false;
25579b4f98cdSJohannes Weiner 
25589b4f98cdSJohannes Weiner 	do {
25595660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25605660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2561ef8f2327SMel Gorman 			.pgdat = pgdat,
25629e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25635660048cSJohannes Weiner 		};
2564a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2565694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25665660048cSJohannes Weiner 
25679b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25689b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25699b4f98cdSJohannes Weiner 
2570694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2571694fbc0fSAndrew Morton 		do {
25726b4f7799SJohannes Weiner 			unsigned long lru_pages;
25738e8ae645SJohannes Weiner 			unsigned long reclaimed;
2574cb731d6cSVladimir Davydov 			unsigned long scanned;
25759b4f98cdSJohannes Weiner 
2576241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2577d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2578d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2579241994edSJohannes Weiner 					continue;
2580d6622f63SYisheng Xie 				}
258131176c78SJohannes Weiner 				mem_cgroup_event(memcg, MEMCG_LOW);
2582241994edSJohannes Weiner 			}
2583241994edSJohannes Weiner 
25848e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2585cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
25865660048cSJohannes Weiner 
2587a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2588a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2589f9be23d6SKonstantin Khlebnikov 
2590b5afba29SVladimir Davydov 			if (memcg)
2591a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
2592cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2593cb731d6cSVladimir Davydov 					    lru_pages);
2594cb731d6cSVladimir Davydov 
25958e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25968e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25978e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25988e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25998e8ae645SJohannes Weiner 
26005660048cSJohannes Weiner 			/*
2601a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2602a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2603a9dd0a83SMel Gorman 			 * node.
2604a394cb8eSMichal Hocko 			 *
2605a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2606a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2607a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2608a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
26095660048cSJohannes Weiner 			 */
2610a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2611a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
26125660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
26135660048cSJohannes Weiner 				break;
26145660048cSJohannes Weiner 			}
2615241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
261670ddf637SAnton Vorontsov 
26176b4f7799SJohannes Weiner 		/*
26186b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
26196b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
26206b4f7799SJohannes Weiner 		 */
2621b2e18757SMel Gorman 		if (global_reclaim(sc))
2622a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
26236b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
2624a9dd0a83SMel Gorman 				    node_lru_pages);
26256b4f7799SJohannes Weiner 
26266b4f7799SJohannes Weiner 		if (reclaim_state) {
2627cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
26286b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
26296b4f7799SJohannes Weiner 		}
26306b4f7799SJohannes Weiner 
26318e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
26328e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
263370ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
263470ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
263570ddf637SAnton Vorontsov 
26362344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
26372344d7e4SJohannes Weiner 			reclaimable = true;
26382344d7e4SJohannes Weiner 
2639a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
26409b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
26412344d7e4SJohannes Weiner 
2642c73322d0SJohannes Weiner 	/*
2643c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2644c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2645c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2646c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2647c73322d0SJohannes Weiner 	 */
2648c73322d0SJohannes Weiner 	if (reclaimable)
2649c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2650c73322d0SJohannes Weiner 
26512344d7e4SJohannes Weiner 	return reclaimable;
2652f16015fbSJohannes Weiner }
2653f16015fbSJohannes Weiner 
265453853e2dSVlastimil Babka /*
2655fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2656fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2657fdd4c614SVlastimil Babka  * should reclaim first.
265853853e2dSVlastimil Babka  */
26594f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2660fe4b1b24SMel Gorman {
266131483b6aSMel Gorman 	unsigned long watermark;
2662fdd4c614SVlastimil Babka 	enum compact_result suitable;
2663fe4b1b24SMel Gorman 
2664fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2665fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2666fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2667fdd4c614SVlastimil Babka 		return true;
2668fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2669fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2670fe4b1b24SMel Gorman 		return false;
2671fe4b1b24SMel Gorman 
2672fdd4c614SVlastimil Babka 	/*
2673fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2674fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2675fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2676fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2677fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2678fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2679fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2680fdd4c614SVlastimil Babka 	 */
2681fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2682fdd4c614SVlastimil Babka 
2683fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2684fe4b1b24SMel Gorman }
2685fe4b1b24SMel Gorman 
26861da177e4SLinus Torvalds /*
26871da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
26881da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
26891da177e4SLinus Torvalds  * request.
26901da177e4SLinus Torvalds  *
26911da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
26921da177e4SLinus Torvalds  * scan then give up on it.
26931da177e4SLinus Torvalds  */
26940a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
26951da177e4SLinus Torvalds {
2696dd1a239fSMel Gorman 	struct zoneref *z;
269754a6eb5cSMel Gorman 	struct zone *zone;
26980608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26990608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2700619d0d76SWeijie Yang 	gfp_t orig_mask;
270179dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
27021cfb419bSKAMEZAWA Hiroyuki 
2703cc715d99SMel Gorman 	/*
2704cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2705cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2706cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2707cc715d99SMel Gorman 	 */
2708619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2709b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2710cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
27114f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2712b2e18757SMel Gorman 	}
2713cc715d99SMel Gorman 
2714d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2715b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2716b2e18757SMel Gorman 		/*
27171cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
27181cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
27191cfb419bSKAMEZAWA Hiroyuki 		 */
272089b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2721344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2722344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
27231da177e4SLinus Torvalds 				continue;
272465ec02cbSVladimir Davydov 
2725e0887c19SRik van Riel 			/*
2726e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2727e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2728e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2729e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2730e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2731c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2732c7cfa37bSCopot Alexandru 			 * page allocations.
2733e0887c19SRik van Riel 			 */
27340b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
27350b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
27364f588331SMel Gorman 			    compaction_ready(zone, sc)) {
27370b06496aSJohannes Weiner 				sc->compaction_ready = true;
2738e0887c19SRik van Riel 				continue;
2739e0887c19SRik van Riel 			}
27400b06496aSJohannes Weiner 
27410608f43dSAndrew Morton 			/*
274279dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
274379dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
274479dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
274579dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
274679dafcdcSMel Gorman 			 */
274779dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
274879dafcdcSMel Gorman 				continue;
274979dafcdcSMel Gorman 
275079dafcdcSMel Gorman 			/*
27510608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27520608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27530608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27540608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27550608f43dSAndrew Morton 			 */
27560608f43dSAndrew Morton 			nr_soft_scanned = 0;
2757ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27580608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27590608f43dSAndrew Morton 						&nr_soft_scanned);
27600608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27610608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2762ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2763ac34a1a3SKAMEZAWA Hiroyuki 		}
2764d149e3b2SYing Han 
276579dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
276679dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
276779dafcdcSMel Gorman 			continue;
276879dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2769970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27701da177e4SLinus Torvalds 	}
2771e0c23279SMel Gorman 
277265ec02cbSVladimir Davydov 	/*
2773619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2774619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2775619d0d76SWeijie Yang 	 */
2776619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27771da177e4SLinus Torvalds }
27781da177e4SLinus Torvalds 
27792a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
27802a2e4885SJohannes Weiner {
27812a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
27822a2e4885SJohannes Weiner 
27832a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
27842a2e4885SJohannes Weiner 	do {
27852a2e4885SJohannes Weiner 		unsigned long refaults;
27862a2e4885SJohannes Weiner 		struct lruvec *lruvec;
27872a2e4885SJohannes Weiner 
27882a2e4885SJohannes Weiner 		if (memcg)
2789ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
27902a2e4885SJohannes Weiner 		else
27912a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
27922a2e4885SJohannes Weiner 
27932a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
27942a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
27952a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
27962a2e4885SJohannes Weiner }
27972a2e4885SJohannes Weiner 
27981da177e4SLinus Torvalds /*
27991da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
28001da177e4SLinus Torvalds  *
28011da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
28021da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
28031da177e4SLinus Torvalds  *
28041da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
28051da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
28065b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
28075b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
28085b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
28095b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2810a41f24eaSNishanth Aravamudan  *
2811a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2812a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
28131da177e4SLinus Torvalds  */
2814dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
28153115cd91SVladimir Davydov 					  struct scan_control *sc)
28161da177e4SLinus Torvalds {
2817241994edSJohannes Weiner 	int initial_priority = sc->priority;
28182a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
28192a2e4885SJohannes Weiner 	struct zoneref *z;
28202a2e4885SJohannes Weiner 	struct zone *zone;
2821241994edSJohannes Weiner retry:
2822873b4771SKeika Kobayashi 	delayacct_freepages_start();
2823873b4771SKeika Kobayashi 
282489b5fae5SJohannes Weiner 	if (global_reclaim(sc))
28257cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
28261da177e4SLinus Torvalds 
28279e3b2f8cSKonstantin Khlebnikov 	do {
282870ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
282970ddf637SAnton Vorontsov 				sc->priority);
283066e1707bSBalbir Singh 		sc->nr_scanned = 0;
28310a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2832e0c23279SMel Gorman 
2833bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
28340b06496aSJohannes Weiner 			break;
28350b06496aSJohannes Weiner 
28360b06496aSJohannes Weiner 		if (sc->compaction_ready)
28370b06496aSJohannes Weiner 			break;
28381da177e4SLinus Torvalds 
28391da177e4SLinus Torvalds 		/*
28400e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
28410e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
28420e50ce3bSMinchan Kim 		 */
28430e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
28440e50ce3bSMinchan Kim 			sc->may_writepage = 1;
28450b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2846bb21c7ceSKOSAKI Motohiro 
28472a2e4885SJohannes Weiner 	last_pgdat = NULL;
28482a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
28492a2e4885SJohannes Weiner 					sc->nodemask) {
28502a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
28512a2e4885SJohannes Weiner 			continue;
28522a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
28532a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
28542a2e4885SJohannes Weiner 	}
28552a2e4885SJohannes Weiner 
2856873b4771SKeika Kobayashi 	delayacct_freepages_end();
2857873b4771SKeika Kobayashi 
2858bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2859bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2860bb21c7ceSKOSAKI Motohiro 
28610cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
28620b06496aSJohannes Weiner 	if (sc->compaction_ready)
28637335084dSMel Gorman 		return 1;
28647335084dSMel Gorman 
2865241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2866d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
2867241994edSJohannes Weiner 		sc->priority = initial_priority;
2868d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
2869d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
2870241994edSJohannes Weiner 		goto retry;
2871241994edSJohannes Weiner 	}
2872241994edSJohannes Weiner 
2873bb21c7ceSKOSAKI Motohiro 	return 0;
28741da177e4SLinus Torvalds }
28751da177e4SLinus Torvalds 
2876c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
28775515061dSMel Gorman {
28785515061dSMel Gorman 	struct zone *zone;
28795515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
28805515061dSMel Gorman 	unsigned long free_pages = 0;
28815515061dSMel Gorman 	int i;
28825515061dSMel Gorman 	bool wmark_ok;
28835515061dSMel Gorman 
2884c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
2885c73322d0SJohannes Weiner 		return true;
2886c73322d0SJohannes Weiner 
28875515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
28885515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2889d450abd8SJohannes Weiner 		if (!managed_zone(zone))
2890d450abd8SJohannes Weiner 			continue;
2891d450abd8SJohannes Weiner 
2892d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
2893675becceSMel Gorman 			continue;
2894675becceSMel Gorman 
28955515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
28965515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
28975515061dSMel Gorman 	}
28985515061dSMel Gorman 
2899675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2900675becceSMel Gorman 	if (!pfmemalloc_reserve)
2901675becceSMel Gorman 		return true;
2902675becceSMel Gorman 
29035515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
29045515061dSMel Gorman 
29055515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
29065515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
290738087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
29085515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
29095515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
29105515061dSMel Gorman 	}
29115515061dSMel Gorman 
29125515061dSMel Gorman 	return wmark_ok;
29135515061dSMel Gorman }
29145515061dSMel Gorman 
29155515061dSMel Gorman /*
29165515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
29175515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
29185515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
291950694c28SMel Gorman  * when the low watermark is reached.
292050694c28SMel Gorman  *
292150694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
292250694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
29235515061dSMel Gorman  */
292450694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
29255515061dSMel Gorman 					nodemask_t *nodemask)
29265515061dSMel Gorman {
2927675becceSMel Gorman 	struct zoneref *z;
29285515061dSMel Gorman 	struct zone *zone;
2929675becceSMel Gorman 	pg_data_t *pgdat = NULL;
29305515061dSMel Gorman 
29315515061dSMel Gorman 	/*
29325515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
29335515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
29345515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
29355515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
29365515061dSMel Gorman 	 * processes to block on log_wait_commit().
29375515061dSMel Gorman 	 */
29385515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
293950694c28SMel Gorman 		goto out;
294050694c28SMel Gorman 
294150694c28SMel Gorman 	/*
294250694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
294350694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
294450694c28SMel Gorman 	 */
294550694c28SMel Gorman 	if (fatal_signal_pending(current))
294650694c28SMel Gorman 		goto out;
29475515061dSMel Gorman 
2948675becceSMel Gorman 	/*
2949675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2950675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2951675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2952675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2953675becceSMel Gorman 	 *
2954675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2955675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2956675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2957675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2958675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2959675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2960675becceSMel Gorman 	 * should make reasonable progress.
2961675becceSMel Gorman 	 */
2962675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
296317636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2964675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2965675becceSMel Gorman 			continue;
2966675becceSMel Gorman 
2967675becceSMel Gorman 		/* Throttle based on the first usable node */
29685515061dSMel Gorman 		pgdat = zone->zone_pgdat;
2969c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
297050694c28SMel Gorman 			goto out;
2971675becceSMel Gorman 		break;
2972675becceSMel Gorman 	}
2973675becceSMel Gorman 
2974675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2975675becceSMel Gorman 	if (!pgdat)
2976675becceSMel Gorman 		goto out;
29775515061dSMel Gorman 
297868243e76SMel Gorman 	/* Account for the throttling */
297968243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
298068243e76SMel Gorman 
29815515061dSMel Gorman 	/*
29825515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
29835515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
29845515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
29855515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
29865515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
29875515061dSMel Gorman 	 * second before continuing.
29885515061dSMel Gorman 	 */
29895515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
29905515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2991c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
299250694c28SMel Gorman 
299350694c28SMel Gorman 		goto check_pending;
29945515061dSMel Gorman 	}
29955515061dSMel Gorman 
29965515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
29975515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2998c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
299950694c28SMel Gorman 
300050694c28SMel Gorman check_pending:
300150694c28SMel Gorman 	if (fatal_signal_pending(current))
300250694c28SMel Gorman 		return true;
300350694c28SMel Gorman 
300450694c28SMel Gorman out:
300550694c28SMel Gorman 	return false;
30065515061dSMel Gorman }
30075515061dSMel Gorman 
3008dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3009327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
301066e1707bSBalbir Singh {
301133906bc5SMel Gorman 	unsigned long nr_reclaimed;
301266e1707bSBalbir Singh 	struct scan_control sc = {
301322fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3014f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3015b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3016ee814fe2SJohannes Weiner 		.order = order,
3017ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3018ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3019ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3020a6dc60f8SJohannes Weiner 		.may_unmap = 1,
30212e2e4259SKOSAKI Motohiro 		.may_swap = 1,
302266e1707bSBalbir Singh 	};
302366e1707bSBalbir Singh 
30245515061dSMel Gorman 	/*
302550694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
302650694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
302750694c28SMel Gorman 	 * point.
30285515061dSMel Gorman 	 */
3029f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
30305515061dSMel Gorman 		return 1;
30315515061dSMel Gorman 
303233906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
303333906bc5SMel Gorman 				sc.may_writepage,
3034f2f43e56SNick Desaulniers 				sc.gfp_mask,
3035e5146b12SMel Gorman 				sc.reclaim_idx);
303633906bc5SMel Gorman 
30373115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
303833906bc5SMel Gorman 
303933906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
304033906bc5SMel Gorman 
304133906bc5SMel Gorman 	return nr_reclaimed;
304266e1707bSBalbir Singh }
304366e1707bSBalbir Singh 
3044c255a458SAndrew Morton #ifdef CONFIG_MEMCG
304566e1707bSBalbir Singh 
3046a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
30474e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3048ef8f2327SMel Gorman 						pg_data_t *pgdat,
30490ae5e89cSYing Han 						unsigned long *nr_scanned)
30504e416953SBalbir Singh {
30514e416953SBalbir Singh 	struct scan_control sc = {
3052b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3053ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
30544e416953SBalbir Singh 		.may_writepage = !laptop_mode,
30554e416953SBalbir Singh 		.may_unmap = 1,
3056b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
30574e416953SBalbir Singh 		.may_swap = !noswap,
30584e416953SBalbir Singh 	};
30596b4f7799SJohannes Weiner 	unsigned long lru_pages;
30600ae5e89cSYing Han 
30614e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
30624e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3063bdce6d9eSKOSAKI Motohiro 
30649e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3065bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3066e5146b12SMel Gorman 						      sc.gfp_mask,
3067e5146b12SMel Gorman 						      sc.reclaim_idx);
3068bdce6d9eSKOSAKI Motohiro 
30694e416953SBalbir Singh 	/*
30704e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
30714e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3072a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30734e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
30744e416953SBalbir Singh 	 * the priority and make it zero.
30754e416953SBalbir Singh 	 */
3076ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3077bdce6d9eSKOSAKI Motohiro 
3078bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3079bdce6d9eSKOSAKI Motohiro 
30800ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
30814e416953SBalbir Singh 	return sc.nr_reclaimed;
30824e416953SBalbir Singh }
30834e416953SBalbir Singh 
308472835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3085b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
30868c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3087b70a2a21SJohannes Weiner 					   bool may_swap)
308866e1707bSBalbir Singh {
30894e416953SBalbir Singh 	struct zonelist *zonelist;
3090bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3091889976dbSYing Han 	int nid;
3092499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
309366e1707bSBalbir Singh 	struct scan_control sc = {
3094b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
30957dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3096ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3097b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3098ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3099ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
310066e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3101a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3102b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3103a09ed5e0SYing Han 	};
310466e1707bSBalbir Singh 
3105889976dbSYing Han 	/*
3106889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3107889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3108889976dbSYing Han 	 * scan does not need to be the current node.
3109889976dbSYing Han 	 */
311072835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3111889976dbSYing Han 
3112c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3113bdce6d9eSKOSAKI Motohiro 
3114bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3115bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3116e5146b12SMel Gorman 					    sc.gfp_mask,
3117e5146b12SMel Gorman 					    sc.reclaim_idx);
3118bdce6d9eSKOSAKI Motohiro 
3119499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
31203115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3121499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3122bdce6d9eSKOSAKI Motohiro 
3123bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3124bdce6d9eSKOSAKI Motohiro 
3125bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
312666e1707bSBalbir Singh }
312766e1707bSBalbir Singh #endif
312866e1707bSBalbir Singh 
31291d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3130ef8f2327SMel Gorman 				struct scan_control *sc)
3131f16015fbSJohannes Weiner {
3132b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3133b95a2f2dSJohannes Weiner 
3134b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3135b95a2f2dSJohannes Weiner 		return;
3136b95a2f2dSJohannes Weiner 
3137b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3138b95a2f2dSJohannes Weiner 	do {
3139ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3140f16015fbSJohannes Weiner 
31412a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
31421a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
31439e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3144b95a2f2dSJohannes Weiner 
3145b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3146b95a2f2dSJohannes Weiner 	} while (memcg);
3147f16015fbSJohannes Weiner }
3148f16015fbSJohannes Weiner 
3149e716f2ebSMel Gorman /*
3150e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3151e716f2ebSMel Gorman  * and classzone_idx
3152e716f2ebSMel Gorman  */
3153e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
315460cefed4SJohannes Weiner {
3155e716f2ebSMel Gorman 	int i;
3156e716f2ebSMel Gorman 	unsigned long mark = -1;
3157e716f2ebSMel Gorman 	struct zone *zone;
315860cefed4SJohannes Weiner 
3159e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3160e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
31616256c6b4SMel Gorman 
3162e716f2ebSMel Gorman 		if (!managed_zone(zone))
3163e716f2ebSMel Gorman 			continue;
3164e716f2ebSMel Gorman 
3165e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3166e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
31676256c6b4SMel Gorman 			return true;
316860cefed4SJohannes Weiner 	}
316960cefed4SJohannes Weiner 
3170e716f2ebSMel Gorman 	/*
3171e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3172e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3173e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3174e716f2ebSMel Gorman 	 */
3175e716f2ebSMel Gorman 	if (mark == -1)
3176e716f2ebSMel Gorman 		return true;
3177e716f2ebSMel Gorman 
3178e716f2ebSMel Gorman 	return false;
3179e716f2ebSMel Gorman }
3180e716f2ebSMel Gorman 
3181631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3182631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3183631b6e08SMel Gorman {
3184631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3185631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3186631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3187631b6e08SMel Gorman }
3188631b6e08SMel Gorman 
31891741c877SMel Gorman /*
31905515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
31915515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
31925515061dSMel Gorman  *
31935515061dSMel Gorman  * Returns true if kswapd is ready to sleep
31945515061dSMel Gorman  */
3195d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3196f50de2d3SMel Gorman {
31975515061dSMel Gorman 	/*
31989e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3199c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
32009e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
32019e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
32029e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
32039e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
32049e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
32059e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
32069e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
32079e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
32089e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
32095515061dSMel Gorman 	 */
32109e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
32119e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3212f50de2d3SMel Gorman 
3213c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3214c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3215c73322d0SJohannes Weiner 		return true;
3216c73322d0SJohannes Weiner 
3217e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3218631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3219333b0a45SShantanu Goel 		return true;
32201d82de61SMel Gorman 	}
32211d82de61SMel Gorman 
3222333b0a45SShantanu Goel 	return false;
3223f50de2d3SMel Gorman }
3224f50de2d3SMel Gorman 
32251da177e4SLinus Torvalds /*
32261d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
32271d82de61SMel Gorman  * zone that is currently unbalanced.
3228b8e83b94SMel Gorman  *
3229b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3230283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3231283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
323275485363SMel Gorman  */
32331d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3234accf6242SVlastimil Babka 			       struct scan_control *sc)
323575485363SMel Gorman {
32361d82de61SMel Gorman 	struct zone *zone;
32371d82de61SMel Gorman 	int z;
323875485363SMel Gorman 
32391d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
32401d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3241970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
32421d82de61SMel Gorman 		zone = pgdat->node_zones + z;
32436aa303deSMel Gorman 		if (!managed_zone(zone))
32441d82de61SMel Gorman 			continue;
32457c954f6dSMel Gorman 
32461d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
32477c954f6dSMel Gorman 	}
32487c954f6dSMel Gorman 
32491d82de61SMel Gorman 	/*
32501d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
32511d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
32521d82de61SMel Gorman 	 */
3253970a39a3SMel Gorman 	shrink_node(pgdat, sc);
32541d82de61SMel Gorman 
32551d82de61SMel Gorman 	/*
32561d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
32571d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
32581d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
32591d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
32601d82de61SMel Gorman 	 * can direct reclaim/compact.
32611d82de61SMel Gorman 	 */
32629861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
32631d82de61SMel Gorman 		sc->order = 0;
32641d82de61SMel Gorman 
3265b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
326675485363SMel Gorman }
326775485363SMel Gorman 
326875485363SMel Gorman /*
32691d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
32701d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
32711d82de61SMel Gorman  * balanced.
32721da177e4SLinus Torvalds  *
32731d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
32741da177e4SLinus Torvalds  *
32751da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
327641858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
32771d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
32781d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
32791d82de61SMel Gorman  * balanced.
32801da177e4SLinus Torvalds  */
3281accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
32821da177e4SLinus Torvalds {
32831da177e4SLinus Torvalds 	int i;
32840608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
32850608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
32861d82de61SMel Gorman 	struct zone *zone;
3287179e9639SAndrew Morton 	struct scan_control sc = {
3288179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3289ee814fe2SJohannes Weiner 		.order = order,
3290b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3291ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3292a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32932e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3294179e9639SAndrew Morton 	};
3295f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
32961da177e4SLinus Torvalds 
32979e3b2f8cSKonstantin Khlebnikov 	do {
3298c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3299b8e83b94SMel Gorman 		bool raise_priority = true;
3300b8e83b94SMel Gorman 
330184c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
33021da177e4SLinus Torvalds 
330386c79f6bSMel Gorman 		/*
330484c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
330584c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
330684c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
330784c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
330884c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
330984c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
331084c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
331184c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
331286c79f6bSMel Gorman 		 */
331386c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
331486c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
331586c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
33166aa303deSMel Gorman 				if (!managed_zone(zone))
331786c79f6bSMel Gorman 					continue;
331886c79f6bSMel Gorman 
3319970a39a3SMel Gorman 				sc.reclaim_idx = i;
332086c79f6bSMel Gorman 				break;
332186c79f6bSMel Gorman 			}
332286c79f6bSMel Gorman 		}
332386c79f6bSMel Gorman 
332486c79f6bSMel Gorman 		/*
3325e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3326e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3327e716f2ebSMel Gorman 		 * have adjusted it.
332886c79f6bSMel Gorman 		 */
3329e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
33301da177e4SLinus Torvalds 			goto out;
3331e1dbeda6SAndrew Morton 
33321da177e4SLinus Torvalds 		/*
33331d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
33341d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
33351d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
33361d82de61SMel Gorman 		 * about consistent aging.
33371d82de61SMel Gorman 		 */
3338ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
33391d82de61SMel Gorman 
33401d82de61SMel Gorman 		/*
3341b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3342b7ea3c41SMel Gorman 		 * even in laptop mode.
3343b7ea3c41SMel Gorman 		 */
3344047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3345b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3346b7ea3c41SMel Gorman 
33471d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
33481da177e4SLinus Torvalds 		sc.nr_scanned = 0;
33490608f43dSAndrew Morton 		nr_soft_scanned = 0;
3350ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
33511d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
33520608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
33530608f43dSAndrew Morton 
335432a4330dSRik van Riel 		/*
33551d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
33561d82de61SMel Gorman 		 * enough pages are already being scanned that that high
33571d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
335832a4330dSRik van Riel 		 */
3359970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3360b8e83b94SMel Gorman 			raise_priority = false;
3361d7868daeSMel Gorman 
33625515061dSMel Gorman 		/*
33635515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
33645515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
33655515061dSMel Gorman 		 * able to safely make forward progress. Wake them
33665515061dSMel Gorman 		 */
33675515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3368c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3369cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
33705515061dSMel Gorman 
3371b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3372b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3373b8e83b94SMel Gorman 			break;
3374b8e83b94SMel Gorman 
3375b8e83b94SMel Gorman 		/*
3376b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3377b8e83b94SMel Gorman 		 * progress in reclaiming pages
3378b8e83b94SMel Gorman 		 */
3379c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3380c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3381b8e83b94SMel Gorman 			sc.priority--;
33821d82de61SMel Gorman 	} while (sc.priority >= 1);
33831da177e4SLinus Torvalds 
3384c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3385c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3386c73322d0SJohannes Weiner 
3387b8e83b94SMel Gorman out:
33882a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
33890abdee2bSMel Gorman 	/*
33901d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
33911d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
33921d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
33931d82de61SMel Gorman 	 * remain at the higher level.
33940abdee2bSMel Gorman 	 */
33951d82de61SMel Gorman 	return sc.order;
33961da177e4SLinus Torvalds }
33971da177e4SLinus Torvalds 
3398e716f2ebSMel Gorman /*
3399e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3400e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3401e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3402e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3403e716f2ebSMel Gorman  * was recently woke for.
3404e716f2ebSMel Gorman  */
3405e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3406e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3407e716f2ebSMel Gorman {
3408e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3409e716f2ebSMel Gorman 		return classzone_idx;
3410e716f2ebSMel Gorman 
3411e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3412e716f2ebSMel Gorman }
3413e716f2ebSMel Gorman 
341438087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
341538087d9bSMel Gorman 				unsigned int classzone_idx)
3416f0bc0a60SKOSAKI Motohiro {
3417f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3418f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3419f0bc0a60SKOSAKI Motohiro 
3420f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3421f0bc0a60SKOSAKI Motohiro 		return;
3422f0bc0a60SKOSAKI Motohiro 
3423f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3424f0bc0a60SKOSAKI Motohiro 
3425333b0a45SShantanu Goel 	/*
3426333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3427333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3428333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3429333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3430333b0a45SShantanu Goel 	 * succeed.
3431333b0a45SShantanu Goel 	 */
3432d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3433fd901c95SVlastimil Babka 		/*
3434fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3435fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3436fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3437fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3438fd901c95SVlastimil Babka 		 */
3439fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3440fd901c95SVlastimil Babka 
3441fd901c95SVlastimil Babka 		/*
3442fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3443fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3444fd901c95SVlastimil Babka 		 */
344538087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3446fd901c95SVlastimil Babka 
3447f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
344838087d9bSMel Gorman 
344938087d9bSMel Gorman 		/*
345038087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
345138087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
345238087d9bSMel Gorman 		 * the previous request that slept prematurely.
345338087d9bSMel Gorman 		 */
345438087d9bSMel Gorman 		if (remaining) {
3455e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
345638087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
345738087d9bSMel Gorman 		}
345838087d9bSMel Gorman 
3459f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3460f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3461f0bc0a60SKOSAKI Motohiro 	}
3462f0bc0a60SKOSAKI Motohiro 
3463f0bc0a60SKOSAKI Motohiro 	/*
3464f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3465f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3466f0bc0a60SKOSAKI Motohiro 	 */
3467d9f21d42SMel Gorman 	if (!remaining &&
3468d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3469f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3470f0bc0a60SKOSAKI Motohiro 
3471f0bc0a60SKOSAKI Motohiro 		/*
3472f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3473f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3474f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3475f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3476f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3477f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3478f0bc0a60SKOSAKI Motohiro 		 */
3479f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
34801c7e7f6cSAaditya Kumar 
34811c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3482f0bc0a60SKOSAKI Motohiro 			schedule();
34831c7e7f6cSAaditya Kumar 
3484f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3485f0bc0a60SKOSAKI Motohiro 	} else {
3486f0bc0a60SKOSAKI Motohiro 		if (remaining)
3487f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3488f0bc0a60SKOSAKI Motohiro 		else
3489f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3490f0bc0a60SKOSAKI Motohiro 	}
3491f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3492f0bc0a60SKOSAKI Motohiro }
3493f0bc0a60SKOSAKI Motohiro 
34941da177e4SLinus Torvalds /*
34951da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
34961da177e4SLinus Torvalds  * from the init process.
34971da177e4SLinus Torvalds  *
34981da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
34991da177e4SLinus Torvalds  * free memory available even if there is no other activity
35001da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
35011da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
35021da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
35031da177e4SLinus Torvalds  *
35041da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
35051da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
35061da177e4SLinus Torvalds  */
35071da177e4SLinus Torvalds static int kswapd(void *p)
35081da177e4SLinus Torvalds {
3509e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3510e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
35111da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
35121da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3513f0bc0a60SKOSAKI Motohiro 
35141da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
35151da177e4SLinus Torvalds 		.reclaimed_slab = 0,
35161da177e4SLinus Torvalds 	};
3517a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
35181da177e4SLinus Torvalds 
3519cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3520cf40bd16SNick Piggin 
3521174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3522c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
35231da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
35241da177e4SLinus Torvalds 
35251da177e4SLinus Torvalds 	/*
35261da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
35271da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
35281da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
35291da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
35301da177e4SLinus Torvalds 	 *
35311da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
35321da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
35331da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
35341da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
35351da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
35361da177e4SLinus Torvalds 	 */
3537930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
353883144186SRafael J. Wysocki 	set_freezable();
35391da177e4SLinus Torvalds 
3540e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3541e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35421da177e4SLinus Torvalds 	for ( ; ; ) {
35436f6313d4SJeff Liu 		bool ret;
35443e1d1d28SChristoph Lameter 
3545e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3546e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3547e716f2ebSMel Gorman 
354838087d9bSMel Gorman kswapd_try_sleep:
354938087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
355038087d9bSMel Gorman 					classzone_idx);
3551215ddd66SMel Gorman 
355238087d9bSMel Gorman 		/* Read the new order and classzone_idx */
355338087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3554e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
355538087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3556e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35571da177e4SLinus Torvalds 
35588fe23e05SDavid Rientjes 		ret = try_to_freeze();
35598fe23e05SDavid Rientjes 		if (kthread_should_stop())
35608fe23e05SDavid Rientjes 			break;
35618fe23e05SDavid Rientjes 
35628fe23e05SDavid Rientjes 		/*
35638fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
35648fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3565b1296cc4SRafael J. Wysocki 		 */
356638087d9bSMel Gorman 		if (ret)
356738087d9bSMel Gorman 			continue;
35681d82de61SMel Gorman 
356938087d9bSMel Gorman 		/*
357038087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
357138087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
357238087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
357338087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
357438087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
357538087d9bSMel Gorman 		 * request (alloc_order).
357638087d9bSMel Gorman 		 */
3577e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3578e5146b12SMel Gorman 						alloc_order);
357938087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
358038087d9bSMel Gorman 		if (reclaim_order < alloc_order)
358138087d9bSMel Gorman 			goto kswapd_try_sleep;
358233906bc5SMel Gorman 	}
3583b0a8cc58STakamori Yamaguchi 
358471abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3585b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
358671abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
358771abdc15SJohannes Weiner 
35881da177e4SLinus Torvalds 	return 0;
35891da177e4SLinus Torvalds }
35901da177e4SLinus Torvalds 
35911da177e4SLinus Torvalds /*
35921da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
35931da177e4SLinus Torvalds  */
359499504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
35951da177e4SLinus Torvalds {
35961da177e4SLinus Torvalds 	pg_data_t *pgdat;
35971da177e4SLinus Torvalds 
35986aa303deSMel Gorman 	if (!managed_zone(zone))
35991da177e4SLinus Torvalds 		return;
36001da177e4SLinus Torvalds 
3601344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
36021da177e4SLinus Torvalds 		return;
360388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3604e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3605e716f2ebSMel Gorman 							   classzone_idx);
360638087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
36078d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
36081da177e4SLinus Torvalds 		return;
3609e1a55637SMel Gorman 
3610c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3611c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3612c73322d0SJohannes Weiner 		return;
3613c73322d0SJohannes Weiner 
3614e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx))
361588f5acf8SMel Gorman 		return;
361688f5acf8SMel Gorman 
3617e716f2ebSMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order);
36188d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
36191da177e4SLinus Torvalds }
36201da177e4SLinus Torvalds 
3621c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
36221da177e4SLinus Torvalds /*
36237b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3624d6277db4SRafael J. Wysocki  * freed pages.
3625d6277db4SRafael J. Wysocki  *
3626d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3627d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3628d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
36291da177e4SLinus Torvalds  */
36307b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
36311da177e4SLinus Torvalds {
3632d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3633d6277db4SRafael J. Wysocki 	struct scan_control sc = {
36347b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3635ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3636b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
36379e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3638ee814fe2SJohannes Weiner 		.may_writepage = 1,
3639ee814fe2SJohannes Weiner 		.may_unmap = 1,
3640ee814fe2SJohannes Weiner 		.may_swap = 1,
3641ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
36421da177e4SLinus Torvalds 	};
36437b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
36447b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
36457b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3646499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
36471da177e4SLinus Torvalds 
3648499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
36497b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3650d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
36517b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3652d6277db4SRafael J. Wysocki 
36533115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3654d6277db4SRafael J. Wysocki 
36557b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
36567b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3657499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3658d6277db4SRafael J. Wysocki 
36597b51755cSKOSAKI Motohiro 	return nr_reclaimed;
36601da177e4SLinus Torvalds }
3661c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
36621da177e4SLinus Torvalds 
36631da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
36641da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
36651da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
36661da177e4SLinus Torvalds    restore their cpu bindings. */
3667517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
36681da177e4SLinus Torvalds {
366958c0a4a7SYasunori Goto 	int nid;
36701da177e4SLinus Torvalds 
367148fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3672c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3673a70f7302SRusty Russell 		const struct cpumask *mask;
3674a70f7302SRusty Russell 
3675a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3676c5f59f08SMike Travis 
36773e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
36781da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3679c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
36801da177e4SLinus Torvalds 	}
3681517bbed9SSebastian Andrzej Siewior 	return 0;
36821da177e4SLinus Torvalds }
36831da177e4SLinus Torvalds 
36843218ae14SYasunori Goto /*
36853218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
36863218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
36873218ae14SYasunori Goto  */
36883218ae14SYasunori Goto int kswapd_run(int nid)
36893218ae14SYasunori Goto {
36903218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
36913218ae14SYasunori Goto 	int ret = 0;
36923218ae14SYasunori Goto 
36933218ae14SYasunori Goto 	if (pgdat->kswapd)
36943218ae14SYasunori Goto 		return 0;
36953218ae14SYasunori Goto 
36963218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
36973218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
36983218ae14SYasunori Goto 		/* failure at boot is fatal */
3699c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3700d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3701d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3702d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
37033218ae14SYasunori Goto 	}
37043218ae14SYasunori Goto 	return ret;
37053218ae14SYasunori Goto }
37063218ae14SYasunori Goto 
37078fe23e05SDavid Rientjes /*
3708d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3709bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
37108fe23e05SDavid Rientjes  */
37118fe23e05SDavid Rientjes void kswapd_stop(int nid)
37128fe23e05SDavid Rientjes {
37138fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
37148fe23e05SDavid Rientjes 
3715d8adde17SJiang Liu 	if (kswapd) {
37168fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3717d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3718d8adde17SJiang Liu 	}
37198fe23e05SDavid Rientjes }
37208fe23e05SDavid Rientjes 
37211da177e4SLinus Torvalds static int __init kswapd_init(void)
37221da177e4SLinus Torvalds {
3723517bbed9SSebastian Andrzej Siewior 	int nid, ret;
372469e05944SAndrew Morton 
37251da177e4SLinus Torvalds 	swap_setup();
372648fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
37273218ae14SYasunori Goto  		kswapd_run(nid);
3728517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3729517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3730517bbed9SSebastian Andrzej Siewior 					NULL);
3731517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
37321da177e4SLinus Torvalds 	return 0;
37331da177e4SLinus Torvalds }
37341da177e4SLinus Torvalds 
37351da177e4SLinus Torvalds module_init(kswapd_init)
37369eeff239SChristoph Lameter 
37379eeff239SChristoph Lameter #ifdef CONFIG_NUMA
37389eeff239SChristoph Lameter /*
3739a5f5f91dSMel Gorman  * Node reclaim mode
37409eeff239SChristoph Lameter  *
3741a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
37429eeff239SChristoph Lameter  * the watermarks.
37439eeff239SChristoph Lameter  */
3744a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
37459eeff239SChristoph Lameter 
37461b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
37477d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
37481b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
374995bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
37501b2ffb78SChristoph Lameter 
37519eeff239SChristoph Lameter /*
3752a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3753a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3754a92f7126SChristoph Lameter  * a zone.
3755a92f7126SChristoph Lameter  */
3756a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3757a92f7126SChristoph Lameter 
37589eeff239SChristoph Lameter /*
3759a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
37609614634fSChristoph Lameter  * occur.
37619614634fSChristoph Lameter  */
37629614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
37639614634fSChristoph Lameter 
37649614634fSChristoph Lameter /*
37650ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
37660ff38490SChristoph Lameter  * slab reclaim needs to occur.
37670ff38490SChristoph Lameter  */
37680ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
37690ff38490SChristoph Lameter 
377011fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
377190afa5deSMel Gorman {
377211fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
377311fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
377411fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
377590afa5deSMel Gorman 
377690afa5deSMel Gorman 	/*
377790afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
377890afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
377990afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
378090afa5deSMel Gorman 	 */
378190afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
378290afa5deSMel Gorman }
378390afa5deSMel Gorman 
378490afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3785a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
378690afa5deSMel Gorman {
3787d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3788d031a157SAlexandru Moise 	unsigned long delta = 0;
378990afa5deSMel Gorman 
379090afa5deSMel Gorman 	/*
379195bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
379290afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
379311fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
379490afa5deSMel Gorman 	 * a better estimate
379590afa5deSMel Gorman 	 */
3796a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3797a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
379890afa5deSMel Gorman 	else
3799a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
380090afa5deSMel Gorman 
380190afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3802a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3803a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
380490afa5deSMel Gorman 
380590afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
380690afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
380790afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
380890afa5deSMel Gorman 
380990afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
381090afa5deSMel Gorman }
381190afa5deSMel Gorman 
38120ff38490SChristoph Lameter /*
3813a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
38149eeff239SChristoph Lameter  */
3815a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
38169eeff239SChristoph Lameter {
38177fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
381869e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
38199eeff239SChristoph Lameter 	struct task_struct *p = current;
38209eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3821499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
3822179e9639SAndrew Morton 	struct scan_control sc = {
382362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3824f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3825bd2f6199SJohannes Weiner 		.order = order,
3826a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3827a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3828a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3829ee814fe2SJohannes Weiner 		.may_swap = 1,
3830f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
3831179e9639SAndrew Morton 	};
38329eeff239SChristoph Lameter 
38339eeff239SChristoph Lameter 	cond_resched();
3834d4f7796eSChristoph Lameter 	/*
383595bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3836d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
383795bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3838d4f7796eSChristoph Lameter 	 */
3839499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3840499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
3841f2f43e56SNick Desaulniers 	lockdep_set_current_reclaim_state(sc.gfp_mask);
38429eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
38439eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3844c84db23cSChristoph Lameter 
3845a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3846a92f7126SChristoph Lameter 		/*
38470ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
38480ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3849a92f7126SChristoph Lameter 		 */
3850a92f7126SChristoph Lameter 		do {
3851970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
38529e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
38530ff38490SChristoph Lameter 	}
3854a92f7126SChristoph Lameter 
38559eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3856499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
3857499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
385876ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3859a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
38609eeff239SChristoph Lameter }
3861179e9639SAndrew Morton 
3862a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3863179e9639SAndrew Morton {
3864d773ed6bSDavid Rientjes 	int ret;
3865179e9639SAndrew Morton 
3866179e9639SAndrew Morton 	/*
3867a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
38680ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
386934aa1330SChristoph Lameter 	 *
38709614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
38719614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3872a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3873a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
38749614634fSChristoph Lameter 	 * unmapped file backed pages.
3875179e9639SAndrew Morton 	 */
3876a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3877*385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3878a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3879179e9639SAndrew Morton 
3880179e9639SAndrew Morton 	/*
3881d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3882179e9639SAndrew Morton 	 */
3883d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3884a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3885179e9639SAndrew Morton 
3886179e9639SAndrew Morton 	/*
3887a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3888179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3889179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3890179e9639SAndrew Morton 	 * as wide as possible.
3891179e9639SAndrew Morton 	 */
3892a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3893a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3894d773ed6bSDavid Rientjes 
3895a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3896a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3897fa5e084eSMel Gorman 
3898a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3899a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3900d773ed6bSDavid Rientjes 
390124cf7251SMel Gorman 	if (!ret)
390224cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
390324cf7251SMel Gorman 
3904d773ed6bSDavid Rientjes 	return ret;
3905179e9639SAndrew Morton }
39069eeff239SChristoph Lameter #endif
3907894bc310SLee Schermerhorn 
3908894bc310SLee Schermerhorn /*
3909894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3910894bc310SLee Schermerhorn  * @page: the page to test
3911894bc310SLee Schermerhorn  *
3912894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
391339b5f29aSHugh Dickins  * lists vs unevictable list.
3914894bc310SLee Schermerhorn  *
3915894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3916ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3917b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3918ba9ddf49SLee Schermerhorn  *
3919894bc310SLee Schermerhorn  */
392039b5f29aSHugh Dickins int page_evictable(struct page *page)
3921894bc310SLee Schermerhorn {
392239b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3923894bc310SLee Schermerhorn }
392489e004eaSLee Schermerhorn 
392585046579SHugh Dickins #ifdef CONFIG_SHMEM
392689e004eaSLee Schermerhorn /**
392724513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
392824513264SHugh Dickins  * @pages:	array of pages to check
392924513264SHugh Dickins  * @nr_pages:	number of pages to check
393089e004eaSLee Schermerhorn  *
393124513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
393285046579SHugh Dickins  *
393385046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
393489e004eaSLee Schermerhorn  */
393524513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
393689e004eaSLee Schermerhorn {
3937925b7673SJohannes Weiner 	struct lruvec *lruvec;
3938785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
393924513264SHugh Dickins 	int pgscanned = 0;
394024513264SHugh Dickins 	int pgrescued = 0;
394189e004eaSLee Schermerhorn 	int i;
394289e004eaSLee Schermerhorn 
394324513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
394424513264SHugh Dickins 		struct page *page = pages[i];
3945785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
394689e004eaSLee Schermerhorn 
394724513264SHugh Dickins 		pgscanned++;
3948785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3949785b99feSMel Gorman 			if (pgdat)
3950785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3951785b99feSMel Gorman 			pgdat = pagepgdat;
3952785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
395389e004eaSLee Schermerhorn 		}
3954785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
395589e004eaSLee Schermerhorn 
395624513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
395724513264SHugh Dickins 			continue;
395889e004eaSLee Schermerhorn 
395939b5f29aSHugh Dickins 		if (page_evictable(page)) {
396024513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
396124513264SHugh Dickins 
3962309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
396324513264SHugh Dickins 			ClearPageUnevictable(page);
3964fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3965fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
396624513264SHugh Dickins 			pgrescued++;
396789e004eaSLee Schermerhorn 		}
396889e004eaSLee Schermerhorn 	}
396924513264SHugh Dickins 
3970785b99feSMel Gorman 	if (pgdat) {
397124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
397224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3973785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
397424513264SHugh Dickins 	}
397585046579SHugh Dickins }
397685046579SHugh Dickins #endif /* CONFIG_SHMEM */
3977