xref: /openbmc/linux/mm/vmscan.c (revision b4536f0c829c8586544c94735c343f9b5070bd01)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *  linux/mm/vmscan.c
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
71da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
81da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
91da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
101da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
111da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
121da177e4SLinus Torvalds  */
131da177e4SLinus Torvalds 
14b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15b1de0d13SMitchel Humpherys 
161da177e4SLinus Torvalds #include <linux/mm.h>
171da177e4SLinus Torvalds #include <linux/module.h>
185a0e3ad6STejun Heo #include <linux/gfp.h>
191da177e4SLinus Torvalds #include <linux/kernel_stat.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/pagemap.h>
221da177e4SLinus Torvalds #include <linux/init.h>
231da177e4SLinus Torvalds #include <linux/highmem.h>
2470ddf637SAnton Vorontsov #include <linux/vmpressure.h>
25e129b5c2SAndrew Morton #include <linux/vmstat.h>
261da177e4SLinus Torvalds #include <linux/file.h>
271da177e4SLinus Torvalds #include <linux/writeback.h>
281da177e4SLinus Torvalds #include <linux/blkdev.h>
291da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
301da177e4SLinus Torvalds 					buffer_heads_over_limit */
311da177e4SLinus Torvalds #include <linux/mm_inline.h>
321da177e4SLinus Torvalds #include <linux/backing-dev.h>
331da177e4SLinus Torvalds #include <linux/rmap.h>
341da177e4SLinus Torvalds #include <linux/topology.h>
351da177e4SLinus Torvalds #include <linux/cpu.h>
361da177e4SLinus Torvalds #include <linux/cpuset.h>
373e7d3449SMel Gorman #include <linux/compaction.h>
381da177e4SLinus Torvalds #include <linux/notifier.h>
391da177e4SLinus Torvalds #include <linux/rwsem.h>
40248a0301SRafael J. Wysocki #include <linux/delay.h>
413218ae14SYasunori Goto #include <linux/kthread.h>
427dfb7103SNigel Cunningham #include <linux/freezer.h>
4366e1707bSBalbir Singh #include <linux/memcontrol.h>
44873b4771SKeika Kobayashi #include <linux/delayacct.h>
45af936a16SLee Schermerhorn #include <linux/sysctl.h>
46929bea7cSKOSAKI Motohiro #include <linux/oom.h>
47268bb0ceSLinus Torvalds #include <linux/prefetch.h>
48b1de0d13SMitchel Humpherys #include <linux/printk.h>
49f9fe48beSRoss Zwisler #include <linux/dax.h>
501da177e4SLinus Torvalds 
511da177e4SLinus Torvalds #include <asm/tlbflush.h>
521da177e4SLinus Torvalds #include <asm/div64.h>
531da177e4SLinus Torvalds 
541da177e4SLinus Torvalds #include <linux/swapops.h>
55117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
561da177e4SLinus Torvalds 
570f8053a5SNick Piggin #include "internal.h"
580f8053a5SNick Piggin 
5933906bc5SMel Gorman #define CREATE_TRACE_POINTS
6033906bc5SMel Gorman #include <trace/events/vmscan.h>
6133906bc5SMel Gorman 
621da177e4SLinus Torvalds struct scan_control {
6322fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6422fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6522fba335SKOSAKI Motohiro 
661da177e4SLinus Torvalds 	/* This context's GFP mask */
676daa0e28SAl Viro 	gfp_t gfp_mask;
681da177e4SLinus Torvalds 
69ee814fe2SJohannes Weiner 	/* Allocation order */
705ad333ebSAndy Whitcroft 	int order;
7166e1707bSBalbir Singh 
72ee814fe2SJohannes Weiner 	/*
73ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
74ee814fe2SJohannes Weiner 	 * are scanned.
75ee814fe2SJohannes Weiner 	 */
76ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
779e3b2f8cSKonstantin Khlebnikov 
785f53e762SKOSAKI Motohiro 	/*
79f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
80f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
81f16015fbSJohannes Weiner 	 */
82f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8366e1707bSBalbir Singh 
84ee814fe2SJohannes Weiner 	/* Scan (total_size >> priority) pages at once */
85ee814fe2SJohannes Weiner 	int priority;
86ee814fe2SJohannes Weiner 
87b2e18757SMel Gorman 	/* The highest zone to isolate pages for reclaim from */
88b2e18757SMel Gorman 	enum zone_type reclaim_idx;
89b2e18757SMel Gorman 
90ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
91ee814fe2SJohannes Weiner 
92ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
93ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
94ee814fe2SJohannes Weiner 
95ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
96ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
97ee814fe2SJohannes Weiner 
98241994edSJohannes Weiner 	/* Can cgroups be reclaimed below their normal consumption range? */
99241994edSJohannes Weiner 	unsigned int may_thrash:1;
100241994edSJohannes Weiner 
101ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
102ee814fe2SJohannes Weiner 
103ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
104ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
105ee814fe2SJohannes Weiner 
106ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
107ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
108ee814fe2SJohannes Weiner 
109ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
110ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1111da177e4SLinus Torvalds };
1121da177e4SLinus Torvalds 
1131da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1141da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1151da177e4SLinus Torvalds 	do {								\
1161da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1171da177e4SLinus Torvalds 			struct page *prev;				\
1181da177e4SLinus Torvalds 									\
1191da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1201da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1211da177e4SLinus Torvalds 		}							\
1221da177e4SLinus Torvalds 	} while (0)
1231da177e4SLinus Torvalds #else
1241da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1251da177e4SLinus Torvalds #endif
1261da177e4SLinus Torvalds 
1271da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1281da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1291da177e4SLinus Torvalds 	do {								\
1301da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1311da177e4SLinus Torvalds 			struct page *prev;				\
1321da177e4SLinus Torvalds 									\
1331da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1341da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1351da177e4SLinus Torvalds 		}							\
1361da177e4SLinus Torvalds 	} while (0)
1371da177e4SLinus Torvalds #else
1381da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1391da177e4SLinus Torvalds #endif
1401da177e4SLinus Torvalds 
1411da177e4SLinus Torvalds /*
1421da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1431da177e4SLinus Torvalds  */
1441da177e4SLinus Torvalds int vm_swappiness = 60;
145d0480be4SWang Sheng-Hui /*
146d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
147d0480be4SWang Sheng-Hui  * zones.
148d0480be4SWang Sheng-Hui  */
149d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1501da177e4SLinus Torvalds 
1511da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1521da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1531da177e4SLinus Torvalds 
154c255a458SAndrew Morton #ifdef CONFIG_MEMCG
15589b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
15689b5fae5SJohannes Weiner {
157f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
15889b5fae5SJohannes Weiner }
15997c9341fSTejun Heo 
16097c9341fSTejun Heo /**
16197c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
16297c9341fSTejun Heo  * @sc: scan_control in question
16397c9341fSTejun Heo  *
16497c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
16597c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
16697c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
16797c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
16897c9341fSTejun Heo  * allocation and configurability.
16997c9341fSTejun Heo  *
17097c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
17197c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
17297c9341fSTejun Heo  */
17397c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
17497c9341fSTejun Heo {
17597c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
17697c9341fSTejun Heo 
17797c9341fSTejun Heo 	if (!memcg)
17897c9341fSTejun Heo 		return true;
17997c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
18069234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
18197c9341fSTejun Heo 		return true;
18297c9341fSTejun Heo #endif
18397c9341fSTejun Heo 	return false;
18497c9341fSTejun Heo }
18591a45470SKAMEZAWA Hiroyuki #else
18689b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
18789b5fae5SJohannes Weiner {
18889b5fae5SJohannes Weiner 	return true;
18989b5fae5SJohannes Weiner }
19097c9341fSTejun Heo 
19197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19297c9341fSTejun Heo {
19397c9341fSTejun Heo 	return true;
19497c9341fSTejun Heo }
19591a45470SKAMEZAWA Hiroyuki #endif
19691a45470SKAMEZAWA Hiroyuki 
1975a1c84b4SMel Gorman /*
1985a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
1995a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2005a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2015a1c84b4SMel Gorman  */
2025a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2035a1c84b4SMel Gorman {
2045a1c84b4SMel Gorman 	unsigned long nr;
2055a1c84b4SMel Gorman 
2065a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2075a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2085a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2095a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2105a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2115a1c84b4SMel Gorman 
2125a1c84b4SMel Gorman 	return nr;
2135a1c84b4SMel Gorman }
2145a1c84b4SMel Gorman 
215599d0c95SMel Gorman unsigned long pgdat_reclaimable_pages(struct pglist_data *pgdat)
2166e543d57SLisa Du {
217599d0c95SMel Gorman 	unsigned long nr;
218599d0c95SMel Gorman 
219599d0c95SMel Gorman 	nr = node_page_state_snapshot(pgdat, NR_ACTIVE_FILE) +
220599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_INACTIVE_FILE) +
221599d0c95SMel Gorman 	     node_page_state_snapshot(pgdat, NR_ISOLATED_FILE);
222599d0c95SMel Gorman 
223599d0c95SMel Gorman 	if (get_nr_swap_pages() > 0)
224599d0c95SMel Gorman 		nr += node_page_state_snapshot(pgdat, NR_ACTIVE_ANON) +
225599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_INACTIVE_ANON) +
226599d0c95SMel Gorman 		      node_page_state_snapshot(pgdat, NR_ISOLATED_ANON);
227599d0c95SMel Gorman 
228599d0c95SMel Gorman 	return nr;
229599d0c95SMel Gorman }
230599d0c95SMel Gorman 
231599d0c95SMel Gorman bool pgdat_reclaimable(struct pglist_data *pgdat)
232599d0c95SMel Gorman {
233599d0c95SMel Gorman 	return node_page_state_snapshot(pgdat, NR_PAGES_SCANNED) <
234599d0c95SMel Gorman 		pgdat_reclaimable_pages(pgdat) * 6;
2356e543d57SLisa Du }
2366e543d57SLisa Du 
23723047a96SJohannes Weiner unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru)
238c9f299d9SKOSAKI Motohiro {
239c3c787e8SHugh Dickins 	if (!mem_cgroup_disabled())
2404d7dcca2SHugh Dickins 		return mem_cgroup_get_lru_size(lruvec, lru);
241a3d8e054SKOSAKI Motohiro 
242599d0c95SMel Gorman 	return node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
243c9f299d9SKOSAKI Motohiro }
244c9f299d9SKOSAKI Motohiro 
245*b4536f0cSMichal Hocko unsigned long lruvec_zone_lru_size(struct lruvec *lruvec, enum lru_list lru,
246*b4536f0cSMichal Hocko 				   int zone_idx)
247*b4536f0cSMichal Hocko {
248*b4536f0cSMichal Hocko 	if (!mem_cgroup_disabled())
249*b4536f0cSMichal Hocko 		return mem_cgroup_get_zone_lru_size(lruvec, lru, zone_idx);
250*b4536f0cSMichal Hocko 
251*b4536f0cSMichal Hocko 	return zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zone_idx],
252*b4536f0cSMichal Hocko 			       NR_ZONE_LRU_BASE + lru);
253*b4536f0cSMichal Hocko }
254*b4536f0cSMichal Hocko 
2551da177e4SLinus Torvalds /*
2561d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2571da177e4SLinus Torvalds  */
2581d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2591da177e4SLinus Torvalds {
2601d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2611d3d4437SGlauber Costa 
2621d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2631d3d4437SGlauber Costa 		size *= nr_node_ids;
2641d3d4437SGlauber Costa 
2651d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2661d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2671d3d4437SGlauber Costa 		return -ENOMEM;
2681d3d4437SGlauber Costa 
2691da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2701da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2711da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2721d3d4437SGlauber Costa 	return 0;
2731da177e4SLinus Torvalds }
2748e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2751da177e4SLinus Torvalds 
2761da177e4SLinus Torvalds /*
2771da177e4SLinus Torvalds  * Remove one
2781da177e4SLinus Torvalds  */
2798e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2801da177e4SLinus Torvalds {
2811da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2821da177e4SLinus Torvalds 	list_del(&shrinker->list);
2831da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
284ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
2851da177e4SLinus Torvalds }
2868e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2871da177e4SLinus Torvalds 
2881da177e4SLinus Torvalds #define SHRINK_BATCH 128
2891d3d4437SGlauber Costa 
290cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2916b4f7799SJohannes Weiner 				    struct shrinker *shrinker,
2926b4f7799SJohannes Weiner 				    unsigned long nr_scanned,
2936b4f7799SJohannes Weiner 				    unsigned long nr_eligible)
2941da177e4SLinus Torvalds {
29524f7c6b9SDave Chinner 	unsigned long freed = 0;
2961da177e4SLinus Torvalds 	unsigned long long delta;
297635697c6SKonstantin Khlebnikov 	long total_scan;
298d5bc5fd3SVladimir Davydov 	long freeable;
299acf92b48SDave Chinner 	long nr;
300acf92b48SDave Chinner 	long new_nr;
3011d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
302e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
303e9299f50SDave Chinner 					  : SHRINK_BATCH;
3045f33a080SShaohua Li 	long scanned = 0, next_deferred;
3051da177e4SLinus Torvalds 
306d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
307d5bc5fd3SVladimir Davydov 	if (freeable == 0)
3081d3d4437SGlauber Costa 		return 0;
309635697c6SKonstantin Khlebnikov 
310acf92b48SDave Chinner 	/*
311acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
312acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
313acf92b48SDave Chinner 	 * don't also do this scanning work.
314acf92b48SDave Chinner 	 */
3151d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
316acf92b48SDave Chinner 
317acf92b48SDave Chinner 	total_scan = nr;
3186b4f7799SJohannes Weiner 	delta = (4 * nr_scanned) / shrinker->seeks;
319d5bc5fd3SVladimir Davydov 	delta *= freeable;
3206b4f7799SJohannes Weiner 	do_div(delta, nr_eligible + 1);
321acf92b48SDave Chinner 	total_scan += delta;
322acf92b48SDave Chinner 	if (total_scan < 0) {
3238612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
324a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
325d5bc5fd3SVladimir Davydov 		total_scan = freeable;
3265f33a080SShaohua Li 		next_deferred = nr;
3275f33a080SShaohua Li 	} else
3285f33a080SShaohua Li 		next_deferred = total_scan;
329ea164d73SAndrea Arcangeli 
330ea164d73SAndrea Arcangeli 	/*
3313567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3323567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3333567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3343567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3353567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
336d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3373567b59aSDave Chinner 	 * memory.
3383567b59aSDave Chinner 	 *
3393567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3403567b59aSDave Chinner 	 * a large delta change is calculated directly.
3413567b59aSDave Chinner 	 */
342d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
343d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3443567b59aSDave Chinner 
3453567b59aSDave Chinner 	/*
346ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
347ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
348ea164d73SAndrea Arcangeli 	 * freeable entries.
349ea164d73SAndrea Arcangeli 	 */
350d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
351d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3521da177e4SLinus Torvalds 
35324f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3546b4f7799SJohannes Weiner 				   nr_scanned, nr_eligible,
355d5bc5fd3SVladimir Davydov 				   freeable, delta, total_scan);
35609576073SDave Chinner 
3570b1fb40aSVladimir Davydov 	/*
3580b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3590b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3600b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3610b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3620b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3630b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3640b1fb40aSVladimir Davydov 	 * batch_size.
3650b1fb40aSVladimir Davydov 	 *
3660b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3670b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
368d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3690b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3700b1fb40aSVladimir Davydov 	 * possible.
3710b1fb40aSVladimir Davydov 	 */
3720b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
373d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
37424f7c6b9SDave Chinner 		unsigned long ret;
3750b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3761da177e4SLinus Torvalds 
3770b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
37824f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
37924f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3801da177e4SLinus Torvalds 			break;
38124f7c6b9SDave Chinner 		freed += ret;
38224f7c6b9SDave Chinner 
3830b1fb40aSVladimir Davydov 		count_vm_events(SLABS_SCANNED, nr_to_scan);
3840b1fb40aSVladimir Davydov 		total_scan -= nr_to_scan;
3855f33a080SShaohua Li 		scanned += nr_to_scan;
3861da177e4SLinus Torvalds 
3871da177e4SLinus Torvalds 		cond_resched();
3881da177e4SLinus Torvalds 	}
3891da177e4SLinus Torvalds 
3905f33a080SShaohua Li 	if (next_deferred >= scanned)
3915f33a080SShaohua Li 		next_deferred -= scanned;
3925f33a080SShaohua Li 	else
3935f33a080SShaohua Li 		next_deferred = 0;
394acf92b48SDave Chinner 	/*
395acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
396acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
397acf92b48SDave Chinner 	 * scan, there is no need to do an update.
398acf92b48SDave Chinner 	 */
3995f33a080SShaohua Li 	if (next_deferred > 0)
4005f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
4011d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
40283aeeadaSKonstantin Khlebnikov 	else
4031d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
404acf92b48SDave Chinner 
405df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
4061d3d4437SGlauber Costa 	return freed;
4071d3d4437SGlauber Costa }
4081d3d4437SGlauber Costa 
4096b4f7799SJohannes Weiner /**
410cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
4116b4f7799SJohannes Weiner  * @gfp_mask: allocation context
4126b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
413cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
4146b4f7799SJohannes Weiner  * @nr_scanned: pressure numerator
4156b4f7799SJohannes Weiner  * @nr_eligible: pressure denominator
4161d3d4437SGlauber Costa  *
4176b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4181d3d4437SGlauber Costa  *
4196b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4206b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4211d3d4437SGlauber Costa  *
422cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
423cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4240fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4250fc9f58aSVladimir Davydov  * shrinkers are called.
426cb731d6cSVladimir Davydov  *
4276b4f7799SJohannes Weiner  * @nr_scanned and @nr_eligible form a ratio that indicate how much of
4286b4f7799SJohannes Weiner  * the available objects should be scanned.  Page reclaim for example
4296b4f7799SJohannes Weiner  * passes the number of pages scanned and the number of pages on the
4306b4f7799SJohannes Weiner  * LRU lists that it considered on @nid, plus a bias in @nr_scanned
4316b4f7799SJohannes Weiner  * when it encountered mapped pages.  The ratio is further biased by
4326b4f7799SJohannes Weiner  * the ->seeks setting of the shrink function, which indicates the
4336b4f7799SJohannes Weiner  * cost to recreate an object relative to that of an LRU page.
4341d3d4437SGlauber Costa  *
4356b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4361d3d4437SGlauber Costa  */
437cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
438cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4396b4f7799SJohannes Weiner 				 unsigned long nr_scanned,
4406b4f7799SJohannes Weiner 				 unsigned long nr_eligible)
4411d3d4437SGlauber Costa {
4421d3d4437SGlauber Costa 	struct shrinker *shrinker;
4431d3d4437SGlauber Costa 	unsigned long freed = 0;
4441d3d4437SGlauber Costa 
4450fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
446cb731d6cSVladimir Davydov 		return 0;
447cb731d6cSVladimir Davydov 
4486b4f7799SJohannes Weiner 	if (nr_scanned == 0)
4496b4f7799SJohannes Weiner 		nr_scanned = SWAP_CLUSTER_MAX;
4501d3d4437SGlauber Costa 
4511d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4521d3d4437SGlauber Costa 		/*
4531d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4541d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4551d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4561d3d4437SGlauber Costa 		 * time.
4571d3d4437SGlauber Costa 		 */
4581d3d4437SGlauber Costa 		freed = 1;
4591d3d4437SGlauber Costa 		goto out;
4601d3d4437SGlauber Costa 	}
4611d3d4437SGlauber Costa 
4621d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4636b4f7799SJohannes Weiner 		struct shrink_control sc = {
4646b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4656b4f7799SJohannes Weiner 			.nid = nid,
466cb731d6cSVladimir Davydov 			.memcg = memcg,
4676b4f7799SJohannes Weiner 		};
4686b4f7799SJohannes Weiner 
4690fc9f58aSVladimir Davydov 		/*
4700fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4710fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4720fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4730fc9f58aSVladimir Davydov 		 */
4740fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4750fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
476cb731d6cSVladimir Davydov 			continue;
477cb731d6cSVladimir Davydov 
4786b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4796b4f7799SJohannes Weiner 			sc.nid = 0;
4806b4f7799SJohannes Weiner 
481cb731d6cSVladimir Davydov 		freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
482ec97097bSVladimir Davydov 	}
4831d3d4437SGlauber Costa 
4841da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
485f06590bdSMinchan Kim out:
486f06590bdSMinchan Kim 	cond_resched();
48724f7c6b9SDave Chinner 	return freed;
4881da177e4SLinus Torvalds }
4891da177e4SLinus Torvalds 
490cb731d6cSVladimir Davydov void drop_slab_node(int nid)
491cb731d6cSVladimir Davydov {
492cb731d6cSVladimir Davydov 	unsigned long freed;
493cb731d6cSVladimir Davydov 
494cb731d6cSVladimir Davydov 	do {
495cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
496cb731d6cSVladimir Davydov 
497cb731d6cSVladimir Davydov 		freed = 0;
498cb731d6cSVladimir Davydov 		do {
499cb731d6cSVladimir Davydov 			freed += shrink_slab(GFP_KERNEL, nid, memcg,
500cb731d6cSVladimir Davydov 					     1000, 1000);
501cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
502cb731d6cSVladimir Davydov 	} while (freed > 10);
503cb731d6cSVladimir Davydov }
504cb731d6cSVladimir Davydov 
505cb731d6cSVladimir Davydov void drop_slab(void)
506cb731d6cSVladimir Davydov {
507cb731d6cSVladimir Davydov 	int nid;
508cb731d6cSVladimir Davydov 
509cb731d6cSVladimir Davydov 	for_each_online_node(nid)
510cb731d6cSVladimir Davydov 		drop_slab_node(nid);
511cb731d6cSVladimir Davydov }
512cb731d6cSVladimir Davydov 
5131da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5141da177e4SLinus Torvalds {
515ceddc3a5SJohannes Weiner 	/*
516ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
517ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
518ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
519ceddc3a5SJohannes Weiner 	 */
520edcf4748SJohannes Weiner 	return page_count(page) - page_has_private(page) == 2;
5211da177e4SLinus Torvalds }
5221da177e4SLinus Torvalds 
523703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5241da177e4SLinus Torvalds {
525930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5261da177e4SLinus Torvalds 		return 1;
527703c2708STejun Heo 	if (!inode_write_congested(inode))
5281da177e4SLinus Torvalds 		return 1;
529703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5301da177e4SLinus Torvalds 		return 1;
5311da177e4SLinus Torvalds 	return 0;
5321da177e4SLinus Torvalds }
5331da177e4SLinus Torvalds 
5341da177e4SLinus Torvalds /*
5351da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5361da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5371da177e4SLinus Torvalds  * fsync(), msync() or close().
5381da177e4SLinus Torvalds  *
5391da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5401da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5411da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5421da177e4SLinus Torvalds  *
5431da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5441da177e4SLinus Torvalds  * __GFP_FS.
5451da177e4SLinus Torvalds  */
5461da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5471da177e4SLinus Torvalds 				struct page *page, int error)
5481da177e4SLinus Torvalds {
5497eaceaccSJens Axboe 	lock_page(page);
5503e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5513e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5521da177e4SLinus Torvalds 	unlock_page(page);
5531da177e4SLinus Torvalds }
5541da177e4SLinus Torvalds 
55504e62a29SChristoph Lameter /* possible outcome of pageout() */
55604e62a29SChristoph Lameter typedef enum {
55704e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
55804e62a29SChristoph Lameter 	PAGE_KEEP,
55904e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
56004e62a29SChristoph Lameter 	PAGE_ACTIVATE,
56104e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
56204e62a29SChristoph Lameter 	PAGE_SUCCESS,
56304e62a29SChristoph Lameter 	/* page is clean and locked */
56404e62a29SChristoph Lameter 	PAGE_CLEAN,
56504e62a29SChristoph Lameter } pageout_t;
56604e62a29SChristoph Lameter 
5671da177e4SLinus Torvalds /*
5681742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5691742f19fSAndrew Morton  * Calls ->writepage().
5701da177e4SLinus Torvalds  */
571c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5727d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5731da177e4SLinus Torvalds {
5741da177e4SLinus Torvalds 	/*
5751da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5761da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5771da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5781da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5791da177e4SLinus Torvalds 	 * PagePrivate for that.
5801da177e4SLinus Torvalds 	 *
5818174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5821da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5831da177e4SLinus Torvalds 	 * will block.
5841da177e4SLinus Torvalds 	 *
5851da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5861da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5871da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5881da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5891da177e4SLinus Torvalds 	 */
5901da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5911da177e4SLinus Torvalds 		return PAGE_KEEP;
5921da177e4SLinus Torvalds 	if (!mapping) {
5931da177e4SLinus Torvalds 		/*
5941da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5951da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5961da177e4SLinus Torvalds 		 */
597266cf658SDavid Howells 		if (page_has_private(page)) {
5981da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5991da177e4SLinus Torvalds 				ClearPageDirty(page);
600b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
6011da177e4SLinus Torvalds 				return PAGE_CLEAN;
6021da177e4SLinus Torvalds 			}
6031da177e4SLinus Torvalds 		}
6041da177e4SLinus Torvalds 		return PAGE_KEEP;
6051da177e4SLinus Torvalds 	}
6061da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6071da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
608703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6091da177e4SLinus Torvalds 		return PAGE_KEEP;
6101da177e4SLinus Torvalds 
6111da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6121da177e4SLinus Torvalds 		int res;
6131da177e4SLinus Torvalds 		struct writeback_control wbc = {
6141da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6151da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
616111ebb6eSOGAWA Hirofumi 			.range_start = 0,
617111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6181da177e4SLinus Torvalds 			.for_reclaim = 1,
6191da177e4SLinus Torvalds 		};
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds 		SetPageReclaim(page);
6221da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6231da177e4SLinus Torvalds 		if (res < 0)
6241da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
625994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6261da177e4SLinus Torvalds 			ClearPageReclaim(page);
6271da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6281da177e4SLinus Torvalds 		}
629c661b078SAndy Whitcroft 
6301da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6311da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6321da177e4SLinus Torvalds 			ClearPageReclaim(page);
6331da177e4SLinus Torvalds 		}
6343aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
635c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6361da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6371da177e4SLinus Torvalds 	}
6381da177e4SLinus Torvalds 
6391da177e4SLinus Torvalds 	return PAGE_CLEAN;
6401da177e4SLinus Torvalds }
6411da177e4SLinus Torvalds 
642a649fd92SAndrew Morton /*
643e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
644e286781dSNick Piggin  * gets returned with a refcount of 0.
645a649fd92SAndrew Morton  */
646a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
647a528910eSJohannes Weiner 			    bool reclaimed)
64849d2e9ccSChristoph Lameter {
649c4843a75SGreg Thelen 	unsigned long flags;
650c4843a75SGreg Thelen 
65128e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
65228e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
65349d2e9ccSChristoph Lameter 
654c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
65549d2e9ccSChristoph Lameter 	/*
6560fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6570fd0e6b0SNick Piggin 	 *
6580fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6590fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6600fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6610fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6620fd0e6b0SNick Piggin 	 *
6630fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6640fd0e6b0SNick Piggin 	 * [user mapping goes away]
6650fd0e6b0SNick Piggin 	 * write_to(page);
6660fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6670fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6680fd0e6b0SNick Piggin 	 * put_page(page);
6690fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6700fd0e6b0SNick Piggin 	 *
6710fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6720fd0e6b0SNick Piggin 	 *
6730fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6740fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6750139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6760fd0e6b0SNick Piggin 	 *
6770fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6780fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
67949d2e9ccSChristoph Lameter 	 */
680fe896d18SJoonsoo Kim 	if (!page_ref_freeze(page, 2))
68149d2e9ccSChristoph Lameter 		goto cannot_free;
682e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
683e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
684fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 2);
68549d2e9ccSChristoph Lameter 		goto cannot_free;
686e286781dSNick Piggin 	}
68749d2e9ccSChristoph Lameter 
68849d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
68949d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6900a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
69149d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
692c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
6930a31bc97SJohannes Weiner 		swapcache_free(swap);
694e286781dSNick Piggin 	} else {
6956072d13cSLinus Torvalds 		void (*freepage)(struct page *);
696a528910eSJohannes Weiner 		void *shadow = NULL;
6976072d13cSLinus Torvalds 
6986072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
699a528910eSJohannes Weiner 		/*
700a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
701a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
702a528910eSJohannes Weiner 		 *
703a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
704a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
705a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
706a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
707a528910eSJohannes Weiner 		 * back.
708f9fe48beSRoss Zwisler 		 *
709f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
710f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
711f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
712f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
713f9fe48beSRoss Zwisler 		 * same page_tree.
714a528910eSJohannes Weiner 		 */
715a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
716f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
717a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
71862cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
719c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7206072d13cSLinus Torvalds 
7216072d13cSLinus Torvalds 		if (freepage != NULL)
7226072d13cSLinus Torvalds 			freepage(page);
723e286781dSNick Piggin 	}
724e286781dSNick Piggin 
72549d2e9ccSChristoph Lameter 	return 1;
72649d2e9ccSChristoph Lameter 
72749d2e9ccSChristoph Lameter cannot_free:
728c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
72949d2e9ccSChristoph Lameter 	return 0;
73049d2e9ccSChristoph Lameter }
73149d2e9ccSChristoph Lameter 
7321da177e4SLinus Torvalds /*
733e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
734e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
735e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
736e286781dSNick Piggin  * this page.
737e286781dSNick Piggin  */
738e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
739e286781dSNick Piggin {
740a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
741e286781dSNick Piggin 		/*
742e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
743e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
744e286781dSNick Piggin 		 * atomic operation.
745e286781dSNick Piggin 		 */
746fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
747e286781dSNick Piggin 		return 1;
748e286781dSNick Piggin 	}
749e286781dSNick Piggin 	return 0;
750e286781dSNick Piggin }
751e286781dSNick Piggin 
752894bc310SLee Schermerhorn /**
753894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
754894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
755894bc310SLee Schermerhorn  *
756894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
757894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
758894bc310SLee Schermerhorn  *
759894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
760894bc310SLee Schermerhorn  */
761894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
762894bc310SLee Schermerhorn {
7630ec3b74cSVlastimil Babka 	bool is_unevictable;
764bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
765894bc310SLee Schermerhorn 
766309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
767894bc310SLee Schermerhorn 
768894bc310SLee Schermerhorn redo:
769894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
770894bc310SLee Schermerhorn 
77139b5f29aSHugh Dickins 	if (page_evictable(page)) {
772894bc310SLee Schermerhorn 		/*
773894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
774894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
775894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
776894bc310SLee Schermerhorn 		 * We know how to handle that.
777894bc310SLee Schermerhorn 		 */
7780ec3b74cSVlastimil Babka 		is_unevictable = false;
779c53954a0SMel Gorman 		lru_cache_add(page);
780894bc310SLee Schermerhorn 	} else {
781894bc310SLee Schermerhorn 		/*
782894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
783894bc310SLee Schermerhorn 		 * list.
784894bc310SLee Schermerhorn 		 */
7850ec3b74cSVlastimil Babka 		is_unevictable = true;
786894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7876a7b9548SJohannes Weiner 		/*
78821ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
78921ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
79021ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
79124513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
79221ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
7936a7b9548SJohannes Weiner 		 * the page back to the evictable list.
7946a7b9548SJohannes Weiner 		 *
79521ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
7966a7b9548SJohannes Weiner 		 */
7976a7b9548SJohannes Weiner 		smp_mb();
798894bc310SLee Schermerhorn 	}
799894bc310SLee Schermerhorn 
800894bc310SLee Schermerhorn 	/*
801894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
802894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
803894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
804894bc310SLee Schermerhorn 	 */
8050ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
806894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
807894bc310SLee Schermerhorn 			put_page(page);
808894bc310SLee Schermerhorn 			goto redo;
809894bc310SLee Schermerhorn 		}
810894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
811894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
812894bc310SLee Schermerhorn 		 * nothing to do here.
813894bc310SLee Schermerhorn 		 */
814894bc310SLee Schermerhorn 	}
815894bc310SLee Schermerhorn 
8160ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
817bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8180ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
819bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
820bbfd28eeSLee Schermerhorn 
821894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
822894bc310SLee Schermerhorn }
823894bc310SLee Schermerhorn 
824dfc8d636SJohannes Weiner enum page_references {
825dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
826dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
82764574746SJohannes Weiner 	PAGEREF_KEEP,
828dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
829dfc8d636SJohannes Weiner };
830dfc8d636SJohannes Weiner 
831dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
832dfc8d636SJohannes Weiner 						  struct scan_control *sc)
833dfc8d636SJohannes Weiner {
83464574746SJohannes Weiner 	int referenced_ptes, referenced_page;
835dfc8d636SJohannes Weiner 	unsigned long vm_flags;
836dfc8d636SJohannes Weiner 
837c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
838c3ac9a8aSJohannes Weiner 					  &vm_flags);
83964574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
840dfc8d636SJohannes Weiner 
841dfc8d636SJohannes Weiner 	/*
842dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
843dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
844dfc8d636SJohannes Weiner 	 */
845dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
846dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
847dfc8d636SJohannes Weiner 
84864574746SJohannes Weiner 	if (referenced_ptes) {
849e4898273SMichal Hocko 		if (PageSwapBacked(page))
85064574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
85164574746SJohannes Weiner 		/*
85264574746SJohannes Weiner 		 * All mapped pages start out with page table
85364574746SJohannes Weiner 		 * references from the instantiating fault, so we need
85464574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
85564574746SJohannes Weiner 		 * than once.
85664574746SJohannes Weiner 		 *
85764574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
85864574746SJohannes Weiner 		 * inactive list.  Another page table reference will
85964574746SJohannes Weiner 		 * lead to its activation.
86064574746SJohannes Weiner 		 *
86164574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
86264574746SJohannes Weiner 		 * so that recently deactivated but used pages are
86364574746SJohannes Weiner 		 * quickly recovered.
86464574746SJohannes Weiner 		 */
86564574746SJohannes Weiner 		SetPageReferenced(page);
86664574746SJohannes Weiner 
86734dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
868dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
869dfc8d636SJohannes Weiner 
870c909e993SKonstantin Khlebnikov 		/*
871c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
872c909e993SKonstantin Khlebnikov 		 */
873c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
874c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
875c909e993SKonstantin Khlebnikov 
87664574746SJohannes Weiner 		return PAGEREF_KEEP;
87764574746SJohannes Weiner 	}
87864574746SJohannes Weiner 
879dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8802e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
881dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
88264574746SJohannes Weiner 
88364574746SJohannes Weiner 	return PAGEREF_RECLAIM;
884dfc8d636SJohannes Weiner }
885dfc8d636SJohannes Weiner 
886e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
887e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
888e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
889e2be15f6SMel Gorman {
890b4597226SMel Gorman 	struct address_space *mapping;
891b4597226SMel Gorman 
892e2be15f6SMel Gorman 	/*
893e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
894e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
895e2be15f6SMel Gorman 	 */
896e2be15f6SMel Gorman 	if (!page_is_file_cache(page)) {
897e2be15f6SMel Gorman 		*dirty = false;
898e2be15f6SMel Gorman 		*writeback = false;
899e2be15f6SMel Gorman 		return;
900e2be15f6SMel Gorman 	}
901e2be15f6SMel Gorman 
902e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
903e2be15f6SMel Gorman 	*dirty = PageDirty(page);
904e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
905b4597226SMel Gorman 
906b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
907b4597226SMel Gorman 	if (!page_has_private(page))
908b4597226SMel Gorman 		return;
909b4597226SMel Gorman 
910b4597226SMel Gorman 	mapping = page_mapping(page);
911b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
912b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
913e2be15f6SMel Gorman }
914e2be15f6SMel Gorman 
915e286781dSNick Piggin /*
9161742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
9171da177e4SLinus Torvalds  */
9181742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
919599d0c95SMel Gorman 				      struct pglist_data *pgdat,
920f84f6e2bSMel Gorman 				      struct scan_control *sc,
92102c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9228e950282SMel Gorman 				      unsigned long *ret_nr_dirty,
923d43006d5SMel Gorman 				      unsigned long *ret_nr_unqueued_dirty,
9248e950282SMel Gorman 				      unsigned long *ret_nr_congested,
92502c6de8dSMinchan Kim 				      unsigned long *ret_nr_writeback,
926b1a6f21eSMel Gorman 				      unsigned long *ret_nr_immediate,
92702c6de8dSMinchan Kim 				      bool force_reclaim)
9281da177e4SLinus Torvalds {
9291da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
930abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9311da177e4SLinus Torvalds 	int pgactivate = 0;
932d43006d5SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
9330e093d99SMel Gorman 	unsigned long nr_dirty = 0;
9340e093d99SMel Gorman 	unsigned long nr_congested = 0;
93505ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
93692df3a72SMel Gorman 	unsigned long nr_writeback = 0;
937b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
9381da177e4SLinus Torvalds 
9391da177e4SLinus Torvalds 	cond_resched();
9401da177e4SLinus Torvalds 
9411da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9421da177e4SLinus Torvalds 		struct address_space *mapping;
9431da177e4SLinus Torvalds 		struct page *page;
9441da177e4SLinus Torvalds 		int may_enter_fs;
94502c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
946e2be15f6SMel Gorman 		bool dirty, writeback;
947854e9ed0SMinchan Kim 		bool lazyfree = false;
948854e9ed0SMinchan Kim 		int ret = SWAP_SUCCESS;
9491da177e4SLinus Torvalds 
9501da177e4SLinus Torvalds 		cond_resched();
9511da177e4SLinus Torvalds 
9521da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9531da177e4SLinus Torvalds 		list_del(&page->lru);
9541da177e4SLinus Torvalds 
955529ae9aaSNick Piggin 		if (!trylock_page(page))
9561da177e4SLinus Torvalds 			goto keep;
9571da177e4SLinus Torvalds 
958309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9591da177e4SLinus Torvalds 
9601da177e4SLinus Torvalds 		sc->nr_scanned++;
96180e43426SChristoph Lameter 
96239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
963b291f000SNick Piggin 			goto cull_mlocked;
964894bc310SLee Schermerhorn 
965a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
96680e43426SChristoph Lameter 			goto keep_locked;
96780e43426SChristoph Lameter 
9681da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
9691da177e4SLinus Torvalds 		if (page_mapped(page) || PageSwapCache(page))
9701da177e4SLinus Torvalds 			sc->nr_scanned++;
9711da177e4SLinus Torvalds 
972c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
973c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
974c661b078SAndy Whitcroft 
975e62e384eSMichal Hocko 		/*
976e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
977e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
978e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
979e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
980e2be15f6SMel Gorman 		 */
981e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
982e2be15f6SMel Gorman 		if (dirty || writeback)
983e2be15f6SMel Gorman 			nr_dirty++;
984e2be15f6SMel Gorman 
985e2be15f6SMel Gorman 		if (dirty && !writeback)
986e2be15f6SMel Gorman 			nr_unqueued_dirty++;
987e2be15f6SMel Gorman 
988d04e8acdSMel Gorman 		/*
989d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
990d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
991d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
992d04e8acdSMel Gorman 		 * end of the LRU a second time.
993d04e8acdSMel Gorman 		 */
994e2be15f6SMel Gorman 		mapping = page_mapping(page);
9951da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
996703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
997d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
998e2be15f6SMel Gorman 			nr_congested++;
999e2be15f6SMel Gorman 
1000e2be15f6SMel Gorman 		/*
1001283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1002283aba9fSMel Gorman 		 * are three cases to consider.
1003e62e384eSMichal Hocko 		 *
1004283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1005283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1006283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1007283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1008283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1009283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1010283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1011b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1012b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1013c3b94f44SHugh Dickins 		 *
101497c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1015ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1016ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1017ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
101897c9341fSTejun Heo 		 *    reclaim and continue scanning.
1019283aba9fSMel Gorman 		 *
1020ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1021ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1022283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1023283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1024283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1025283aba9fSMel Gorman 		 *    would probably show more reasons.
1026283aba9fSMel Gorman 		 *
10277fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1028283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1029283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1030283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1031283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1032e62e384eSMichal Hocko 		 */
1033283aba9fSMel Gorman 		if (PageWriteback(page)) {
1034283aba9fSMel Gorman 			/* Case 1 above */
1035283aba9fSMel Gorman 			if (current_is_kswapd() &&
1036283aba9fSMel Gorman 			    PageReclaim(page) &&
1037599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1038b1a6f21eSMel Gorman 				nr_immediate++;
1039b1a6f21eSMel Gorman 				goto keep_locked;
1040283aba9fSMel Gorman 
1041283aba9fSMel Gorman 			/* Case 2 above */
104297c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1043ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1044c3b94f44SHugh Dickins 				/*
1045c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1046c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1047c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1048c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1049c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1050c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1051c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1052c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1053c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1054c3b94f44SHugh Dickins 				 */
1055c3b94f44SHugh Dickins 				SetPageReclaim(page);
105692df3a72SMel Gorman 				nr_writeback++;
1057c3b94f44SHugh Dickins 				goto keep_locked;
1058283aba9fSMel Gorman 
1059283aba9fSMel Gorman 			/* Case 3 above */
1060283aba9fSMel Gorman 			} else {
10617fadc820SHugh Dickins 				unlock_page(page);
1062c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10637fadc820SHugh Dickins 				/* then go back and try same page again */
10647fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10657fadc820SHugh Dickins 				continue;
1066e62e384eSMichal Hocko 			}
1067283aba9fSMel Gorman 		}
10681da177e4SLinus Torvalds 
106902c6de8dSMinchan Kim 		if (!force_reclaim)
10706a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
107102c6de8dSMinchan Kim 
1072dfc8d636SJohannes Weiner 		switch (references) {
1073dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10741da177e4SLinus Torvalds 			goto activate_locked;
107564574746SJohannes Weiner 		case PAGEREF_KEEP:
107664574746SJohannes Weiner 			goto keep_locked;
1077dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1078dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1079dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1080dfc8d636SJohannes Weiner 		}
10811da177e4SLinus Torvalds 
10821da177e4SLinus Torvalds 		/*
10831da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10841da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
10851da177e4SLinus Torvalds 		 */
1086b291f000SNick Piggin 		if (PageAnon(page) && !PageSwapCache(page)) {
108763eb6b93SHugh Dickins 			if (!(sc->gfp_mask & __GFP_IO))
108863eb6b93SHugh Dickins 				goto keep_locked;
10895bc7b8acSShaohua Li 			if (!add_to_swap(page, page_list))
10901da177e4SLinus Torvalds 				goto activate_locked;
1091854e9ed0SMinchan Kim 			lazyfree = true;
109263eb6b93SHugh Dickins 			may_enter_fs = 1;
10931da177e4SLinus Torvalds 
1094e2be15f6SMel Gorman 			/* Adding to swap updated mapping */
10951da177e4SLinus Torvalds 			mapping = page_mapping(page);
10967751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
10977751b2daSKirill A. Shutemov 			/* Split file THP */
10987751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
10997751b2daSKirill A. Shutemov 				goto keep_locked;
1100e2be15f6SMel Gorman 		}
11011da177e4SLinus Torvalds 
11027751b2daSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransHuge(page), page);
11037751b2daSKirill A. Shutemov 
11041da177e4SLinus Torvalds 		/*
11051da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
11061da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
11071da177e4SLinus Torvalds 		 */
11081da177e4SLinus Torvalds 		if (page_mapped(page) && mapping) {
1109854e9ed0SMinchan Kim 			switch (ret = try_to_unmap(page, lazyfree ?
1110854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH | TTU_LZFREE) :
1111854e9ed0SMinchan Kim 				(ttu_flags | TTU_BATCH_FLUSH))) {
11121da177e4SLinus Torvalds 			case SWAP_FAIL:
11131da177e4SLinus Torvalds 				goto activate_locked;
11141da177e4SLinus Torvalds 			case SWAP_AGAIN:
11151da177e4SLinus Torvalds 				goto keep_locked;
1116b291f000SNick Piggin 			case SWAP_MLOCK:
1117b291f000SNick Piggin 				goto cull_mlocked;
1118854e9ed0SMinchan Kim 			case SWAP_LZFREE:
1119854e9ed0SMinchan Kim 				goto lazyfree;
11201da177e4SLinus Torvalds 			case SWAP_SUCCESS:
11211da177e4SLinus Torvalds 				; /* try to free the page below */
11221da177e4SLinus Torvalds 			}
11231da177e4SLinus Torvalds 		}
11241da177e4SLinus Torvalds 
11251da177e4SLinus Torvalds 		if (PageDirty(page)) {
1126ee72886dSMel Gorman 			/*
1127ee72886dSMel Gorman 			 * Only kswapd can writeback filesystem pages to
1128d43006d5SMel Gorman 			 * avoid risk of stack overflow but only writeback
1129d43006d5SMel Gorman 			 * if many dirty pages have been encountered.
1130ee72886dSMel Gorman 			 */
1131f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11329e3b2f8cSKonstantin Khlebnikov 					(!current_is_kswapd() ||
1133599d0c95SMel Gorman 					 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
113449ea7eb6SMel Gorman 				/*
113549ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
113649ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
113749ea7eb6SMel Gorman 				 * except we already have the page isolated
113849ea7eb6SMel Gorman 				 * and know it's dirty
113949ea7eb6SMel Gorman 				 */
1140c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
114149ea7eb6SMel Gorman 				SetPageReclaim(page);
114249ea7eb6SMel Gorman 
1143ee72886dSMel Gorman 				goto keep_locked;
1144ee72886dSMel Gorman 			}
1145ee72886dSMel Gorman 
1146dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11471da177e4SLinus Torvalds 				goto keep_locked;
11484dd4b920SAndrew Morton 			if (!may_enter_fs)
11491da177e4SLinus Torvalds 				goto keep_locked;
115052a8363eSChristoph Lameter 			if (!sc->may_writepage)
11511da177e4SLinus Torvalds 				goto keep_locked;
11521da177e4SLinus Torvalds 
1153d950c947SMel Gorman 			/*
1154d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1155d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1156d950c947SMel Gorman 			 * starts and then write it out here.
1157d950c947SMel Gorman 			 */
1158d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11597d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11601da177e4SLinus Torvalds 			case PAGE_KEEP:
11611da177e4SLinus Torvalds 				goto keep_locked;
11621da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11631da177e4SLinus Torvalds 				goto activate_locked;
11641da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11657d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
116641ac1999SMel Gorman 					goto keep;
11677d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11681da177e4SLinus Torvalds 					goto keep;
11697d3579e8SKOSAKI Motohiro 
11701da177e4SLinus Torvalds 				/*
11711da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11721da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11731da177e4SLinus Torvalds 				 */
1174529ae9aaSNick Piggin 				if (!trylock_page(page))
11751da177e4SLinus Torvalds 					goto keep;
11761da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11771da177e4SLinus Torvalds 					goto keep_locked;
11781da177e4SLinus Torvalds 				mapping = page_mapping(page);
11791da177e4SLinus Torvalds 			case PAGE_CLEAN:
11801da177e4SLinus Torvalds 				; /* try to free the page below */
11811da177e4SLinus Torvalds 			}
11821da177e4SLinus Torvalds 		}
11831da177e4SLinus Torvalds 
11841da177e4SLinus Torvalds 		/*
11851da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11861da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11871da177e4SLinus Torvalds 		 * the page as well.
11881da177e4SLinus Torvalds 		 *
11891da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11901da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11911da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11921da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11931da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11941da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11951da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11961da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11971da177e4SLinus Torvalds 		 *
11981da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11991da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
12001da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
12011da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
12021da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
12031da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
12041da177e4SLinus Torvalds 		 */
1205266cf658SDavid Howells 		if (page_has_private(page)) {
12061da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
12071da177e4SLinus Torvalds 				goto activate_locked;
1208e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1209e286781dSNick Piggin 				unlock_page(page);
1210e286781dSNick Piggin 				if (put_page_testzero(page))
12111da177e4SLinus Torvalds 					goto free_it;
1212e286781dSNick Piggin 				else {
1213e286781dSNick Piggin 					/*
1214e286781dSNick Piggin 					 * rare race with speculative reference.
1215e286781dSNick Piggin 					 * the speculative reference will free
1216e286781dSNick Piggin 					 * this page shortly, so we may
1217e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1218e286781dSNick Piggin 					 * leave it off the LRU).
1219e286781dSNick Piggin 					 */
1220e286781dSNick Piggin 					nr_reclaimed++;
1221e286781dSNick Piggin 					continue;
1222e286781dSNick Piggin 				}
1223e286781dSNick Piggin 			}
12241da177e4SLinus Torvalds 		}
12251da177e4SLinus Torvalds 
1226854e9ed0SMinchan Kim lazyfree:
1227a528910eSJohannes Weiner 		if (!mapping || !__remove_mapping(mapping, page, true))
122849d2e9ccSChristoph Lameter 			goto keep_locked;
12291da177e4SLinus Torvalds 
1230a978d6f5SNick Piggin 		/*
1231a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1232a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1233a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1234a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1235a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1236a978d6f5SNick Piggin 		 */
123748c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1238e286781dSNick Piggin free_it:
1239854e9ed0SMinchan Kim 		if (ret == SWAP_LZFREE)
1240854e9ed0SMinchan Kim 			count_vm_event(PGLAZYFREED);
1241854e9ed0SMinchan Kim 
124205ff5137SAndrew Morton 		nr_reclaimed++;
1243abe4c3b5SMel Gorman 
1244abe4c3b5SMel Gorman 		/*
1245abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1246abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1247abe4c3b5SMel Gorman 		 */
1248abe4c3b5SMel Gorman 		list_add(&page->lru, &free_pages);
12491da177e4SLinus Torvalds 		continue;
12501da177e4SLinus Torvalds 
1251b291f000SNick Piggin cull_mlocked:
125263d6c5adSHugh Dickins 		if (PageSwapCache(page))
125363d6c5adSHugh Dickins 			try_to_free_swap(page);
1254b291f000SNick Piggin 		unlock_page(page);
1255c54839a7SJaewon Kim 		list_add(&page->lru, &ret_pages);
1256b291f000SNick Piggin 		continue;
1257b291f000SNick Piggin 
12581da177e4SLinus Torvalds activate_locked:
125968a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
12605ccc5abaSVladimir Davydov 		if (PageSwapCache(page) && mem_cgroup_swap_full(page))
1261a2c43eedSHugh Dickins 			try_to_free_swap(page);
1262309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
12631da177e4SLinus Torvalds 		SetPageActive(page);
12641da177e4SLinus Torvalds 		pgactivate++;
12651da177e4SLinus Torvalds keep_locked:
12661da177e4SLinus Torvalds 		unlock_page(page);
12671da177e4SLinus Torvalds keep:
12681da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1269309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12701da177e4SLinus Torvalds 	}
1271abe4c3b5SMel Gorman 
1272747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
127372b252aeSMel Gorman 	try_to_unmap_flush();
1274b745bc85SMel Gorman 	free_hot_cold_page_list(&free_pages, true);
1275abe4c3b5SMel Gorman 
12761da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1277f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12780a31bc97SJohannes Weiner 
12798e950282SMel Gorman 	*ret_nr_dirty += nr_dirty;
12808e950282SMel Gorman 	*ret_nr_congested += nr_congested;
1281d43006d5SMel Gorman 	*ret_nr_unqueued_dirty += nr_unqueued_dirty;
128292df3a72SMel Gorman 	*ret_nr_writeback += nr_writeback;
1283b1a6f21eSMel Gorman 	*ret_nr_immediate += nr_immediate;
128405ff5137SAndrew Morton 	return nr_reclaimed;
12851da177e4SLinus Torvalds }
12861da177e4SLinus Torvalds 
128702c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
128802c6de8dSMinchan Kim 					    struct list_head *page_list)
128902c6de8dSMinchan Kim {
129002c6de8dSMinchan Kim 	struct scan_control sc = {
129102c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
129202c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
129302c6de8dSMinchan Kim 		.may_unmap = 1,
129402c6de8dSMinchan Kim 	};
12958e950282SMel Gorman 	unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
129602c6de8dSMinchan Kim 	struct page *page, *next;
129702c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
129802c6de8dSMinchan Kim 
129902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1300117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1301b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
130202c6de8dSMinchan Kim 			ClearPageActive(page);
130302c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
130402c6de8dSMinchan Kim 		}
130502c6de8dSMinchan Kim 	}
130602c6de8dSMinchan Kim 
1307599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
130802c6de8dSMinchan Kim 			TTU_UNMAP|TTU_IGNORE_ACCESS,
13098e950282SMel Gorman 			&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
131002c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1311599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
131202c6de8dSMinchan Kim 	return ret;
131302c6de8dSMinchan Kim }
131402c6de8dSMinchan Kim 
13155ad333ebSAndy Whitcroft /*
13165ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13175ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13185ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13195ad333ebSAndy Whitcroft  *
13205ad333ebSAndy Whitcroft  * page:	page to consider
13215ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13225ad333ebSAndy Whitcroft  *
13235ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13245ad333ebSAndy Whitcroft  */
1325f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13265ad333ebSAndy Whitcroft {
13275ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13285ad333ebSAndy Whitcroft 
13295ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13305ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13315ad333ebSAndy Whitcroft 		return ret;
13325ad333ebSAndy Whitcroft 
1333e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1334e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1335894bc310SLee Schermerhorn 		return ret;
1336894bc310SLee Schermerhorn 
13375ad333ebSAndy Whitcroft 	ret = -EBUSY;
133808e552c6SKAMEZAWA Hiroyuki 
1339c8244935SMel Gorman 	/*
1340c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1341c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1342c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1343c8244935SMel Gorman 	 *
1344c8244935SMel Gorman 	 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1345c8244935SMel Gorman 	 * is used by reclaim when it is cannot write to backing storage
1346c8244935SMel Gorman 	 *
1347c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1348c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1349c8244935SMel Gorman 	 */
1350c8244935SMel Gorman 	if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1351c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1352c8244935SMel Gorman 		if (PageWriteback(page))
135339deaf85SMinchan Kim 			return ret;
135439deaf85SMinchan Kim 
1355c8244935SMel Gorman 		if (PageDirty(page)) {
1356c8244935SMel Gorman 			struct address_space *mapping;
1357c8244935SMel Gorman 
1358c8244935SMel Gorman 			/* ISOLATE_CLEAN means only clean pages */
1359c8244935SMel Gorman 			if (mode & ISOLATE_CLEAN)
1360c8244935SMel Gorman 				return ret;
1361c8244935SMel Gorman 
1362c8244935SMel Gorman 			/*
1363c8244935SMel Gorman 			 * Only pages without mappings or that have a
1364c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1365c8244935SMel Gorman 			 * without blocking
1366c8244935SMel Gorman 			 */
1367c8244935SMel Gorman 			mapping = page_mapping(page);
1368c8244935SMel Gorman 			if (mapping && !mapping->a_ops->migratepage)
1369c8244935SMel Gorman 				return ret;
1370c8244935SMel Gorman 		}
1371c8244935SMel Gorman 	}
1372c8244935SMel Gorman 
1373f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1374f80c0673SMinchan Kim 		return ret;
1375f80c0673SMinchan Kim 
13765ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13775ad333ebSAndy Whitcroft 		/*
13785ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13795ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13805ad333ebSAndy Whitcroft 		 * page release code relies on it.
13815ad333ebSAndy Whitcroft 		 */
13825ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13835ad333ebSAndy Whitcroft 		ret = 0;
13845ad333ebSAndy Whitcroft 	}
13855ad333ebSAndy Whitcroft 
13865ad333ebSAndy Whitcroft 	return ret;
13875ad333ebSAndy Whitcroft }
13885ad333ebSAndy Whitcroft 
13897ee36a14SMel Gorman 
13907ee36a14SMel Gorman /*
13917ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
13927ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
13937ee36a14SMel Gorman  */
13947ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1395*b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
13967ee36a14SMel Gorman {
13977ee36a14SMel Gorman 	int zid;
13987ee36a14SMel Gorman 
13997ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14007ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14017ee36a14SMel Gorman 			continue;
14027ee36a14SMel Gorman 
14037ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1404*b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1405*b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1406*b4536f0cSMichal Hocko #endif
14077ee36a14SMel Gorman 	}
14087ee36a14SMel Gorman 
14097ee36a14SMel Gorman }
14107ee36a14SMel Gorman 
141149d2e9ccSChristoph Lameter /*
1412a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14131da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14141da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14151da177e4SLinus Torvalds  *
14161da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14171da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14181da177e4SLinus Torvalds  *
14191da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14201da177e4SLinus Torvalds  *
14211da177e4SLinus Torvalds  * @nr_to_scan:	The number of pages to look through on the list.
14225dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14231da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1424f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1425fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14265ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14273cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14281da177e4SLinus Torvalds  *
14291da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14301da177e4SLinus Torvalds  */
143169e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14325dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1433fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14343cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14351da177e4SLinus Torvalds {
143675b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
143769e05944SAndrew Morton 	unsigned long nr_taken = 0;
1438599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14397cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1440599d0c95SMel Gorman 	unsigned long scan, nr_pages;
1441b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14421da177e4SLinus Torvalds 
14430b802f10SVladimir Davydov 	for (scan = 0; scan < nr_to_scan && nr_taken < nr_to_scan &&
1444d7f05528SMel Gorman 					!list_empty(src);) {
14455ad333ebSAndy Whitcroft 		struct page *page;
14465ad333ebSAndy Whitcroft 
14471da177e4SLinus Torvalds 		page = lru_to_page(src);
14481da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14491da177e4SLinus Torvalds 
1450309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14518d438f96SNick Piggin 
1452b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1453b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
14547cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1455b2e18757SMel Gorman 			continue;
1456b2e18757SMel Gorman 		}
1457b2e18757SMel Gorman 
1458d7f05528SMel Gorman 		/*
1459d7f05528SMel Gorman 		 * Account for scanned and skipped separetly to avoid the pgdat
1460d7f05528SMel Gorman 		 * being prematurely marked unreclaimable by pgdat_reclaimable.
1461d7f05528SMel Gorman 		 */
1462d7f05528SMel Gorman 		scan++;
1463d7f05528SMel Gorman 
1464f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14655ad333ebSAndy Whitcroft 		case 0:
1466599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1467599d0c95SMel Gorman 			nr_taken += nr_pages;
1468599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14695ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14705ad333ebSAndy Whitcroft 			break;
14717c8ee9a8SNick Piggin 
14725ad333ebSAndy Whitcroft 		case -EBUSY:
14735ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
14745ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
14755ad333ebSAndy Whitcroft 			continue;
14765ad333ebSAndy Whitcroft 
14775ad333ebSAndy Whitcroft 		default:
14785ad333ebSAndy Whitcroft 			BUG();
14795ad333ebSAndy Whitcroft 		}
14805ad333ebSAndy Whitcroft 	}
14811da177e4SLinus Torvalds 
1482b2e18757SMel Gorman 	/*
1483b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1484b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1485b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1486b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1487b2e18757SMel Gorman 	 * system at risk of premature OOM.
1488b2e18757SMel Gorman 	 */
14897cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
14907cc30fcfSMel Gorman 		int zid;
1491d7f05528SMel Gorman 		unsigned long total_skipped = 0;
14927cc30fcfSMel Gorman 
14937cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14947cc30fcfSMel Gorman 			if (!nr_skipped[zid])
14957cc30fcfSMel Gorman 				continue;
14967cc30fcfSMel Gorman 
14977cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1498d7f05528SMel Gorman 			total_skipped += nr_skipped[zid];
14997cc30fcfSMel Gorman 		}
1500d7f05528SMel Gorman 
1501d7f05528SMel Gorman 		/*
1502d7f05528SMel Gorman 		 * Account skipped pages as a partial scan as the pgdat may be
1503d7f05528SMel Gorman 		 * close to unreclaimable. If the LRU list is empty, account
1504d7f05528SMel Gorman 		 * skipped pages as a full scan.
1505d7f05528SMel Gorman 		 */
1506d7f05528SMel Gorman 		scan += list_empty(src) ? total_skipped : total_skipped >> 2;
1507d7f05528SMel Gorman 
1508d7f05528SMel Gorman 		list_splice(&pages_skipped, src);
15097cc30fcfSMel Gorman 	}
1510f626012dSHugh Dickins 	*nr_scanned = scan;
1511e5146b12SMel Gorman 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan, scan,
151275b00af7SHugh Dickins 				    nr_taken, mode, is_file_lru(lru));
1513*b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15141da177e4SLinus Torvalds 	return nr_taken;
15151da177e4SLinus Torvalds }
15161da177e4SLinus Torvalds 
151762695a84SNick Piggin /**
151862695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
151962695a84SNick Piggin  * @page: page to isolate from its LRU list
152062695a84SNick Piggin  *
152162695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
152262695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
152362695a84SNick Piggin  *
152462695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
152562695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
152662695a84SNick Piggin  *
152762695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1528894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1529894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1530894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
153162695a84SNick Piggin  *
153262695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
153362695a84SNick Piggin  * found will be decremented.
153462695a84SNick Piggin  *
153562695a84SNick Piggin  * Restrictions:
153662695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
153762695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
153862695a84SNick Piggin  *     without a stable reference).
153962695a84SNick Piggin  * (2) the lru_lock must not be held.
154062695a84SNick Piggin  * (3) interrupts must be enabled.
154162695a84SNick Piggin  */
154262695a84SNick Piggin int isolate_lru_page(struct page *page)
154362695a84SNick Piggin {
154462695a84SNick Piggin 	int ret = -EBUSY;
154562695a84SNick Piggin 
1546309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1547cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15480c917313SKonstantin Khlebnikov 
154962695a84SNick Piggin 	if (PageLRU(page)) {
155062695a84SNick Piggin 		struct zone *zone = page_zone(page);
1551fa9add64SHugh Dickins 		struct lruvec *lruvec;
155262695a84SNick Piggin 
1553a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1554599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
15550c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1556894bc310SLee Schermerhorn 			int lru = page_lru(page);
15570c917313SKonstantin Khlebnikov 			get_page(page);
155862695a84SNick Piggin 			ClearPageLRU(page);
1559fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1560fa9add64SHugh Dickins 			ret = 0;
156162695a84SNick Piggin 		}
1562a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
156362695a84SNick Piggin 	}
156462695a84SNick Piggin 	return ret;
156562695a84SNick Piggin }
156662695a84SNick Piggin 
15675ad333ebSAndy Whitcroft /*
1568d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1569d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1570d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1571d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1572d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
157335cd7815SRik van Riel  */
1574599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
157535cd7815SRik van Riel 		struct scan_control *sc)
157635cd7815SRik van Riel {
157735cd7815SRik van Riel 	unsigned long inactive, isolated;
157835cd7815SRik van Riel 
157935cd7815SRik van Riel 	if (current_is_kswapd())
158035cd7815SRik van Riel 		return 0;
158135cd7815SRik van Riel 
158297c9341fSTejun Heo 	if (!sane_reclaim(sc))
158335cd7815SRik van Riel 		return 0;
158435cd7815SRik van Riel 
158535cd7815SRik van Riel 	if (file) {
1586599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1587599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
158835cd7815SRik van Riel 	} else {
1589599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1590599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
159135cd7815SRik van Riel 	}
159235cd7815SRik van Riel 
15933cf23841SFengguang Wu 	/*
15943cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
15953cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
15963cf23841SFengguang Wu 	 * deadlock.
15973cf23841SFengguang Wu 	 */
1598d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
15993cf23841SFengguang Wu 		inactive >>= 3;
16003cf23841SFengguang Wu 
160135cd7815SRik van Riel 	return isolated > inactive;
160235cd7815SRik van Riel }
160335cd7815SRik van Riel 
160466635629SMel Gorman static noinline_for_stack void
160575b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
160666635629SMel Gorman {
160727ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1608599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16093f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
161066635629SMel Gorman 
161166635629SMel Gorman 	/*
161266635629SMel Gorman 	 * Put back any unfreeable pages.
161366635629SMel Gorman 	 */
161466635629SMel Gorman 	while (!list_empty(page_list)) {
16153f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
161666635629SMel Gorman 		int lru;
16173f79768fSHugh Dickins 
1618309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
161966635629SMel Gorman 		list_del(&page->lru);
162039b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1621599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
162266635629SMel Gorman 			putback_lru_page(page);
1623599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
162466635629SMel Gorman 			continue;
162566635629SMel Gorman 		}
1626fa9add64SHugh Dickins 
1627599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1628fa9add64SHugh Dickins 
16297a608572SLinus Torvalds 		SetPageLRU(page);
163066635629SMel Gorman 		lru = page_lru(page);
1631fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1632fa9add64SHugh Dickins 
163366635629SMel Gorman 		if (is_active_lru(lru)) {
163466635629SMel Gorman 			int file = is_file_lru(lru);
16359992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16369992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
163766635629SMel Gorman 		}
16382bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16392bcf8879SHugh Dickins 			__ClearPageLRU(page);
16402bcf8879SHugh Dickins 			__ClearPageActive(page);
1641fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16422bcf8879SHugh Dickins 
16432bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1644599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1645747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16462bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1647599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16482bcf8879SHugh Dickins 			} else
16492bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
165066635629SMel Gorman 		}
165166635629SMel Gorman 	}
165266635629SMel Gorman 
16533f79768fSHugh Dickins 	/*
16543f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
16553f79768fSHugh Dickins 	 */
16563f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
165766635629SMel Gorman }
165866635629SMel Gorman 
165966635629SMel Gorman /*
1660399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1661399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1662399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1663399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1664399ba0b9SNeilBrown  */
1665399ba0b9SNeilBrown static int current_may_throttle(void)
1666399ba0b9SNeilBrown {
1667399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1668399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1669399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1670399ba0b9SNeilBrown }
1671399ba0b9SNeilBrown 
167291dcade4SMinchan Kim static bool inactive_reclaimable_pages(struct lruvec *lruvec,
167391dcade4SMinchan Kim 				struct scan_control *sc, enum lru_list lru)
167491dcade4SMinchan Kim {
167591dcade4SMinchan Kim 	int zid;
167691dcade4SMinchan Kim 	struct zone *zone;
167791dcade4SMinchan Kim 	int file = is_file_lru(lru);
167891dcade4SMinchan Kim 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
167991dcade4SMinchan Kim 
168091dcade4SMinchan Kim 	if (!global_reclaim(sc))
168191dcade4SMinchan Kim 		return true;
168291dcade4SMinchan Kim 
168391dcade4SMinchan Kim 	for (zid = sc->reclaim_idx; zid >= 0; zid--) {
168491dcade4SMinchan Kim 		zone = &pgdat->node_zones[zid];
16856aa303deSMel Gorman 		if (!managed_zone(zone))
168691dcade4SMinchan Kim 			continue;
168791dcade4SMinchan Kim 
168891dcade4SMinchan Kim 		if (zone_page_state_snapshot(zone, NR_ZONE_LRU_BASE +
168991dcade4SMinchan Kim 				LRU_FILE * file) >= SWAP_CLUSTER_MAX)
169091dcade4SMinchan Kim 			return true;
169191dcade4SMinchan Kim 	}
169291dcade4SMinchan Kim 
169391dcade4SMinchan Kim 	return false;
169491dcade4SMinchan Kim }
169591dcade4SMinchan Kim 
1696399ba0b9SNeilBrown /*
1697b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16981742f19fSAndrew Morton  * of reclaimed pages
16991da177e4SLinus Torvalds  */
170066635629SMel Gorman static noinline_for_stack unsigned long
17011a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
17029e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
17031da177e4SLinus Torvalds {
17041da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1705e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
170605ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1707e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
17088e950282SMel Gorman 	unsigned long nr_dirty = 0;
17098e950282SMel Gorman 	unsigned long nr_congested = 0;
1710e2be15f6SMel Gorman 	unsigned long nr_unqueued_dirty = 0;
171192df3a72SMel Gorman 	unsigned long nr_writeback = 0;
1712b1a6f21eSMel Gorman 	unsigned long nr_immediate = 0;
1713f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17143cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1715599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17161a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
171778dc583dSKOSAKI Motohiro 
171891dcade4SMinchan Kim 	if (!inactive_reclaimable_pages(lruvec, sc, lru))
171991dcade4SMinchan Kim 		return 0;
172091dcade4SMinchan Kim 
1721599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
172258355c78SKOSAKI Motohiro 		congestion_wait(BLK_RW_ASYNC, HZ/10);
172335cd7815SRik van Riel 
172435cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
172535cd7815SRik van Riel 		if (fatal_signal_pending(current))
172635cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
172735cd7815SRik van Riel 	}
172835cd7815SRik van Riel 
17291da177e4SLinus Torvalds 	lru_add_drain();
1730f80c0673SMinchan Kim 
1731f80c0673SMinchan Kim 	if (!sc->may_unmap)
173261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1733f80c0673SMinchan Kim 	if (!sc->may_writepage)
173461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1735f80c0673SMinchan Kim 
1736599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17371da177e4SLinus Torvalds 
17385dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17395dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
174095d918fcSKonstantin Khlebnikov 
1741599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17429d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
174395d918fcSKonstantin Khlebnikov 
174489b5fae5SJohannes Weiner 	if (global_reclaim(sc)) {
1745599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1746b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1747599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
1748b35ea17bSKOSAKI Motohiro 		else
1749599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
1750b35ea17bSKOSAKI Motohiro 	}
1751599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1752d563c050SHillf Danton 
1753d563c050SHillf Danton 	if (nr_taken == 0)
175466635629SMel Gorman 		return 0;
1755b35ea17bSKOSAKI Motohiro 
1756599d0c95SMel Gorman 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, TTU_UNMAP,
17578e950282SMel Gorman 				&nr_dirty, &nr_unqueued_dirty, &nr_congested,
17588e950282SMel Gorman 				&nr_writeback, &nr_immediate,
1759b1a6f21eSMel Gorman 				false);
1760c661b078SAndy Whitcroft 
1761599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17623f79768fSHugh Dickins 
1763904249aaSYing Han 	if (global_reclaim(sc)) {
1764b35ea17bSKOSAKI Motohiro 		if (current_is_kswapd())
1765599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
1766904249aaSYing Han 		else
1767599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
1768904249aaSYing Han 	}
1769a74609faSNick Piggin 
177027ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
17713f79768fSHugh Dickins 
1772599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
17733f79768fSHugh Dickins 
1774599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
17753f79768fSHugh Dickins 
1776747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
1777b745bc85SMel Gorman 	free_hot_cold_page_list(&page_list, true);
1778e11da5b4SMel Gorman 
177992df3a72SMel Gorman 	/*
178092df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
178192df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
178292df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
178392df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
178492df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
178592df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
178692df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
178792df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
178892df3a72SMel Gorman 	 *
17898e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
17908e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17918e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
179292df3a72SMel Gorman 	 */
1793918fc718SMel Gorman 	if (nr_writeback && nr_writeback == nr_taken)
1794599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
179592df3a72SMel Gorman 
1796d43006d5SMel Gorman 	/*
179797c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
179897c9341fSTejun Heo 	 * stalling here.
1799d43006d5SMel Gorman 	 */
180097c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1801b1a6f21eSMel Gorman 		/*
18028e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
18038e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
18048e950282SMel Gorman 		 */
18058e950282SMel Gorman 		if (nr_dirty && nr_dirty == nr_congested)
1806599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
18078e950282SMel Gorman 
18088e950282SMel Gorman 		/*
1809b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1810b1a6f21eSMel Gorman 		 * implies that flushers are not keeping up. In this case, flag
1811599d0c95SMel Gorman 		 * the pgdat PGDAT_DIRTY and kswapd will start writing pages from
181257054651SJohannes Weiner 		 * reclaim context.
1813b1a6f21eSMel Gorman 		 */
1814b1a6f21eSMel Gorman 		if (nr_unqueued_dirty == nr_taken)
1815599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1816b1a6f21eSMel Gorman 
1817b1a6f21eSMel Gorman 		/*
1818b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1819b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1820b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1821b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1822b1a6f21eSMel Gorman 		 */
1823b738d764SLinus Torvalds 		if (nr_immediate && current_may_throttle())
1824b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1825e2be15f6SMel Gorman 	}
1826d43006d5SMel Gorman 
18278e950282SMel Gorman 	/*
18288e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
18298e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18308e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18318e950282SMel Gorman 	 */
1832399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1833399ba0b9SNeilBrown 	    current_may_throttle())
1834599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18358e950282SMel Gorman 
1836599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1837599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
1838ba5e9579Syalin wang 			sc->priority, file);
183905ff5137SAndrew Morton 	return nr_reclaimed;
18401da177e4SLinus Torvalds }
18411da177e4SLinus Torvalds 
18423bb1a852SMartin Bligh /*
18431cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18441cfb419bSKAMEZAWA Hiroyuki  *
18451cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18461cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18471cfb419bSKAMEZAWA Hiroyuki  *
18481cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1849a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18501cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1851a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18521cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18531cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18541cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18551cfb419bSKAMEZAWA Hiroyuki  *
18560139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18571cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
18581cfb419bSKAMEZAWA Hiroyuki  */
18591cfb419bSKAMEZAWA Hiroyuki 
1860fa9add64SHugh Dickins static void move_active_pages_to_lru(struct lruvec *lruvec,
18613eb4140fSWu Fengguang 				     struct list_head *list,
18622bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18633eb4140fSWu Fengguang 				     enum lru_list lru)
18643eb4140fSWu Fengguang {
1865599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18663eb4140fSWu Fengguang 	unsigned long pgmoved = 0;
18673eb4140fSWu Fengguang 	struct page *page;
1868fa9add64SHugh Dickins 	int nr_pages;
18693eb4140fSWu Fengguang 
18703eb4140fSWu Fengguang 	while (!list_empty(list)) {
18713eb4140fSWu Fengguang 		page = lru_to_page(list);
1872599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18733eb4140fSWu Fengguang 
1874309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18753eb4140fSWu Fengguang 		SetPageLRU(page);
18763eb4140fSWu Fengguang 
1877fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1878599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1879925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
1880fa9add64SHugh Dickins 		pgmoved += nr_pages;
18813eb4140fSWu Fengguang 
18822bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18832bcf8879SHugh Dickins 			__ClearPageLRU(page);
18842bcf8879SHugh Dickins 			__ClearPageActive(page);
1885fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18862bcf8879SHugh Dickins 
18872bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1888599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1889747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18902bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1891599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18922bcf8879SHugh Dickins 			} else
18932bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18943eb4140fSWu Fengguang 		}
18953eb4140fSWu Fengguang 	}
18969d5e6a9fSHugh Dickins 
18973eb4140fSWu Fengguang 	if (!is_active_lru(lru))
18983eb4140fSWu Fengguang 		__count_vm_events(PGDEACTIVATE, pgmoved);
18993eb4140fSWu Fengguang }
19001cfb419bSKAMEZAWA Hiroyuki 
1901f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19021a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1903f16015fbSJohannes Weiner 			       struct scan_control *sc,
19049e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19051cfb419bSKAMEZAWA Hiroyuki {
190644c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1907f626012dSHugh Dickins 	unsigned long nr_scanned;
19086fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19091cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19108cab4754SWu Fengguang 	LIST_HEAD(l_active);
1911b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19121cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19131a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
191444c241f1SKOSAKI Motohiro 	unsigned long nr_rotated = 0;
1915f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19163cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1917599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19181cfb419bSKAMEZAWA Hiroyuki 
19191da177e4SLinus Torvalds 	lru_add_drain();
1920f80c0673SMinchan Kim 
1921f80c0673SMinchan Kim 	if (!sc->may_unmap)
192261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1923f80c0673SMinchan Kim 	if (!sc->may_writepage)
192461317289SHillf Danton 		isolate_mode |= ISOLATE_CLEAN;
1925f80c0673SMinchan Kim 
1926599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1927925b7673SJohannes Weiner 
19285dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19295dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
193089b5fae5SJohannes Weiner 
1931599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1932b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19331cfb419bSKAMEZAWA Hiroyuki 
19349d5e6a9fSHugh Dickins 	if (global_reclaim(sc))
1935599d0c95SMel Gorman 		__mod_node_page_state(pgdat, NR_PAGES_SCANNED, nr_scanned);
1936599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19379d5e6a9fSHugh Dickins 
1938599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19391da177e4SLinus Torvalds 
19401da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19411da177e4SLinus Torvalds 		cond_resched();
19421da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19431da177e4SLinus Torvalds 		list_del(&page->lru);
19447e9cd484SRik van Riel 
194539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1946894bc310SLee Schermerhorn 			putback_lru_page(page);
1947894bc310SLee Schermerhorn 			continue;
1948894bc310SLee Schermerhorn 		}
1949894bc310SLee Schermerhorn 
1950cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1951cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1952cc715d99SMel Gorman 				if (page_has_private(page))
1953cc715d99SMel Gorman 					try_to_release_page(page, 0);
1954cc715d99SMel Gorman 				unlock_page(page);
1955cc715d99SMel Gorman 			}
1956cc715d99SMel Gorman 		}
1957cc715d99SMel Gorman 
1958c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1959c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19609992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19618cab4754SWu Fengguang 			/*
19628cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19638cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19648cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19658cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19668cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19678cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19688cab4754SWu Fengguang 			 * so we ignore them here.
19698cab4754SWu Fengguang 			 */
197041e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19718cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19728cab4754SWu Fengguang 				continue;
19738cab4754SWu Fengguang 			}
19748cab4754SWu Fengguang 		}
19757e9cd484SRik van Riel 
19765205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19771da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19781da177e4SLinus Torvalds 	}
19791da177e4SLinus Torvalds 
1980b555749aSAndrew Morton 	/*
19818cab4754SWu Fengguang 	 * Move pages back to the lru list.
1982b555749aSAndrew Morton 	 */
1983599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19844f98a2feSRik van Riel 	/*
19858cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19868cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19878cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19887c0db9e9SJerome Marchand 	 * get_scan_count.
1989556adecbSRik van Riel 	 */
1990b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1991556adecbSRik van Riel 
1992fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1993fa9add64SHugh Dickins 	move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1994599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1995599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19962bcf8879SHugh Dickins 
1997747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
1998b745bc85SMel Gorman 	free_hot_cold_page_list(&l_hold, true);
19991da177e4SLinus Torvalds }
20001da177e4SLinus Torvalds 
200159dc76b0SRik van Riel /*
200259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
200359dc76b0SRik van Riel  * to do too much work.
200414797e23SKOSAKI Motohiro  *
200559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
200659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
200759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
200859dc76b0SRik van Riel  *
200959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
201059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
201159dc76b0SRik van Riel  *
201259dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
201359dc76b0SRik van Riel  * on this LRU, maintained by the pageout code. A zone->inactive_ratio
201459dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
201559dc76b0SRik van Riel  *
201659dc76b0SRik van Riel  * total     target    max
201759dc76b0SRik van Riel  * memory    ratio     inactive
201859dc76b0SRik van Riel  * -------------------------------------
201959dc76b0SRik van Riel  *   10MB       1         5MB
202059dc76b0SRik van Riel  *  100MB       1        50MB
202159dc76b0SRik van Riel  *    1GB       3       250MB
202259dc76b0SRik van Riel  *   10GB      10       0.9GB
202359dc76b0SRik van Riel  *  100GB      31         3GB
202459dc76b0SRik van Riel  *    1TB     101        10GB
202559dc76b0SRik van Riel  *   10TB     320        32GB
202614797e23SKOSAKI Motohiro  */
2027f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
2028f8d1a311SMel Gorman 						struct scan_control *sc)
202914797e23SKOSAKI Motohiro {
203059dc76b0SRik van Riel 	unsigned long inactive_ratio;
203159dc76b0SRik van Riel 	unsigned long inactive;
203259dc76b0SRik van Riel 	unsigned long active;
203359dc76b0SRik van Riel 	unsigned long gb;
2034f8d1a311SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2035f8d1a311SMel Gorman 	int zid;
203659dc76b0SRik van Riel 
203774e3f3c3SMinchan Kim 	/*
203874e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
203974e3f3c3SMinchan Kim 	 * is pointless.
204074e3f3c3SMinchan Kim 	 */
204159dc76b0SRik van Riel 	if (!file && !total_swap_pages)
204242e2e457SYaowei Bai 		return false;
204374e3f3c3SMinchan Kim 
204459dc76b0SRik van Riel 	inactive = lruvec_lru_size(lruvec, file * LRU_FILE);
204559dc76b0SRik van Riel 	active = lruvec_lru_size(lruvec, file * LRU_FILE + LRU_ACTIVE);
2046f16015fbSJohannes Weiner 
2047f8d1a311SMel Gorman 	/*
2048f8d1a311SMel Gorman 	 * For zone-constrained allocations, it is necessary to check if
2049f8d1a311SMel Gorman 	 * deactivations are required for lowmem to be reclaimed. This
2050f8d1a311SMel Gorman 	 * calculates the inactive/active pages available in eligible zones.
2051f8d1a311SMel Gorman 	 */
2052f8d1a311SMel Gorman 	for (zid = sc->reclaim_idx + 1; zid < MAX_NR_ZONES; zid++) {
2053f8d1a311SMel Gorman 		struct zone *zone = &pgdat->node_zones[zid];
2054f8d1a311SMel Gorman 		unsigned long inactive_zone, active_zone;
2055f8d1a311SMel Gorman 
20566aa303deSMel Gorman 		if (!managed_zone(zone))
2057f8d1a311SMel Gorman 			continue;
2058f8d1a311SMel Gorman 
2059*b4536f0cSMichal Hocko 		inactive_zone = lruvec_zone_lru_size(lruvec, file * LRU_FILE, zid);
2060*b4536f0cSMichal Hocko 		active_zone = lruvec_zone_lru_size(lruvec, (file * LRU_FILE) + LRU_ACTIVE, zid);
2061f8d1a311SMel Gorman 
2062f8d1a311SMel Gorman 		inactive -= min(inactive, inactive_zone);
2063f8d1a311SMel Gorman 		active -= min(active, active_zone);
2064f8d1a311SMel Gorman 	}
2065f8d1a311SMel Gorman 
206659dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
206759dc76b0SRik van Riel 	if (gb)
206859dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2069b39415b2SRik van Riel 	else
207059dc76b0SRik van Riel 		inactive_ratio = 1;
207159dc76b0SRik van Riel 
207259dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2073b39415b2SRik van Riel }
2074b39415b2SRik van Riel 
20754f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
20761a93be0eSKonstantin Khlebnikov 				 struct lruvec *lruvec, struct scan_control *sc)
2077b69408e8SChristoph Lameter {
2078b39415b2SRik van Riel 	if (is_active_lru(lru)) {
2079f8d1a311SMel Gorman 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc))
20801a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2081556adecbSRik van Riel 		return 0;
2082556adecbSRik van Riel 	}
2083556adecbSRik van Riel 
20841a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2085b69408e8SChristoph Lameter }
2086b69408e8SChristoph Lameter 
20879a265114SJohannes Weiner enum scan_balance {
20889a265114SJohannes Weiner 	SCAN_EQUAL,
20899a265114SJohannes Weiner 	SCAN_FRACT,
20909a265114SJohannes Weiner 	SCAN_ANON,
20919a265114SJohannes Weiner 	SCAN_FILE,
20929a265114SJohannes Weiner };
20939a265114SJohannes Weiner 
20941da177e4SLinus Torvalds /*
20954f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
20964f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
20974f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
20984f98a2feSRik van Riel  * onto the active list instead of evict.
20994f98a2feSRik van Riel  *
2100be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2101be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
21024f98a2feSRik van Riel  */
210333377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
21046b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
21056b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
21064f98a2feSRik van Riel {
210733377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
210890126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
21099a265114SJohannes Weiner 	u64 fraction[2];
21109a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2111599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21129a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
21139a265114SJohannes Weiner 	enum scan_balance scan_balance;
21140bf1457fSJohannes Weiner 	unsigned long anon, file;
21159a265114SJohannes Weiner 	bool force_scan = false;
21169a265114SJohannes Weiner 	unsigned long ap, fp;
21179a265114SJohannes Weiner 	enum lru_list lru;
21186f04f48dSSuleiman Souhlal 	bool some_scanned;
21196f04f48dSSuleiman Souhlal 	int pass;
2120246e87a9SKAMEZAWA Hiroyuki 
2121f11c0ca5SJohannes Weiner 	/*
2122f11c0ca5SJohannes Weiner 	 * If the zone or memcg is small, nr[l] can be 0.  This
2123f11c0ca5SJohannes Weiner 	 * results in no scanning on this priority and a potential
2124f11c0ca5SJohannes Weiner 	 * priority drop.  Global direct reclaim can go to the next
2125f11c0ca5SJohannes Weiner 	 * zone and tends to have no problems. Global kswapd is for
2126f11c0ca5SJohannes Weiner 	 * zone balancing and it needs to scan a minimum amount. When
2127f11c0ca5SJohannes Weiner 	 * reclaiming for a memcg, a priority drop can cause high
2128f11c0ca5SJohannes Weiner 	 * latencies, so it's better to scan a minimum amount there as
2129f11c0ca5SJohannes Weiner 	 * well.
2130f11c0ca5SJohannes Weiner 	 */
213190cbc250SVladimir Davydov 	if (current_is_kswapd()) {
2132599d0c95SMel Gorman 		if (!pgdat_reclaimable(pgdat))
2133a4d3e9e7SJohannes Weiner 			force_scan = true;
2134eb01aaabSVladimir Davydov 		if (!mem_cgroup_online(memcg))
213590cbc250SVladimir Davydov 			force_scan = true;
213690cbc250SVladimir Davydov 	}
213789b5fae5SJohannes Weiner 	if (!global_reclaim(sc))
2138a4d3e9e7SJohannes Weiner 		force_scan = true;
213976a33fc3SShaohua Li 
214076a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2141d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21429a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
214376a33fc3SShaohua Li 		goto out;
214476a33fc3SShaohua Li 	}
21454f98a2feSRik van Riel 
214610316b31SJohannes Weiner 	/*
214710316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
214810316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
214910316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
215010316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
215110316b31SJohannes Weiner 	 * too expensive.
215210316b31SJohannes Weiner 	 */
215302695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21549a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
215510316b31SJohannes Weiner 		goto out;
215610316b31SJohannes Weiner 	}
215710316b31SJohannes Weiner 
215810316b31SJohannes Weiner 	/*
215910316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
216010316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
216110316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
216210316b31SJohannes Weiner 	 */
216302695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21649a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
216510316b31SJohannes Weiner 		goto out;
216610316b31SJohannes Weiner 	}
216710316b31SJohannes Weiner 
216811d16c25SJohannes Weiner 	/*
216962376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
217062376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
217162376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
217262376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
217362376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
217462376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
217562376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
217662376251SJohannes Weiner 	 */
217762376251SJohannes Weiner 	if (global_reclaim(sc)) {
2178599d0c95SMel Gorman 		unsigned long pgdatfile;
2179599d0c95SMel Gorman 		unsigned long pgdatfree;
2180599d0c95SMel Gorman 		int z;
2181599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
218262376251SJohannes Weiner 
2183599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2184599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2185599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21862ab051e1SJerome Marchand 
2187599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2188599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
21896aa303deSMel Gorman 			if (!managed_zone(zone))
2190599d0c95SMel Gorman 				continue;
2191599d0c95SMel Gorman 
2192599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2193599d0c95SMel Gorman 		}
2194599d0c95SMel Gorman 
2195599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
219662376251SJohannes Weiner 			scan_balance = SCAN_ANON;
219762376251SJohannes Weiner 			goto out;
219862376251SJohannes Weiner 		}
219962376251SJohannes Weiner 	}
220062376251SJohannes Weiner 
220162376251SJohannes Weiner 	/*
2202316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2203316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2204316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2205316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2206316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2207316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2208316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2209e9868505SRik van Riel 	 */
2210f8d1a311SMel Gorman 	if (!inactive_list_is_low(lruvec, true, sc) &&
221123047a96SJohannes Weiner 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE) >> sc->priority) {
22129a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2213e9868505SRik van Riel 		goto out;
22144f98a2feSRik van Riel 	}
22154f98a2feSRik van Riel 
22169a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22179a265114SJohannes Weiner 
22184f98a2feSRik van Riel 	/*
221958c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
222058c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
222158c37f6eSKOSAKI Motohiro 	 */
222202695175SJohannes Weiner 	anon_prio = swappiness;
222375b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
222458c37f6eSKOSAKI Motohiro 
222558c37f6eSKOSAKI Motohiro 	/*
22264f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22274f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22284f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22294f98a2feSRik van Riel 	 *
22304f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22314f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22324f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22334f98a2feSRik van Riel 	 *
22344f98a2feSRik van Riel 	 * anon in [0], file in [1]
22354f98a2feSRik van Riel 	 */
22362ab051e1SJerome Marchand 
223723047a96SJohannes Weiner 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON) +
223823047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON);
223923047a96SJohannes Weiner 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE) +
224023047a96SJohannes Weiner 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE);
22412ab051e1SJerome Marchand 
2242599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
224358c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22446e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22456e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22464f98a2feSRik van Riel 	}
22474f98a2feSRik van Riel 
22486e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22496e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22506e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22514f98a2feSRik van Riel 	}
22524f98a2feSRik van Riel 
22534f98a2feSRik van Riel 	/*
225400d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
225500d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
225600d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22574f98a2feSRik van Riel 	 */
2258fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22596e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22604f98a2feSRik van Riel 
2261fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22626e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2263599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22644f98a2feSRik van Riel 
226576a33fc3SShaohua Li 	fraction[0] = ap;
226676a33fc3SShaohua Li 	fraction[1] = fp;
226776a33fc3SShaohua Li 	denominator = ap + fp + 1;
226876a33fc3SShaohua Li out:
22696f04f48dSSuleiman Souhlal 	some_scanned = false;
22706f04f48dSSuleiman Souhlal 	/* Only use force_scan on second pass. */
22716f04f48dSSuleiman Souhlal 	for (pass = 0; !some_scanned && pass < 2; pass++) {
22726b4f7799SJohannes Weiner 		*lru_pages = 0;
22734111304dSHugh Dickins 		for_each_evictable_lru(lru) {
22744111304dSHugh Dickins 			int file = is_file_lru(lru);
2275d778df51SJohannes Weiner 			unsigned long size;
227676a33fc3SShaohua Li 			unsigned long scan;
227776a33fc3SShaohua Li 
227823047a96SJohannes Weiner 			size = lruvec_lru_size(lruvec, lru);
2279d778df51SJohannes Weiner 			scan = size >> sc->priority;
22809a265114SJohannes Weiner 
22816f04f48dSSuleiman Souhlal 			if (!scan && pass && force_scan)
2282d778df51SJohannes Weiner 				scan = min(size, SWAP_CLUSTER_MAX);
22839a265114SJohannes Weiner 
22849a265114SJohannes Weiner 			switch (scan_balance) {
22859a265114SJohannes Weiner 			case SCAN_EQUAL:
22869a265114SJohannes Weiner 				/* Scan lists relative to size */
22879a265114SJohannes Weiner 				break;
22889a265114SJohannes Weiner 			case SCAN_FRACT:
22899a265114SJohannes Weiner 				/*
22909a265114SJohannes Weiner 				 * Scan types proportional to swappiness and
22919a265114SJohannes Weiner 				 * their relative recent reclaim efficiency.
22929a265114SJohannes Weiner 				 */
22936f04f48dSSuleiman Souhlal 				scan = div64_u64(scan * fraction[file],
22946f04f48dSSuleiman Souhlal 							denominator);
22959a265114SJohannes Weiner 				break;
22969a265114SJohannes Weiner 			case SCAN_FILE:
22979a265114SJohannes Weiner 			case SCAN_ANON:
22989a265114SJohannes Weiner 				/* Scan one type exclusively */
22996b4f7799SJohannes Weiner 				if ((scan_balance == SCAN_FILE) != file) {
23006b4f7799SJohannes Weiner 					size = 0;
23019a265114SJohannes Weiner 					scan = 0;
23026b4f7799SJohannes Weiner 				}
23039a265114SJohannes Weiner 				break;
23049a265114SJohannes Weiner 			default:
23059a265114SJohannes Weiner 				/* Look ma, no brain */
23069a265114SJohannes Weiner 				BUG();
23079a265114SJohannes Weiner 			}
23086b4f7799SJohannes Weiner 
23096b4f7799SJohannes Weiner 			*lru_pages += size;
23104111304dSHugh Dickins 			nr[lru] = scan;
23116b4f7799SJohannes Weiner 
23126f04f48dSSuleiman Souhlal 			/*
23136f04f48dSSuleiman Souhlal 			 * Skip the second pass and don't force_scan,
23146f04f48dSSuleiman Souhlal 			 * if we found something to scan.
23156f04f48dSSuleiman Souhlal 			 */
23166f04f48dSSuleiman Souhlal 			some_scanned |= !!scan;
23176f04f48dSSuleiman Souhlal 		}
231876a33fc3SShaohua Li 	}
23196e08a369SWu Fengguang }
23204f98a2feSRik van Riel 
23219b4f98cdSJohannes Weiner /*
2322a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23239b4f98cdSJohannes Weiner  */
2324a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23256b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23269b4f98cdSJohannes Weiner {
2327ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23289b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2329e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23309b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23319b4f98cdSJohannes Weiner 	enum lru_list lru;
23329b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23339b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23349b4f98cdSJohannes Weiner 	struct blk_plug plug;
23351a501907SMel Gorman 	bool scan_adjusted;
23369b4f98cdSJohannes Weiner 
233733377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23389b4f98cdSJohannes Weiner 
2339e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2340e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2341e82e0561SMel Gorman 
23421a501907SMel Gorman 	/*
23431a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23441a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23451a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23461a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23471a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23481a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23491a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23501a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23511a501907SMel Gorman 	 * dropped to zero at the first pass.
23521a501907SMel Gorman 	 */
23531a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23541a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23551a501907SMel Gorman 
23569b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23579b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23589b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2359e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2360e82e0561SMel Gorman 		unsigned long nr_scanned;
2361e82e0561SMel Gorman 
23629b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23639b4f98cdSJohannes Weiner 			if (nr[lru]) {
23649b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23659b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23669b4f98cdSJohannes Weiner 
23679b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23689b4f98cdSJohannes Weiner 							    lruvec, sc);
23699b4f98cdSJohannes Weiner 			}
23709b4f98cdSJohannes Weiner 		}
2371e82e0561SMel Gorman 
2372bd041733SMichal Hocko 		cond_resched();
2373bd041733SMichal Hocko 
2374e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2375e82e0561SMel Gorman 			continue;
2376e82e0561SMel Gorman 
23779b4f98cdSJohannes Weiner 		/*
2378e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23791a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2380e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2381e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2382e82e0561SMel Gorman 		 * proportional to the original scan target.
2383e82e0561SMel Gorman 		 */
2384e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2385e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2386e82e0561SMel Gorman 
23871a501907SMel Gorman 		/*
23881a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23891a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23901a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23911a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23921a501907SMel Gorman 		 */
23931a501907SMel Gorman 		if (!nr_file || !nr_anon)
23941a501907SMel Gorman 			break;
23951a501907SMel Gorman 
2396e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2397e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2398e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2399e82e0561SMel Gorman 			lru = LRU_BASE;
2400e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2401e82e0561SMel Gorman 		} else {
2402e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2403e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2404e82e0561SMel Gorman 			lru = LRU_FILE;
2405e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2406e82e0561SMel Gorman 		}
2407e82e0561SMel Gorman 
2408e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2409e82e0561SMel Gorman 		nr[lru] = 0;
2410e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2411e82e0561SMel Gorman 
2412e82e0561SMel Gorman 		/*
2413e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2414e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2415e82e0561SMel Gorman 		 */
2416e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2417e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2418e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2419e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2420e82e0561SMel Gorman 
2421e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2422e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2423e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2424e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2425e82e0561SMel Gorman 
2426e82e0561SMel Gorman 		scan_adjusted = true;
24279b4f98cdSJohannes Weiner 	}
24289b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24299b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24309b4f98cdSJohannes Weiner 
24319b4f98cdSJohannes Weiner 	/*
24329b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24339b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24349b4f98cdSJohannes Weiner 	 */
2435f8d1a311SMel Gorman 	if (inactive_list_is_low(lruvec, false, sc))
24369b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24379b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24389b4f98cdSJohannes Weiner }
24399b4f98cdSJohannes Weiner 
244023b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24419e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
244223b9da55SMel Gorman {
2443d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
244423b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24459e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
244623b9da55SMel Gorman 		return true;
244723b9da55SMel Gorman 
244823b9da55SMel Gorman 	return false;
244923b9da55SMel Gorman }
245023b9da55SMel Gorman 
24514f98a2feSRik van Riel /*
245223b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
245323b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
245423b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
245523b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
245623b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24573e7d3449SMel Gorman  */
2458a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24593e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24603e7d3449SMel Gorman 					unsigned long nr_scanned,
24613e7d3449SMel Gorman 					struct scan_control *sc)
24623e7d3449SMel Gorman {
24633e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24643e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2465a9dd0a83SMel Gorman 	int z;
24663e7d3449SMel Gorman 
24673e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24689e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24693e7d3449SMel Gorman 		return false;
24703e7d3449SMel Gorman 
24712876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
24722876592fSMel Gorman 	if (sc->gfp_mask & __GFP_REPEAT) {
24733e7d3449SMel Gorman 		/*
24742876592fSMel Gorman 		 * For __GFP_REPEAT allocations, stop reclaiming if the
24752876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24762876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
24772876592fSMel Gorman 		 * expensive but a __GFP_REPEAT caller really wants to succeed
24783e7d3449SMel Gorman 		 */
24793e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24803e7d3449SMel Gorman 			return false;
24812876592fSMel Gorman 	} else {
24822876592fSMel Gorman 		/*
24832876592fSMel Gorman 		 * For non-__GFP_REPEAT allocations which can presumably
24842876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24852876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24862876592fSMel Gorman 		 * pages that were scanned. This will return to the
24872876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24882876592fSMel Gorman 		 * the resulting allocation attempt fails
24892876592fSMel Gorman 		 */
24902876592fSMel Gorman 		if (!nr_reclaimed)
24912876592fSMel Gorman 			return false;
24922876592fSMel Gorman 	}
24933e7d3449SMel Gorman 
24943e7d3449SMel Gorman 	/*
24953e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24963e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24973e7d3449SMel Gorman 	 */
24989861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2499a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2500ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2501a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
25023e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
25033e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
25043e7d3449SMel Gorman 		return true;
25053e7d3449SMel Gorman 
25063e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2507a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2508a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25096aa303deSMel Gorman 		if (!managed_zone(zone))
2510a9dd0a83SMel Gorman 			continue;
2511a9dd0a83SMel Gorman 
2512a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2513cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25143e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25153e7d3449SMel Gorman 			return false;
25163e7d3449SMel Gorman 		default:
2517a9dd0a83SMel Gorman 			/* check next zone */
2518a9dd0a83SMel Gorman 			;
25193e7d3449SMel Gorman 		}
25203e7d3449SMel Gorman 	}
2521a9dd0a83SMel Gorman 	return true;
2522a9dd0a83SMel Gorman }
25233e7d3449SMel Gorman 
2524970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2525f16015fbSJohannes Weiner {
2526cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25279b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25282344d7e4SJohannes Weiner 	bool reclaimable = false;
25299b4f98cdSJohannes Weiner 
25309b4f98cdSJohannes Weiner 	do {
25315660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25325660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2533ef8f2327SMel Gorman 			.pgdat = pgdat,
25349e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25355660048cSJohannes Weiner 		};
2536a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2537694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25385660048cSJohannes Weiner 
25399b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25409b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25419b4f98cdSJohannes Weiner 
2542694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2543694fbc0fSAndrew Morton 		do {
25446b4f7799SJohannes Weiner 			unsigned long lru_pages;
25458e8ae645SJohannes Weiner 			unsigned long reclaimed;
2546cb731d6cSVladimir Davydov 			unsigned long scanned;
25479b4f98cdSJohannes Weiner 
2548241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2549241994edSJohannes Weiner 				if (!sc->may_thrash)
2550241994edSJohannes Weiner 					continue;
2551241994edSJohannes Weiner 				mem_cgroup_events(memcg, MEMCG_LOW, 1);
2552241994edSJohannes Weiner 			}
2553241994edSJohannes Weiner 
25548e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2555cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
25565660048cSJohannes Weiner 
2557a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2558a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2559f9be23d6SKonstantin Khlebnikov 
2560b5afba29SVladimir Davydov 			if (memcg)
2561a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
2562cb731d6cSVladimir Davydov 					    memcg, sc->nr_scanned - scanned,
2563cb731d6cSVladimir Davydov 					    lru_pages);
2564cb731d6cSVladimir Davydov 
25658e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25668e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25678e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25688e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25698e8ae645SJohannes Weiner 
25705660048cSJohannes Weiner 			/*
2571a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2572a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2573a9dd0a83SMel Gorman 			 * node.
2574a394cb8eSMichal Hocko 			 *
2575a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2576a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2577a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2578a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25795660048cSJohannes Weiner 			 */
2580a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2581a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25825660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25835660048cSJohannes Weiner 				break;
25845660048cSJohannes Weiner 			}
2585241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
258670ddf637SAnton Vorontsov 
25876b4f7799SJohannes Weiner 		/*
25886b4f7799SJohannes Weiner 		 * Shrink the slab caches in the same proportion that
25896b4f7799SJohannes Weiner 		 * the eligible LRU pages were scanned.
25906b4f7799SJohannes Weiner 		 */
2591b2e18757SMel Gorman 		if (global_reclaim(sc))
2592a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25936b4f7799SJohannes Weiner 				    sc->nr_scanned - nr_scanned,
2594a9dd0a83SMel Gorman 				    node_lru_pages);
25956b4f7799SJohannes Weiner 
25966b4f7799SJohannes Weiner 		if (reclaim_state) {
2597cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25986b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25996b4f7799SJohannes Weiner 		}
26006b4f7799SJohannes Weiner 
26018e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
26028e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
260370ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
260470ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
260570ddf637SAnton Vorontsov 
26062344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
26072344d7e4SJohannes Weiner 			reclaimable = true;
26082344d7e4SJohannes Weiner 
2609a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
26109b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
26112344d7e4SJohannes Weiner 
26122344d7e4SJohannes Weiner 	return reclaimable;
2613f16015fbSJohannes Weiner }
2614f16015fbSJohannes Weiner 
261553853e2dSVlastimil Babka /*
2616fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2617fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2618fdd4c614SVlastimil Babka  * should reclaim first.
261953853e2dSVlastimil Babka  */
26204f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2621fe4b1b24SMel Gorman {
262231483b6aSMel Gorman 	unsigned long watermark;
2623fdd4c614SVlastimil Babka 	enum compact_result suitable;
2624fe4b1b24SMel Gorman 
2625fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2626fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2627fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2628fdd4c614SVlastimil Babka 		return true;
2629fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2630fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2631fe4b1b24SMel Gorman 		return false;
2632fe4b1b24SMel Gorman 
2633fdd4c614SVlastimil Babka 	/*
2634fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2635fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2636fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2637fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2638fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2639fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2640fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2641fdd4c614SVlastimil Babka 	 */
2642fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2643fdd4c614SVlastimil Babka 
2644fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2645fe4b1b24SMel Gorman }
2646fe4b1b24SMel Gorman 
26471da177e4SLinus Torvalds /*
26481da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
26491da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
26501da177e4SLinus Torvalds  * request.
26511da177e4SLinus Torvalds  *
26521da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
26531da177e4SLinus Torvalds  * scan then give up on it.
26541da177e4SLinus Torvalds  */
26550a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
26561da177e4SLinus Torvalds {
2657dd1a239fSMel Gorman 	struct zoneref *z;
265854a6eb5cSMel Gorman 	struct zone *zone;
26590608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26600608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2661619d0d76SWeijie Yang 	gfp_t orig_mask;
266279dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
26631cfb419bSKAMEZAWA Hiroyuki 
2664cc715d99SMel Gorman 	/*
2665cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2666cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2667cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2668cc715d99SMel Gorman 	 */
2669619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2670b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2671cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
26724f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2673b2e18757SMel Gorman 	}
2674cc715d99SMel Gorman 
2675d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2676b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2677b2e18757SMel Gorman 		/*
26781cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26791cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26801cfb419bSKAMEZAWA Hiroyuki 		 */
268189b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2682344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2683344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26841da177e4SLinus Torvalds 				continue;
268565ec02cbSVladimir Davydov 
26866e543d57SLisa Du 			if (sc->priority != DEF_PRIORITY &&
2687599d0c95SMel Gorman 			    !pgdat_reclaimable(zone->zone_pgdat))
26881da177e4SLinus Torvalds 				continue;	/* Let kswapd poll it */
26890b06496aSJohannes Weiner 
2690e0887c19SRik van Riel 			/*
2691e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2692e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2693e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2694e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2695e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2696c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2697c7cfa37bSCopot Alexandru 			 * page allocations.
2698e0887c19SRik van Riel 			 */
26990b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
27000b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
27014f588331SMel Gorman 			    compaction_ready(zone, sc)) {
27020b06496aSJohannes Weiner 				sc->compaction_ready = true;
2703e0887c19SRik van Riel 				continue;
2704e0887c19SRik van Riel 			}
27050b06496aSJohannes Weiner 
27060608f43dSAndrew Morton 			/*
270779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
270879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
270979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
271079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
271179dafcdcSMel Gorman 			 */
271279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
271379dafcdcSMel Gorman 				continue;
271479dafcdcSMel Gorman 
271579dafcdcSMel Gorman 			/*
27160608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27170608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27180608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27190608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27200608f43dSAndrew Morton 			 */
27210608f43dSAndrew Morton 			nr_soft_scanned = 0;
2722ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27230608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27240608f43dSAndrew Morton 						&nr_soft_scanned);
27250608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27260608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2727ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2728ac34a1a3SKAMEZAWA Hiroyuki 		}
2729d149e3b2SYing Han 
273079dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
273179dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
273279dafcdcSMel Gorman 			continue;
273379dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2734970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27351da177e4SLinus Torvalds 	}
2736e0c23279SMel Gorman 
273765ec02cbSVladimir Davydov 	/*
2738619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2739619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2740619d0d76SWeijie Yang 	 */
2741619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27421da177e4SLinus Torvalds }
27431da177e4SLinus Torvalds 
27441da177e4SLinus Torvalds /*
27451da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
27461da177e4SLinus Torvalds  *
27471da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
27481da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
27491da177e4SLinus Torvalds  *
27501da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
27511da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
27525b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
27535b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
27545b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
27555b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2756a41f24eaSNishanth Aravamudan  *
2757a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2758a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
27591da177e4SLinus Torvalds  */
2760dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
27613115cd91SVladimir Davydov 					  struct scan_control *sc)
27621da177e4SLinus Torvalds {
2763241994edSJohannes Weiner 	int initial_priority = sc->priority;
276469e05944SAndrew Morton 	unsigned long total_scanned = 0;
276522fba335SKOSAKI Motohiro 	unsigned long writeback_threshold;
2766241994edSJohannes Weiner retry:
2767873b4771SKeika Kobayashi 	delayacct_freepages_start();
2768873b4771SKeika Kobayashi 
276989b5fae5SJohannes Weiner 	if (global_reclaim(sc))
27707cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
27711da177e4SLinus Torvalds 
27729e3b2f8cSKonstantin Khlebnikov 	do {
277370ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
277470ddf637SAnton Vorontsov 				sc->priority);
277566e1707bSBalbir Singh 		sc->nr_scanned = 0;
27760a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2777e0c23279SMel Gorman 
277866e1707bSBalbir Singh 		total_scanned += sc->nr_scanned;
2779bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
27800b06496aSJohannes Weiner 			break;
27810b06496aSJohannes Weiner 
27820b06496aSJohannes Weiner 		if (sc->compaction_ready)
27830b06496aSJohannes Weiner 			break;
27841da177e4SLinus Torvalds 
27851da177e4SLinus Torvalds 		/*
27860e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27870e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27880e50ce3bSMinchan Kim 		 */
27890e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27900e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27910e50ce3bSMinchan Kim 
27920e50ce3bSMinchan Kim 		/*
27931da177e4SLinus Torvalds 		 * Try to write back as many pages as we just scanned.  This
27941da177e4SLinus Torvalds 		 * tends to cause slow streaming writers to write data to the
27951da177e4SLinus Torvalds 		 * disk smoothly, at the dirtying rate, which is nice.   But
27961da177e4SLinus Torvalds 		 * that's undesirable in laptop mode, where we *want* lumpy
27971da177e4SLinus Torvalds 		 * writeout.  So in laptop mode, write out the whole world.
27981da177e4SLinus Torvalds 		 */
279922fba335SKOSAKI Motohiro 		writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
280022fba335SKOSAKI Motohiro 		if (total_scanned > writeback_threshold) {
28010e175a18SCurt Wohlgemuth 			wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
28020e175a18SCurt Wohlgemuth 						WB_REASON_TRY_TO_FREE_PAGES);
280366e1707bSBalbir Singh 			sc->may_writepage = 1;
28041da177e4SLinus Torvalds 		}
28050b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2806bb21c7ceSKOSAKI Motohiro 
2807873b4771SKeika Kobayashi 	delayacct_freepages_end();
2808873b4771SKeika Kobayashi 
2809bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2810bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2811bb21c7ceSKOSAKI Motohiro 
28120cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
28130b06496aSJohannes Weiner 	if (sc->compaction_ready)
28147335084dSMel Gorman 		return 1;
28157335084dSMel Gorman 
2816241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2817241994edSJohannes Weiner 	if (!sc->may_thrash) {
2818241994edSJohannes Weiner 		sc->priority = initial_priority;
2819241994edSJohannes Weiner 		sc->may_thrash = 1;
2820241994edSJohannes Weiner 		goto retry;
2821241994edSJohannes Weiner 	}
2822241994edSJohannes Weiner 
2823bb21c7ceSKOSAKI Motohiro 	return 0;
28241da177e4SLinus Torvalds }
28251da177e4SLinus Torvalds 
28265515061dSMel Gorman static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
28275515061dSMel Gorman {
28285515061dSMel Gorman 	struct zone *zone;
28295515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
28305515061dSMel Gorman 	unsigned long free_pages = 0;
28315515061dSMel Gorman 	int i;
28325515061dSMel Gorman 	bool wmark_ok;
28335515061dSMel Gorman 
28345515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
28355515061dSMel Gorman 		zone = &pgdat->node_zones[i];
28366aa303deSMel Gorman 		if (!managed_zone(zone) ||
2837599d0c95SMel Gorman 		    pgdat_reclaimable_pages(pgdat) == 0)
2838675becceSMel Gorman 			continue;
2839675becceSMel Gorman 
28405515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
28415515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
28425515061dSMel Gorman 	}
28435515061dSMel Gorman 
2844675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2845675becceSMel Gorman 	if (!pfmemalloc_reserve)
2846675becceSMel Gorman 		return true;
2847675becceSMel Gorman 
28485515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
28495515061dSMel Gorman 
28505515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
28515515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
285238087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
28535515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
28545515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
28555515061dSMel Gorman 	}
28565515061dSMel Gorman 
28575515061dSMel Gorman 	return wmark_ok;
28585515061dSMel Gorman }
28595515061dSMel Gorman 
28605515061dSMel Gorman /*
28615515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
28625515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
28635515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
286450694c28SMel Gorman  * when the low watermark is reached.
286550694c28SMel Gorman  *
286650694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
286750694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
28685515061dSMel Gorman  */
286950694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
28705515061dSMel Gorman 					nodemask_t *nodemask)
28715515061dSMel Gorman {
2872675becceSMel Gorman 	struct zoneref *z;
28735515061dSMel Gorman 	struct zone *zone;
2874675becceSMel Gorman 	pg_data_t *pgdat = NULL;
28755515061dSMel Gorman 
28765515061dSMel Gorman 	/*
28775515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
28785515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
28795515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
28805515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
28815515061dSMel Gorman 	 * processes to block on log_wait_commit().
28825515061dSMel Gorman 	 */
28835515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
288450694c28SMel Gorman 		goto out;
288550694c28SMel Gorman 
288650694c28SMel Gorman 	/*
288750694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
288850694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
288950694c28SMel Gorman 	 */
289050694c28SMel Gorman 	if (fatal_signal_pending(current))
289150694c28SMel Gorman 		goto out;
28925515061dSMel Gorman 
2893675becceSMel Gorman 	/*
2894675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2895675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2896675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2897675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2898675becceSMel Gorman 	 *
2899675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2900675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2901675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2902675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2903675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2904675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2905675becceSMel Gorman 	 * should make reasonable progress.
2906675becceSMel Gorman 	 */
2907675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
290817636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2909675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2910675becceSMel Gorman 			continue;
2911675becceSMel Gorman 
2912675becceSMel Gorman 		/* Throttle based on the first usable node */
29135515061dSMel Gorman 		pgdat = zone->zone_pgdat;
29145515061dSMel Gorman 		if (pfmemalloc_watermark_ok(pgdat))
291550694c28SMel Gorman 			goto out;
2916675becceSMel Gorman 		break;
2917675becceSMel Gorman 	}
2918675becceSMel Gorman 
2919675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2920675becceSMel Gorman 	if (!pgdat)
2921675becceSMel Gorman 		goto out;
29225515061dSMel Gorman 
292368243e76SMel Gorman 	/* Account for the throttling */
292468243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
292568243e76SMel Gorman 
29265515061dSMel Gorman 	/*
29275515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
29285515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
29295515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
29305515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
29315515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
29325515061dSMel Gorman 	 * second before continuing.
29335515061dSMel Gorman 	 */
29345515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
29355515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
29365515061dSMel Gorman 			pfmemalloc_watermark_ok(pgdat), HZ);
293750694c28SMel Gorman 
293850694c28SMel Gorman 		goto check_pending;
29395515061dSMel Gorman 	}
29405515061dSMel Gorman 
29415515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
29425515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
29435515061dSMel Gorman 		pfmemalloc_watermark_ok(pgdat));
294450694c28SMel Gorman 
294550694c28SMel Gorman check_pending:
294650694c28SMel Gorman 	if (fatal_signal_pending(current))
294750694c28SMel Gorman 		return true;
294850694c28SMel Gorman 
294950694c28SMel Gorman out:
295050694c28SMel Gorman 	return false;
29515515061dSMel Gorman }
29525515061dSMel Gorman 
2953dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2954327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
295566e1707bSBalbir Singh {
295633906bc5SMel Gorman 	unsigned long nr_reclaimed;
295766e1707bSBalbir Singh 	struct scan_control sc = {
295822fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2959ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2960b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2961ee814fe2SJohannes Weiner 		.order = order,
2962ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2963ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2964ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2965a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29662e2e4259SKOSAKI Motohiro 		.may_swap = 1,
296766e1707bSBalbir Singh 	};
296866e1707bSBalbir Singh 
29695515061dSMel Gorman 	/*
297050694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
297150694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
297250694c28SMel Gorman 	 * point.
29735515061dSMel Gorman 	 */
297450694c28SMel Gorman 	if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
29755515061dSMel Gorman 		return 1;
29765515061dSMel Gorman 
297733906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
297833906bc5SMel Gorman 				sc.may_writepage,
2979e5146b12SMel Gorman 				gfp_mask,
2980e5146b12SMel Gorman 				sc.reclaim_idx);
298133906bc5SMel Gorman 
29823115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
298333906bc5SMel Gorman 
298433906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
298533906bc5SMel Gorman 
298633906bc5SMel Gorman 	return nr_reclaimed;
298766e1707bSBalbir Singh }
298866e1707bSBalbir Singh 
2989c255a458SAndrew Morton #ifdef CONFIG_MEMCG
299066e1707bSBalbir Singh 
2991a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
29924e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
2993ef8f2327SMel Gorman 						pg_data_t *pgdat,
29940ae5e89cSYing Han 						unsigned long *nr_scanned)
29954e416953SBalbir Singh {
29964e416953SBalbir Singh 	struct scan_control sc = {
2997b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2998ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
29994e416953SBalbir Singh 		.may_writepage = !laptop_mode,
30004e416953SBalbir Singh 		.may_unmap = 1,
3001b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
30024e416953SBalbir Singh 		.may_swap = !noswap,
30034e416953SBalbir Singh 	};
30046b4f7799SJohannes Weiner 	unsigned long lru_pages;
30050ae5e89cSYing Han 
30064e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
30074e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3008bdce6d9eSKOSAKI Motohiro 
30099e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3010bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3011e5146b12SMel Gorman 						      sc.gfp_mask,
3012e5146b12SMel Gorman 						      sc.reclaim_idx);
3013bdce6d9eSKOSAKI Motohiro 
30144e416953SBalbir Singh 	/*
30154e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
30164e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3017a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30184e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
30194e416953SBalbir Singh 	 * the priority and make it zero.
30204e416953SBalbir Singh 	 */
3021ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3022bdce6d9eSKOSAKI Motohiro 
3023bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3024bdce6d9eSKOSAKI Motohiro 
30250ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
30264e416953SBalbir Singh 	return sc.nr_reclaimed;
30274e416953SBalbir Singh }
30284e416953SBalbir Singh 
302972835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3030b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
30318c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3032b70a2a21SJohannes Weiner 					   bool may_swap)
303366e1707bSBalbir Singh {
30344e416953SBalbir Singh 	struct zonelist *zonelist;
3035bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3036889976dbSYing Han 	int nid;
303766e1707bSBalbir Singh 	struct scan_control sc = {
3038b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3039ee814fe2SJohannes Weiner 		.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3040ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3041b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3042ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3043ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
304466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3045a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3046b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3047a09ed5e0SYing Han 	};
304866e1707bSBalbir Singh 
3049889976dbSYing Han 	/*
3050889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3051889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3052889976dbSYing Han 	 * scan does not need to be the current node.
3053889976dbSYing Han 	 */
305472835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3055889976dbSYing Han 
3056c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3057bdce6d9eSKOSAKI Motohiro 
3058bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3059bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3060e5146b12SMel Gorman 					    sc.gfp_mask,
3061e5146b12SMel Gorman 					    sc.reclaim_idx);
3062bdce6d9eSKOSAKI Motohiro 
306389a28483SJohannes Weiner 	current->flags |= PF_MEMALLOC;
30643115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
306589a28483SJohannes Weiner 	current->flags &= ~PF_MEMALLOC;
3066bdce6d9eSKOSAKI Motohiro 
3067bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3068bdce6d9eSKOSAKI Motohiro 
3069bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
307066e1707bSBalbir Singh }
307166e1707bSBalbir Singh #endif
307266e1707bSBalbir Singh 
30731d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3074ef8f2327SMel Gorman 				struct scan_control *sc)
3075f16015fbSJohannes Weiner {
3076b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3077b95a2f2dSJohannes Weiner 
3078b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3079b95a2f2dSJohannes Weiner 		return;
3080b95a2f2dSJohannes Weiner 
3081b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3082b95a2f2dSJohannes Weiner 	do {
3083ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3084f16015fbSJohannes Weiner 
3085f8d1a311SMel Gorman 		if (inactive_list_is_low(lruvec, false, sc))
30861a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30879e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3088b95a2f2dSJohannes Weiner 
3089b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3090b95a2f2dSJohannes Weiner 	} while (memcg);
3091f16015fbSJohannes Weiner }
3092f16015fbSJohannes Weiner 
309331483b6aSMel Gorman static bool zone_balanced(struct zone *zone, int order, int classzone_idx)
309460cefed4SJohannes Weiner {
309531483b6aSMel Gorman 	unsigned long mark = high_wmark_pages(zone);
309660cefed4SJohannes Weiner 
30976256c6b4SMel Gorman 	if (!zone_watermark_ok_safe(zone, order, mark, classzone_idx))
30986256c6b4SMel Gorman 		return false;
30996256c6b4SMel Gorman 
31006256c6b4SMel Gorman 	/*
31016256c6b4SMel Gorman 	 * If any eligible zone is balanced then the node is not considered
31026256c6b4SMel Gorman 	 * to be congested or dirty
31036256c6b4SMel Gorman 	 */
31046256c6b4SMel Gorman 	clear_bit(PGDAT_CONGESTED, &zone->zone_pgdat->flags);
31056256c6b4SMel Gorman 	clear_bit(PGDAT_DIRTY, &zone->zone_pgdat->flags);
31066256c6b4SMel Gorman 
31076256c6b4SMel Gorman 	return true;
310860cefed4SJohannes Weiner }
310960cefed4SJohannes Weiner 
31101741c877SMel Gorman /*
31115515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
31125515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
31135515061dSMel Gorman  *
31145515061dSMel Gorman  * Returns true if kswapd is ready to sleep
31155515061dSMel Gorman  */
3116d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3117f50de2d3SMel Gorman {
31181d82de61SMel Gorman 	int i;
31191d82de61SMel Gorman 
31205515061dSMel Gorman 	/*
31219e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
31229e5e3661SVlastimil Babka 	 * soon as pfmemalloc_watermark_ok() is true. But there is a potential
31239e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
31249e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
31259e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
31269e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
31279e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
31289e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
31299e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
31309e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
31319e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
31325515061dSMel Gorman 	 */
31339e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
31349e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3135f50de2d3SMel Gorman 
31361d82de61SMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
31371d82de61SMel Gorman 		struct zone *zone = pgdat->node_zones + i;
31381d82de61SMel Gorman 
31396aa303deSMel Gorman 		if (!managed_zone(zone))
31401d82de61SMel Gorman 			continue;
31411d82de61SMel Gorman 
314238087d9bSMel Gorman 		if (!zone_balanced(zone, order, classzone_idx))
314338087d9bSMel Gorman 			return false;
31441d82de61SMel Gorman 	}
31451d82de61SMel Gorman 
314638087d9bSMel Gorman 	return true;
3147f50de2d3SMel Gorman }
3148f50de2d3SMel Gorman 
31491da177e4SLinus Torvalds /*
31501d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
31511d82de61SMel Gorman  * zone that is currently unbalanced.
3152b8e83b94SMel Gorman  *
3153b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3154283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3155283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
315675485363SMel Gorman  */
31571d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3158accf6242SVlastimil Babka 			       struct scan_control *sc)
315975485363SMel Gorman {
31601d82de61SMel Gorman 	struct zone *zone;
31611d82de61SMel Gorman 	int z;
316275485363SMel Gorman 
31631d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
31641d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3165970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
31661d82de61SMel Gorman 		zone = pgdat->node_zones + z;
31676aa303deSMel Gorman 		if (!managed_zone(zone))
31681d82de61SMel Gorman 			continue;
31697c954f6dSMel Gorman 
31701d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
31717c954f6dSMel Gorman 	}
31727c954f6dSMel Gorman 
31731d82de61SMel Gorman 	/*
31741d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
31751d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
31761d82de61SMel Gorman 	 */
3177970a39a3SMel Gorman 	shrink_node(pgdat, sc);
31781d82de61SMel Gorman 
31791d82de61SMel Gorman 	/*
31801d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
31811d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
31821d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
31831d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
31841d82de61SMel Gorman 	 * can direct reclaim/compact.
31851d82de61SMel Gorman 	 */
31869861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
31871d82de61SMel Gorman 		sc->order = 0;
31881d82de61SMel Gorman 
3189b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
319075485363SMel Gorman }
319175485363SMel Gorman 
319275485363SMel Gorman /*
31931d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
31941d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
31951d82de61SMel Gorman  * balanced.
31961da177e4SLinus Torvalds  *
31971d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
31981da177e4SLinus Torvalds  *
31991da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
320041858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
32011d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
32021d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
32031d82de61SMel Gorman  * balanced.
32041da177e4SLinus Torvalds  */
3205accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
32061da177e4SLinus Torvalds {
32071da177e4SLinus Torvalds 	int i;
32080608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
32090608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
32101d82de61SMel Gorman 	struct zone *zone;
3211179e9639SAndrew Morton 	struct scan_control sc = {
3212179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3213ee814fe2SJohannes Weiner 		.order = order,
3214b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3215ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3216a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32172e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3218179e9639SAndrew Morton 	};
3219f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
32201da177e4SLinus Torvalds 
32219e3b2f8cSKonstantin Khlebnikov 	do {
3222b8e83b94SMel Gorman 		bool raise_priority = true;
3223b8e83b94SMel Gorman 
3224b8e83b94SMel Gorman 		sc.nr_reclaimed = 0;
322584c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
32261da177e4SLinus Torvalds 
322786c79f6bSMel Gorman 		/*
322884c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
322984c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
323084c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
323184c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
323284c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
323384c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
323484c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
323584c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
323686c79f6bSMel Gorman 		 */
323786c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
323886c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
323986c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
32406aa303deSMel Gorman 				if (!managed_zone(zone))
324186c79f6bSMel Gorman 					continue;
324286c79f6bSMel Gorman 
3243970a39a3SMel Gorman 				sc.reclaim_idx = i;
324486c79f6bSMel Gorman 				break;
324586c79f6bSMel Gorman 			}
324686c79f6bSMel Gorman 		}
324786c79f6bSMel Gorman 
324886c79f6bSMel Gorman 		/*
324986c79f6bSMel Gorman 		 * Only reclaim if there are no eligible zones. Check from
325086c79f6bSMel Gorman 		 * high to low zone as allocations prefer higher zones.
325186c79f6bSMel Gorman 		 * Scanning from low to high zone would allow congestion to be
325286c79f6bSMel Gorman 		 * cleared during a very small window when a small low
325386c79f6bSMel Gorman 		 * zone was balanced even under extreme pressure when the
325484c7a777SMel Gorman 		 * overall node may be congested. Note that sc.reclaim_idx
325584c7a777SMel Gorman 		 * is not used as buffer_heads_over_limit may have adjusted
325684c7a777SMel Gorman 		 * it.
325786c79f6bSMel Gorman 		 */
325884c7a777SMel Gorman 		for (i = classzone_idx; i >= 0; i--) {
32591d82de61SMel Gorman 			zone = pgdat->node_zones + i;
32606aa303deSMel Gorman 			if (!managed_zone(zone))
32611da177e4SLinus Torvalds 				continue;
32621da177e4SLinus Torvalds 
326384c7a777SMel Gorman 			if (zone_balanced(zone, sc.order, classzone_idx))
32641da177e4SLinus Torvalds 				goto out;
326586c79f6bSMel Gorman 		}
3266e1dbeda6SAndrew Morton 
32671da177e4SLinus Torvalds 		/*
32681d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
32691d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
32701d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
32711d82de61SMel Gorman 		 * about consistent aging.
32721d82de61SMel Gorman 		 */
3273ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
32741d82de61SMel Gorman 
32751d82de61SMel Gorman 		/*
3276b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3277b7ea3c41SMel Gorman 		 * even in laptop mode.
3278b7ea3c41SMel Gorman 		 */
32791d82de61SMel Gorman 		if (sc.priority < DEF_PRIORITY - 2 || !pgdat_reclaimable(pgdat))
3280b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3281b7ea3c41SMel Gorman 
32821d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
32831da177e4SLinus Torvalds 		sc.nr_scanned = 0;
32840608f43dSAndrew Morton 		nr_soft_scanned = 0;
3285ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
32861d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
32870608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
32880608f43dSAndrew Morton 
328932a4330dSRik van Riel 		/*
32901d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
32911d82de61SMel Gorman 		 * enough pages are already being scanned that that high
32921d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
329332a4330dSRik van Riel 		 */
3294970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3295b8e83b94SMel Gorman 			raise_priority = false;
3296d7868daeSMel Gorman 
32975515061dSMel Gorman 		/*
32985515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
32995515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
33005515061dSMel Gorman 		 * able to safely make forward progress. Wake them
33015515061dSMel Gorman 		 */
33025515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
33035515061dSMel Gorman 				pfmemalloc_watermark_ok(pgdat))
3304cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
33055515061dSMel Gorman 
3306b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3307b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3308b8e83b94SMel Gorman 			break;
3309b8e83b94SMel Gorman 
3310b8e83b94SMel Gorman 		/*
3311b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3312b8e83b94SMel Gorman 		 * progress in reclaiming pages
3313b8e83b94SMel Gorman 		 */
3314b8e83b94SMel Gorman 		if (raise_priority || !sc.nr_reclaimed)
3315b8e83b94SMel Gorman 			sc.priority--;
33161d82de61SMel Gorman 	} while (sc.priority >= 1);
33171da177e4SLinus Torvalds 
3318b8e83b94SMel Gorman out:
33190abdee2bSMel Gorman 	/*
33201d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
33211d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
33221d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
33231d82de61SMel Gorman 	 * remain at the higher level.
33240abdee2bSMel Gorman 	 */
33251d82de61SMel Gorman 	return sc.order;
33261da177e4SLinus Torvalds }
33271da177e4SLinus Torvalds 
332838087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
332938087d9bSMel Gorman 				unsigned int classzone_idx)
3330f0bc0a60SKOSAKI Motohiro {
3331f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3332f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3333f0bc0a60SKOSAKI Motohiro 
3334f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3335f0bc0a60SKOSAKI Motohiro 		return;
3336f0bc0a60SKOSAKI Motohiro 
3337f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3338f0bc0a60SKOSAKI Motohiro 
3339f0bc0a60SKOSAKI Motohiro 	/* Try to sleep for a short interval */
3340d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3341fd901c95SVlastimil Babka 		/*
3342fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3343fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3344fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3345fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3346fd901c95SVlastimil Babka 		 */
3347fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3348fd901c95SVlastimil Babka 
3349fd901c95SVlastimil Babka 		/*
3350fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3351fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3352fd901c95SVlastimil Babka 		 */
335338087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3354fd901c95SVlastimil Babka 
3355f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
335638087d9bSMel Gorman 
335738087d9bSMel Gorman 		/*
335838087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
335938087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
336038087d9bSMel Gorman 		 * the previous request that slept prematurely.
336138087d9bSMel Gorman 		 */
336238087d9bSMel Gorman 		if (remaining) {
336338087d9bSMel Gorman 			pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
336438087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
336538087d9bSMel Gorman 		}
336638087d9bSMel Gorman 
3367f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3368f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3369f0bc0a60SKOSAKI Motohiro 	}
3370f0bc0a60SKOSAKI Motohiro 
3371f0bc0a60SKOSAKI Motohiro 	/*
3372f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3373f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3374f0bc0a60SKOSAKI Motohiro 	 */
3375d9f21d42SMel Gorman 	if (!remaining &&
3376d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3377f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3378f0bc0a60SKOSAKI Motohiro 
3379f0bc0a60SKOSAKI Motohiro 		/*
3380f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3381f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3382f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3383f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3384f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3385f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3386f0bc0a60SKOSAKI Motohiro 		 */
3387f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
33881c7e7f6cSAaditya Kumar 
33891c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3390f0bc0a60SKOSAKI Motohiro 			schedule();
33911c7e7f6cSAaditya Kumar 
3392f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3393f0bc0a60SKOSAKI Motohiro 	} else {
3394f0bc0a60SKOSAKI Motohiro 		if (remaining)
3395f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3396f0bc0a60SKOSAKI Motohiro 		else
3397f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3398f0bc0a60SKOSAKI Motohiro 	}
3399f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3400f0bc0a60SKOSAKI Motohiro }
3401f0bc0a60SKOSAKI Motohiro 
34021da177e4SLinus Torvalds /*
34031da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
34041da177e4SLinus Torvalds  * from the init process.
34051da177e4SLinus Torvalds  *
34061da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
34071da177e4SLinus Torvalds  * free memory available even if there is no other activity
34081da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
34091da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
34101da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
34111da177e4SLinus Torvalds  *
34121da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
34131da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
34141da177e4SLinus Torvalds  */
34151da177e4SLinus Torvalds static int kswapd(void *p)
34161da177e4SLinus Torvalds {
341738087d9bSMel Gorman 	unsigned int alloc_order, reclaim_order, classzone_idx;
34181da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
34191da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3420f0bc0a60SKOSAKI Motohiro 
34211da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
34221da177e4SLinus Torvalds 		.reclaimed_slab = 0,
34231da177e4SLinus Torvalds 	};
3424a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
34251da177e4SLinus Torvalds 
3426cf40bd16SNick Piggin 	lockdep_set_current_reclaim_state(GFP_KERNEL);
3427cf40bd16SNick Piggin 
3428174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3429c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
34301da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
34311da177e4SLinus Torvalds 
34321da177e4SLinus Torvalds 	/*
34331da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
34341da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
34351da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
34361da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
34371da177e4SLinus Torvalds 	 *
34381da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
34391da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
34401da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
34411da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34421da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34431da177e4SLinus Torvalds 	 */
3444930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
344583144186SRafael J. Wysocki 	set_freezable();
34461da177e4SLinus Torvalds 
344738087d9bSMel Gorman 	pgdat->kswapd_order = alloc_order = reclaim_order = 0;
344838087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = classzone_idx = 0;
34491da177e4SLinus Torvalds 	for ( ; ; ) {
34506f6313d4SJeff Liu 		bool ret;
34513e1d1d28SChristoph Lameter 
345238087d9bSMel Gorman kswapd_try_sleep:
345338087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
345438087d9bSMel Gorman 					classzone_idx);
3455215ddd66SMel Gorman 
345638087d9bSMel Gorman 		/* Read the new order and classzone_idx */
345738087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
345838087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
345938087d9bSMel Gorman 		pgdat->kswapd_order = 0;
346038087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = 0;
34611da177e4SLinus Torvalds 
34628fe23e05SDavid Rientjes 		ret = try_to_freeze();
34638fe23e05SDavid Rientjes 		if (kthread_should_stop())
34648fe23e05SDavid Rientjes 			break;
34658fe23e05SDavid Rientjes 
34668fe23e05SDavid Rientjes 		/*
34678fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
34688fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3469b1296cc4SRafael J. Wysocki 		 */
347038087d9bSMel Gorman 		if (ret)
347138087d9bSMel Gorman 			continue;
34721d82de61SMel Gorman 
347338087d9bSMel Gorman 		/*
347438087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
347538087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
347638087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
347738087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
347838087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
347938087d9bSMel Gorman 		 * request (alloc_order).
348038087d9bSMel Gorman 		 */
3481e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3482e5146b12SMel Gorman 						alloc_order);
348338087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
348438087d9bSMel Gorman 		if (reclaim_order < alloc_order)
348538087d9bSMel Gorman 			goto kswapd_try_sleep;
348638087d9bSMel Gorman 
348738087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
348838087d9bSMel Gorman 		classzone_idx = pgdat->kswapd_classzone_idx;
348933906bc5SMel Gorman 	}
3490b0a8cc58STakamori Yamaguchi 
349171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3492b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
349371abdc15SJohannes Weiner 	lockdep_clear_current_reclaim_state();
349471abdc15SJohannes Weiner 
34951da177e4SLinus Torvalds 	return 0;
34961da177e4SLinus Torvalds }
34971da177e4SLinus Torvalds 
34981da177e4SLinus Torvalds /*
34991da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
35001da177e4SLinus Torvalds  */
350199504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
35021da177e4SLinus Torvalds {
35031da177e4SLinus Torvalds 	pg_data_t *pgdat;
3504e1a55637SMel Gorman 	int z;
35051da177e4SLinus Torvalds 
35066aa303deSMel Gorman 	if (!managed_zone(zone))
35071da177e4SLinus Torvalds 		return;
35081da177e4SLinus Torvalds 
3509344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
35101da177e4SLinus Torvalds 		return;
351188f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
351238087d9bSMel Gorman 	pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx, classzone_idx);
351338087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
35148d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
35151da177e4SLinus Torvalds 		return;
3516e1a55637SMel Gorman 
3517e1a55637SMel Gorman 	/* Only wake kswapd if all zones are unbalanced */
3518e1a55637SMel Gorman 	for (z = 0; z <= classzone_idx; z++) {
3519e1a55637SMel Gorman 		zone = pgdat->node_zones + z;
35206aa303deSMel Gorman 		if (!managed_zone(zone))
3521e1a55637SMel Gorman 			continue;
3522e1a55637SMel Gorman 
3523e1a55637SMel Gorman 		if (zone_balanced(zone, order, classzone_idx))
352488f5acf8SMel Gorman 			return;
3525e1a55637SMel Gorman 	}
352688f5acf8SMel Gorman 
352788f5acf8SMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
35288d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
35291da177e4SLinus Torvalds }
35301da177e4SLinus Torvalds 
3531c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
35321da177e4SLinus Torvalds /*
35337b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3534d6277db4SRafael J. Wysocki  * freed pages.
3535d6277db4SRafael J. Wysocki  *
3536d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3537d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3538d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35391da177e4SLinus Torvalds  */
35407b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35411da177e4SLinus Torvalds {
3542d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3543d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35447b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3545ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3546b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
35479e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3548ee814fe2SJohannes Weiner 		.may_writepage = 1,
3549ee814fe2SJohannes Weiner 		.may_unmap = 1,
3550ee814fe2SJohannes Weiner 		.may_swap = 1,
3551ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
35521da177e4SLinus Torvalds 	};
35537b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
35547b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
35557b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
35561da177e4SLinus Torvalds 
35577b51755cSKOSAKI Motohiro 	p->flags |= PF_MEMALLOC;
35587b51755cSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(sc.gfp_mask);
3559d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
35607b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3561d6277db4SRafael J. Wysocki 
35623115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3563d6277db4SRafael J. Wysocki 
35647b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
35657b51755cSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
35667b51755cSKOSAKI Motohiro 	p->flags &= ~PF_MEMALLOC;
3567d6277db4SRafael J. Wysocki 
35687b51755cSKOSAKI Motohiro 	return nr_reclaimed;
35691da177e4SLinus Torvalds }
3570c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
35711da177e4SLinus Torvalds 
35721da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
35731da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
35741da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
35751da177e4SLinus Torvalds    restore their cpu bindings. */
3576517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
35771da177e4SLinus Torvalds {
357858c0a4a7SYasunori Goto 	int nid;
35791da177e4SLinus Torvalds 
358048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3581c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3582a70f7302SRusty Russell 		const struct cpumask *mask;
3583a70f7302SRusty Russell 
3584a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3585c5f59f08SMike Travis 
35863e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
35871da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3588c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
35891da177e4SLinus Torvalds 	}
3590517bbed9SSebastian Andrzej Siewior 	return 0;
35911da177e4SLinus Torvalds }
35921da177e4SLinus Torvalds 
35933218ae14SYasunori Goto /*
35943218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
35953218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
35963218ae14SYasunori Goto  */
35973218ae14SYasunori Goto int kswapd_run(int nid)
35983218ae14SYasunori Goto {
35993218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
36003218ae14SYasunori Goto 	int ret = 0;
36013218ae14SYasunori Goto 
36023218ae14SYasunori Goto 	if (pgdat->kswapd)
36033218ae14SYasunori Goto 		return 0;
36043218ae14SYasunori Goto 
36053218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
36063218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
36073218ae14SYasunori Goto 		/* failure at boot is fatal */
36083218ae14SYasunori Goto 		BUG_ON(system_state == SYSTEM_BOOTING);
3609d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3610d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3611d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
36123218ae14SYasunori Goto 	}
36133218ae14SYasunori Goto 	return ret;
36143218ae14SYasunori Goto }
36153218ae14SYasunori Goto 
36168fe23e05SDavid Rientjes /*
3617d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3618bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
36198fe23e05SDavid Rientjes  */
36208fe23e05SDavid Rientjes void kswapd_stop(int nid)
36218fe23e05SDavid Rientjes {
36228fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
36238fe23e05SDavid Rientjes 
3624d8adde17SJiang Liu 	if (kswapd) {
36258fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3626d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3627d8adde17SJiang Liu 	}
36288fe23e05SDavid Rientjes }
36298fe23e05SDavid Rientjes 
36301da177e4SLinus Torvalds static int __init kswapd_init(void)
36311da177e4SLinus Torvalds {
3632517bbed9SSebastian Andrzej Siewior 	int nid, ret;
363369e05944SAndrew Morton 
36341da177e4SLinus Torvalds 	swap_setup();
363548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
36363218ae14SYasunori Goto  		kswapd_run(nid);
3637517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3638517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3639517bbed9SSebastian Andrzej Siewior 					NULL);
3640517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
36411da177e4SLinus Torvalds 	return 0;
36421da177e4SLinus Torvalds }
36431da177e4SLinus Torvalds 
36441da177e4SLinus Torvalds module_init(kswapd_init)
36459eeff239SChristoph Lameter 
36469eeff239SChristoph Lameter #ifdef CONFIG_NUMA
36479eeff239SChristoph Lameter /*
3648a5f5f91dSMel Gorman  * Node reclaim mode
36499eeff239SChristoph Lameter  *
3650a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
36519eeff239SChristoph Lameter  * the watermarks.
36529eeff239SChristoph Lameter  */
3653a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
36549eeff239SChristoph Lameter 
36551b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
36567d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
36571b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
365895bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
36591b2ffb78SChristoph Lameter 
36609eeff239SChristoph Lameter /*
3661a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3662a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3663a92f7126SChristoph Lameter  * a zone.
3664a92f7126SChristoph Lameter  */
3665a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3666a92f7126SChristoph Lameter 
36679eeff239SChristoph Lameter /*
3668a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
36699614634fSChristoph Lameter  * occur.
36709614634fSChristoph Lameter  */
36719614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
36729614634fSChristoph Lameter 
36739614634fSChristoph Lameter /*
36740ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
36750ff38490SChristoph Lameter  * slab reclaim needs to occur.
36760ff38490SChristoph Lameter  */
36770ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
36780ff38490SChristoph Lameter 
367911fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
368090afa5deSMel Gorman {
368111fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
368211fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
368311fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
368490afa5deSMel Gorman 
368590afa5deSMel Gorman 	/*
368690afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
368790afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
368890afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
368990afa5deSMel Gorman 	 */
369090afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
369190afa5deSMel Gorman }
369290afa5deSMel Gorman 
369390afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3694a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
369590afa5deSMel Gorman {
3696d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3697d031a157SAlexandru Moise 	unsigned long delta = 0;
369890afa5deSMel Gorman 
369990afa5deSMel Gorman 	/*
370095bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
370190afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
370211fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
370390afa5deSMel Gorman 	 * a better estimate
370490afa5deSMel Gorman 	 */
3705a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3706a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
370790afa5deSMel Gorman 	else
3708a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
370990afa5deSMel Gorman 
371090afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3711a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3712a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
371390afa5deSMel Gorman 
371490afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
371590afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
371690afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
371790afa5deSMel Gorman 
371890afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
371990afa5deSMel Gorman }
372090afa5deSMel Gorman 
37210ff38490SChristoph Lameter /*
3722a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
37239eeff239SChristoph Lameter  */
3724a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
37259eeff239SChristoph Lameter {
37267fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
372769e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
37289eeff239SChristoph Lameter 	struct task_struct *p = current;
37299eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3730a5f5f91dSMel Gorman 	int classzone_idx = gfp_zone(gfp_mask);
3731179e9639SAndrew Morton 	struct scan_control sc = {
373262b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
373321caf2fcSMing Lei 		.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3734bd2f6199SJohannes Weiner 		.order = order,
3735a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3736a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3737a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3738ee814fe2SJohannes Weiner 		.may_swap = 1,
3739a5f5f91dSMel Gorman 		.reclaim_idx = classzone_idx,
3740179e9639SAndrew Morton 	};
37419eeff239SChristoph Lameter 
37429eeff239SChristoph Lameter 	cond_resched();
3743d4f7796eSChristoph Lameter 	/*
374495bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3745d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
374695bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3747d4f7796eSChristoph Lameter 	 */
3748d4f7796eSChristoph Lameter 	p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
374976ca542dSKOSAKI Motohiro 	lockdep_set_current_reclaim_state(gfp_mask);
37509eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
37519eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3752c84db23cSChristoph Lameter 
3753a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3754a92f7126SChristoph Lameter 		/*
37550ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
37560ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3757a92f7126SChristoph Lameter 		 */
3758a92f7126SChristoph Lameter 		do {
3759970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
37609e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
37610ff38490SChristoph Lameter 	}
3762a92f7126SChristoph Lameter 
37639eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3764d4f7796eSChristoph Lameter 	current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
376576ca542dSKOSAKI Motohiro 	lockdep_clear_current_reclaim_state();
3766a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
37679eeff239SChristoph Lameter }
3768179e9639SAndrew Morton 
3769a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3770179e9639SAndrew Morton {
3771d773ed6bSDavid Rientjes 	int ret;
3772179e9639SAndrew Morton 
3773179e9639SAndrew Morton 	/*
3774a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
37750ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
377634aa1330SChristoph Lameter 	 *
37779614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
37789614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3779a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3780a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
37819614634fSChristoph Lameter 	 * unmapped file backed pages.
3782179e9639SAndrew Morton 	 */
3783a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3784a5f5f91dSMel Gorman 	    sum_zone_node_page_state(pgdat->node_id, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3785a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3786179e9639SAndrew Morton 
3787a5f5f91dSMel Gorman 	if (!pgdat_reclaimable(pgdat))
3788a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3789d773ed6bSDavid Rientjes 
3790179e9639SAndrew Morton 	/*
3791d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3792179e9639SAndrew Morton 	 */
3793d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3794a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3795179e9639SAndrew Morton 
3796179e9639SAndrew Morton 	/*
3797a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3798179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3799179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3800179e9639SAndrew Morton 	 * as wide as possible.
3801179e9639SAndrew Morton 	 */
3802a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3803a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3804d773ed6bSDavid Rientjes 
3805a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3806a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3807fa5e084eSMel Gorman 
3808a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3809a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3810d773ed6bSDavid Rientjes 
381124cf7251SMel Gorman 	if (!ret)
381224cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
381324cf7251SMel Gorman 
3814d773ed6bSDavid Rientjes 	return ret;
3815179e9639SAndrew Morton }
38169eeff239SChristoph Lameter #endif
3817894bc310SLee Schermerhorn 
3818894bc310SLee Schermerhorn /*
3819894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3820894bc310SLee Schermerhorn  * @page: the page to test
3821894bc310SLee Schermerhorn  *
3822894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
382339b5f29aSHugh Dickins  * lists vs unevictable list.
3824894bc310SLee Schermerhorn  *
3825894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3826ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3827b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3828ba9ddf49SLee Schermerhorn  *
3829894bc310SLee Schermerhorn  */
383039b5f29aSHugh Dickins int page_evictable(struct page *page)
3831894bc310SLee Schermerhorn {
383239b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3833894bc310SLee Schermerhorn }
383489e004eaSLee Schermerhorn 
383585046579SHugh Dickins #ifdef CONFIG_SHMEM
383689e004eaSLee Schermerhorn /**
383724513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
383824513264SHugh Dickins  * @pages:	array of pages to check
383924513264SHugh Dickins  * @nr_pages:	number of pages to check
384089e004eaSLee Schermerhorn  *
384124513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
384285046579SHugh Dickins  *
384385046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
384489e004eaSLee Schermerhorn  */
384524513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
384689e004eaSLee Schermerhorn {
3847925b7673SJohannes Weiner 	struct lruvec *lruvec;
3848785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
384924513264SHugh Dickins 	int pgscanned = 0;
385024513264SHugh Dickins 	int pgrescued = 0;
385189e004eaSLee Schermerhorn 	int i;
385289e004eaSLee Schermerhorn 
385324513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
385424513264SHugh Dickins 		struct page *page = pages[i];
3855785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
385689e004eaSLee Schermerhorn 
385724513264SHugh Dickins 		pgscanned++;
3858785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3859785b99feSMel Gorman 			if (pgdat)
3860785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3861785b99feSMel Gorman 			pgdat = pagepgdat;
3862785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
386389e004eaSLee Schermerhorn 		}
3864785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
386589e004eaSLee Schermerhorn 
386624513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
386724513264SHugh Dickins 			continue;
386889e004eaSLee Schermerhorn 
386939b5f29aSHugh Dickins 		if (page_evictable(page)) {
387024513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
387124513264SHugh Dickins 
3872309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
387324513264SHugh Dickins 			ClearPageUnevictable(page);
3874fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3875fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
387624513264SHugh Dickins 			pgrescued++;
387789e004eaSLee Schermerhorn 		}
387889e004eaSLee Schermerhorn 	}
387924513264SHugh Dickins 
3880785b99feSMel Gorman 	if (pgdat) {
388124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
388224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3883785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
388424513264SHugh Dickins 	}
388585046579SHugh Dickins }
388685046579SHugh Dickins #endif /* CONFIG_SHMEM */
3887