xref: /openbmc/linux/mm/vmscan.c (revision 894befec4d70b1c14097e4f009c90114b5a044ba)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/vmscan.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
81da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
91da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
101da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
111da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
121da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16b1de0d13SMitchel Humpherys 
171da177e4SLinus Torvalds #include <linux/mm.h>
185b3cc15aSIngo Molnar #include <linux/sched/mm.h>
191da177e4SLinus Torvalds #include <linux/module.h>
205a0e3ad6STejun Heo #include <linux/gfp.h>
211da177e4SLinus Torvalds #include <linux/kernel_stat.h>
221da177e4SLinus Torvalds #include <linux/swap.h>
231da177e4SLinus Torvalds #include <linux/pagemap.h>
241da177e4SLinus Torvalds #include <linux/init.h>
251da177e4SLinus Torvalds #include <linux/highmem.h>
2670ddf637SAnton Vorontsov #include <linux/vmpressure.h>
27e129b5c2SAndrew Morton #include <linux/vmstat.h>
281da177e4SLinus Torvalds #include <linux/file.h>
291da177e4SLinus Torvalds #include <linux/writeback.h>
301da177e4SLinus Torvalds #include <linux/blkdev.h>
311da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
321da177e4SLinus Torvalds 					buffer_heads_over_limit */
331da177e4SLinus Torvalds #include <linux/mm_inline.h>
341da177e4SLinus Torvalds #include <linux/backing-dev.h>
351da177e4SLinus Torvalds #include <linux/rmap.h>
361da177e4SLinus Torvalds #include <linux/topology.h>
371da177e4SLinus Torvalds #include <linux/cpu.h>
381da177e4SLinus Torvalds #include <linux/cpuset.h>
393e7d3449SMel Gorman #include <linux/compaction.h>
401da177e4SLinus Torvalds #include <linux/notifier.h>
411da177e4SLinus Torvalds #include <linux/rwsem.h>
42248a0301SRafael J. Wysocki #include <linux/delay.h>
433218ae14SYasunori Goto #include <linux/kthread.h>
447dfb7103SNigel Cunningham #include <linux/freezer.h>
4566e1707bSBalbir Singh #include <linux/memcontrol.h>
46873b4771SKeika Kobayashi #include <linux/delayacct.h>
47af936a16SLee Schermerhorn #include <linux/sysctl.h>
48929bea7cSKOSAKI Motohiro #include <linux/oom.h>
49268bb0ceSLinus Torvalds #include <linux/prefetch.h>
50b1de0d13SMitchel Humpherys #include <linux/printk.h>
51f9fe48beSRoss Zwisler #include <linux/dax.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
581da177e4SLinus Torvalds 
590f8053a5SNick Piggin #include "internal.h"
600f8053a5SNick Piggin 
6133906bc5SMel Gorman #define CREATE_TRACE_POINTS
6233906bc5SMel Gorman #include <trace/events/vmscan.h>
6333906bc5SMel Gorman 
641da177e4SLinus Torvalds struct scan_control {
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
681da177e4SLinus Torvalds 	/* This context's GFP mask */
696daa0e28SAl Viro 	gfp_t gfp_mask;
701da177e4SLinus Torvalds 
71ee814fe2SJohannes Weiner 	/* Allocation order */
725ad333ebSAndy Whitcroft 	int order;
7366e1707bSBalbir Singh 
74ee814fe2SJohannes Weiner 	/*
75ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
76ee814fe2SJohannes Weiner 	 * are scanned.
77ee814fe2SJohannes Weiner 	 */
78ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
799e3b2f8cSKonstantin Khlebnikov 
805f53e762SKOSAKI Motohiro 	/*
81f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
82f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
83f16015fbSJohannes Weiner 	 */
84f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8566e1707bSBalbir Singh 
86ee814fe2SJohannes Weiner 	/* Scan (total_size >> priority) pages at once */
87ee814fe2SJohannes Weiner 	int priority;
88ee814fe2SJohannes Weiner 
89b2e18757SMel Gorman 	/* The highest zone to isolate pages for reclaim from */
90b2e18757SMel Gorman 	enum zone_type reclaim_idx;
91b2e18757SMel Gorman 
921276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
93ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
94ee814fe2SJohannes Weiner 
95ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
96ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
97ee814fe2SJohannes Weiner 
98ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
99ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
100ee814fe2SJohannes Weiner 
101d6622f63SYisheng Xie 	/*
102d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
103d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
104d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
105d6622f63SYisheng Xie 	 */
106d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
107d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
108241994edSJohannes Weiner 
109ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
110ee814fe2SJohannes Weiner 
111ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
112ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
113ee814fe2SJohannes Weiner 
114ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
115ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
116ee814fe2SJohannes Weiner 
117ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
118ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
1191da177e4SLinus Torvalds };
1201da177e4SLinus Torvalds 
1211da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1221da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1231da177e4SLinus Torvalds 	do {								\
1241da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1251da177e4SLinus Torvalds 			struct page *prev;				\
1261da177e4SLinus Torvalds 									\
1271da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1281da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1291da177e4SLinus Torvalds 		}							\
1301da177e4SLinus Torvalds 	} while (0)
1311da177e4SLinus Torvalds #else
1321da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1331da177e4SLinus Torvalds #endif
1341da177e4SLinus Torvalds 
1351da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1361da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1371da177e4SLinus Torvalds 	do {								\
1381da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1391da177e4SLinus Torvalds 			struct page *prev;				\
1401da177e4SLinus Torvalds 									\
1411da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1421da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1431da177e4SLinus Torvalds 		}							\
1441da177e4SLinus Torvalds 	} while (0)
1451da177e4SLinus Torvalds #else
1461da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1471da177e4SLinus Torvalds #endif
1481da177e4SLinus Torvalds 
1491da177e4SLinus Torvalds /*
1501da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1511da177e4SLinus Torvalds  */
1521da177e4SLinus Torvalds int vm_swappiness = 60;
153d0480be4SWang Sheng-Hui /*
154d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
155d0480be4SWang Sheng-Hui  * zones.
156d0480be4SWang Sheng-Hui  */
157d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1601da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1611da177e4SLinus Torvalds 
162c255a458SAndrew Morton #ifdef CONFIG_MEMCG
16389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
16489b5fae5SJohannes Weiner {
165f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
16689b5fae5SJohannes Weiner }
16797c9341fSTejun Heo 
16897c9341fSTejun Heo /**
16997c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
17097c9341fSTejun Heo  * @sc: scan_control in question
17197c9341fSTejun Heo  *
17297c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
17397c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
17497c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
17597c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
17697c9341fSTejun Heo  * allocation and configurability.
17797c9341fSTejun Heo  *
17897c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
17997c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
18097c9341fSTejun Heo  */
18197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
18297c9341fSTejun Heo {
18397c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
18497c9341fSTejun Heo 
18597c9341fSTejun Heo 	if (!memcg)
18697c9341fSTejun Heo 		return true;
18797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
18869234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
18997c9341fSTejun Heo 		return true;
19097c9341fSTejun Heo #endif
19197c9341fSTejun Heo 	return false;
19297c9341fSTejun Heo }
19391a45470SKAMEZAWA Hiroyuki #else
19489b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
19589b5fae5SJohannes Weiner {
19689b5fae5SJohannes Weiner 	return true;
19789b5fae5SJohannes Weiner }
19897c9341fSTejun Heo 
19997c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
20097c9341fSTejun Heo {
20197c9341fSTejun Heo 	return true;
20297c9341fSTejun Heo }
20391a45470SKAMEZAWA Hiroyuki #endif
20491a45470SKAMEZAWA Hiroyuki 
2055a1c84b4SMel Gorman /*
2065a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2075a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2085a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2095a1c84b4SMel Gorman  */
2105a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2115a1c84b4SMel Gorman {
2125a1c84b4SMel Gorman 	unsigned long nr;
2135a1c84b4SMel Gorman 
2145a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2155a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2165a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2175a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2185a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2195a1c84b4SMel Gorman 
2205a1c84b4SMel Gorman 	return nr;
2215a1c84b4SMel Gorman }
2225a1c84b4SMel Gorman 
223fd538803SMichal Hocko /**
224fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
225fd538803SMichal Hocko  * @lruvec: lru vector
226fd538803SMichal Hocko  * @lru: lru to use
227fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
228fd538803SMichal Hocko  */
229fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
230c9f299d9SKOSAKI Motohiro {
231fd538803SMichal Hocko 	unsigned long lru_size;
232fd538803SMichal Hocko 	int zid;
233a3d8e054SKOSAKI Motohiro 
234fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
235fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
236fd538803SMichal Hocko 	else
237fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
238fd538803SMichal Hocko 
239fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
240fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
241fd538803SMichal Hocko 		unsigned long size;
242fd538803SMichal Hocko 
243fd538803SMichal Hocko 		if (!managed_zone(zone))
244fd538803SMichal Hocko 			continue;
245fd538803SMichal Hocko 
246fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
247fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
248fd538803SMichal Hocko 		else
249fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
250fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
251fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
252c9f299d9SKOSAKI Motohiro 	}
253c9f299d9SKOSAKI Motohiro 
254fd538803SMichal Hocko 	return lru_size;
255b4536f0cSMichal Hocko 
256b4536f0cSMichal Hocko }
257b4536f0cSMichal Hocko 
2581da177e4SLinus Torvalds /*
2591d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
2601da177e4SLinus Torvalds  */
2611d3d4437SGlauber Costa int register_shrinker(struct shrinker *shrinker)
2621da177e4SLinus Torvalds {
2631d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
2641d3d4437SGlauber Costa 
2651d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
2661d3d4437SGlauber Costa 		size *= nr_node_ids;
2671d3d4437SGlauber Costa 
2681d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
2691d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
2701d3d4437SGlauber Costa 		return -ENOMEM;
2711d3d4437SGlauber Costa 
2721da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2731da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
2741da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
2751d3d4437SGlauber Costa 	return 0;
2761da177e4SLinus Torvalds }
2778e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
2781da177e4SLinus Torvalds 
2791da177e4SLinus Torvalds /*
2801da177e4SLinus Torvalds  * Remove one
2811da177e4SLinus Torvalds  */
2828e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
2831da177e4SLinus Torvalds {
284bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
285bb422a73STetsuo Handa 		return;
2861da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
2871da177e4SLinus Torvalds 	list_del(&shrinker->list);
2881da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
289ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
290bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
2911da177e4SLinus Torvalds }
2928e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
2931da177e4SLinus Torvalds 
2941da177e4SLinus Torvalds #define SHRINK_BATCH 128
2951d3d4437SGlauber Costa 
296cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
2979092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
2981da177e4SLinus Torvalds {
29924f7c6b9SDave Chinner 	unsigned long freed = 0;
3001da177e4SLinus Torvalds 	unsigned long long delta;
301635697c6SKonstantin Khlebnikov 	long total_scan;
302d5bc5fd3SVladimir Davydov 	long freeable;
303acf92b48SDave Chinner 	long nr;
304acf92b48SDave Chinner 	long new_nr;
3051d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
306e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
307e9299f50SDave Chinner 					  : SHRINK_BATCH;
3085f33a080SShaohua Li 	long scanned = 0, next_deferred;
3091da177e4SLinus Torvalds 
310d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
311d5bc5fd3SVladimir Davydov 	if (freeable == 0)
3121d3d4437SGlauber Costa 		return 0;
313635697c6SKonstantin Khlebnikov 
314acf92b48SDave Chinner 	/*
315acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
316acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
317acf92b48SDave Chinner 	 * don't also do this scanning work.
318acf92b48SDave Chinner 	 */
3191d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
320acf92b48SDave Chinner 
321acf92b48SDave Chinner 	total_scan = nr;
3229092c71bSJosef Bacik 	delta = freeable >> priority;
3239092c71bSJosef Bacik 	delta *= 4;
3249092c71bSJosef Bacik 	do_div(delta, shrinker->seeks);
325acf92b48SDave Chinner 	total_scan += delta;
326acf92b48SDave Chinner 	if (total_scan < 0) {
3278612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
328a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
329d5bc5fd3SVladimir Davydov 		total_scan = freeable;
3305f33a080SShaohua Li 		next_deferred = nr;
3315f33a080SShaohua Li 	} else
3325f33a080SShaohua Li 		next_deferred = total_scan;
333ea164d73SAndrea Arcangeli 
334ea164d73SAndrea Arcangeli 	/*
3353567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
3363567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
3373567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
3383567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
3393567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
340d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
3413567b59aSDave Chinner 	 * memory.
3423567b59aSDave Chinner 	 *
3433567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
3443567b59aSDave Chinner 	 * a large delta change is calculated directly.
3453567b59aSDave Chinner 	 */
346d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
347d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
3483567b59aSDave Chinner 
3493567b59aSDave Chinner 	/*
350ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
351ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
352ea164d73SAndrea Arcangeli 	 * freeable entries.
353ea164d73SAndrea Arcangeli 	 */
354d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
355d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
3561da177e4SLinus Torvalds 
35724f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
3589092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
35909576073SDave Chinner 
3600b1fb40aSVladimir Davydov 	/*
3610b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
3620b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
3630b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
3640b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
3650b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
3660b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
3670b1fb40aSVladimir Davydov 	 * batch_size.
3680b1fb40aSVladimir Davydov 	 *
3690b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
3700b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
371d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
3720b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
3730b1fb40aSVladimir Davydov 	 * possible.
3740b1fb40aSVladimir Davydov 	 */
3750b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
376d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
37724f7c6b9SDave Chinner 		unsigned long ret;
3780b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
3791da177e4SLinus Torvalds 
3800b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
381d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
38224f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
38324f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
3841da177e4SLinus Torvalds 			break;
38524f7c6b9SDave Chinner 		freed += ret;
38624f7c6b9SDave Chinner 
387d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
388d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
389d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
3901da177e4SLinus Torvalds 
3911da177e4SLinus Torvalds 		cond_resched();
3921da177e4SLinus Torvalds 	}
3931da177e4SLinus Torvalds 
3945f33a080SShaohua Li 	if (next_deferred >= scanned)
3955f33a080SShaohua Li 		next_deferred -= scanned;
3965f33a080SShaohua Li 	else
3975f33a080SShaohua Li 		next_deferred = 0;
398acf92b48SDave Chinner 	/*
399acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
400acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
401acf92b48SDave Chinner 	 * scan, there is no need to do an update.
402acf92b48SDave Chinner 	 */
4035f33a080SShaohua Li 	if (next_deferred > 0)
4045f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
4051d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
40683aeeadaSKonstantin Khlebnikov 	else
4071d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
408acf92b48SDave Chinner 
409df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
4101d3d4437SGlauber Costa 	return freed;
4111d3d4437SGlauber Costa }
4121d3d4437SGlauber Costa 
4136b4f7799SJohannes Weiner /**
414cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
4156b4f7799SJohannes Weiner  * @gfp_mask: allocation context
4166b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
417cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
4189092c71bSJosef Bacik  * @priority: the reclaim priority
4191d3d4437SGlauber Costa  *
4206b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4211d3d4437SGlauber Costa  *
4226b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4236b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4241d3d4437SGlauber Costa  *
425cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
426cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4270fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4280fc9f58aSVladimir Davydov  * shrinkers are called.
429cb731d6cSVladimir Davydov  *
4309092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
4319092c71bSJosef Bacik  * in order to get the scan target.
4321d3d4437SGlauber Costa  *
4336b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4341d3d4437SGlauber Costa  */
435cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
436cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
4379092c71bSJosef Bacik 				 int priority)
4381d3d4437SGlauber Costa {
4391d3d4437SGlauber Costa 	struct shrinker *shrinker;
4401d3d4437SGlauber Costa 	unsigned long freed = 0;
4411d3d4437SGlauber Costa 
4420fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
443cb731d6cSVladimir Davydov 		return 0;
444cb731d6cSVladimir Davydov 
445e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
4461d3d4437SGlauber Costa 		goto out;
4471d3d4437SGlauber Costa 
4481d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4496b4f7799SJohannes Weiner 		struct shrink_control sc = {
4506b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4516b4f7799SJohannes Weiner 			.nid = nid,
452cb731d6cSVladimir Davydov 			.memcg = memcg,
4536b4f7799SJohannes Weiner 		};
4546b4f7799SJohannes Weiner 
4550fc9f58aSVladimir Davydov 		/*
4560fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4570fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4580fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4590fc9f58aSVladimir Davydov 		 */
4600fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4610fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
462cb731d6cSVladimir Davydov 			continue;
463cb731d6cSVladimir Davydov 
4646b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4656b4f7799SJohannes Weiner 			sc.nid = 0;
4666b4f7799SJohannes Weiner 
4679092c71bSJosef Bacik 		freed += do_shrink_slab(&sc, shrinker, priority);
468e496612cSMinchan Kim 		/*
469e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
470e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
471e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
472e496612cSMinchan Kim 		 */
473e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
474e496612cSMinchan Kim 			freed = freed ? : 1;
475e496612cSMinchan Kim 			break;
476e496612cSMinchan Kim 		}
477ec97097bSVladimir Davydov 	}
4781d3d4437SGlauber Costa 
4791da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
480f06590bdSMinchan Kim out:
481f06590bdSMinchan Kim 	cond_resched();
48224f7c6b9SDave Chinner 	return freed;
4831da177e4SLinus Torvalds }
4841da177e4SLinus Torvalds 
485cb731d6cSVladimir Davydov void drop_slab_node(int nid)
486cb731d6cSVladimir Davydov {
487cb731d6cSVladimir Davydov 	unsigned long freed;
488cb731d6cSVladimir Davydov 
489cb731d6cSVladimir Davydov 	do {
490cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
491cb731d6cSVladimir Davydov 
492cb731d6cSVladimir Davydov 		freed = 0;
493cb731d6cSVladimir Davydov 		do {
4949092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
495cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
496cb731d6cSVladimir Davydov 	} while (freed > 10);
497cb731d6cSVladimir Davydov }
498cb731d6cSVladimir Davydov 
499cb731d6cSVladimir Davydov void drop_slab(void)
500cb731d6cSVladimir Davydov {
501cb731d6cSVladimir Davydov 	int nid;
502cb731d6cSVladimir Davydov 
503cb731d6cSVladimir Davydov 	for_each_online_node(nid)
504cb731d6cSVladimir Davydov 		drop_slab_node(nid);
505cb731d6cSVladimir Davydov }
506cb731d6cSVladimir Davydov 
5071da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5081da177e4SLinus Torvalds {
509ceddc3a5SJohannes Weiner 	/*
510ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
511ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
512ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
513ceddc3a5SJohannes Weiner 	 */
514bd4c82c2SHuang Ying 	int radix_pins = PageTransHuge(page) && PageSwapCache(page) ?
515bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
516bd4c82c2SHuang Ying 	return page_count(page) - page_has_private(page) == 1 + radix_pins;
5171da177e4SLinus Torvalds }
5181da177e4SLinus Torvalds 
519703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5201da177e4SLinus Torvalds {
521930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5221da177e4SLinus Torvalds 		return 1;
523703c2708STejun Heo 	if (!inode_write_congested(inode))
5241da177e4SLinus Torvalds 		return 1;
525703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5261da177e4SLinus Torvalds 		return 1;
5271da177e4SLinus Torvalds 	return 0;
5281da177e4SLinus Torvalds }
5291da177e4SLinus Torvalds 
5301da177e4SLinus Torvalds /*
5311da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5321da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5331da177e4SLinus Torvalds  * fsync(), msync() or close().
5341da177e4SLinus Torvalds  *
5351da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5361da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5371da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5381da177e4SLinus Torvalds  *
5391da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5401da177e4SLinus Torvalds  * __GFP_FS.
5411da177e4SLinus Torvalds  */
5421da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5431da177e4SLinus Torvalds 				struct page *page, int error)
5441da177e4SLinus Torvalds {
5457eaceaccSJens Axboe 	lock_page(page);
5463e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5473e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5481da177e4SLinus Torvalds 	unlock_page(page);
5491da177e4SLinus Torvalds }
5501da177e4SLinus Torvalds 
55104e62a29SChristoph Lameter /* possible outcome of pageout() */
55204e62a29SChristoph Lameter typedef enum {
55304e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
55404e62a29SChristoph Lameter 	PAGE_KEEP,
55504e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
55604e62a29SChristoph Lameter 	PAGE_ACTIVATE,
55704e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
55804e62a29SChristoph Lameter 	PAGE_SUCCESS,
55904e62a29SChristoph Lameter 	/* page is clean and locked */
56004e62a29SChristoph Lameter 	PAGE_CLEAN,
56104e62a29SChristoph Lameter } pageout_t;
56204e62a29SChristoph Lameter 
5631da177e4SLinus Torvalds /*
5641742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5651742f19fSAndrew Morton  * Calls ->writepage().
5661da177e4SLinus Torvalds  */
567c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5687d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5691da177e4SLinus Torvalds {
5701da177e4SLinus Torvalds 	/*
5711da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5721da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5731da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5741da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5751da177e4SLinus Torvalds 	 * PagePrivate for that.
5761da177e4SLinus Torvalds 	 *
5778174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5781da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5791da177e4SLinus Torvalds 	 * will block.
5801da177e4SLinus Torvalds 	 *
5811da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5821da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5831da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5841da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5851da177e4SLinus Torvalds 	 */
5861da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5871da177e4SLinus Torvalds 		return PAGE_KEEP;
5881da177e4SLinus Torvalds 	if (!mapping) {
5891da177e4SLinus Torvalds 		/*
5901da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5911da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
5921da177e4SLinus Torvalds 		 */
593266cf658SDavid Howells 		if (page_has_private(page)) {
5941da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
5951da177e4SLinus Torvalds 				ClearPageDirty(page);
596b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
5971da177e4SLinus Torvalds 				return PAGE_CLEAN;
5981da177e4SLinus Torvalds 			}
5991da177e4SLinus Torvalds 		}
6001da177e4SLinus Torvalds 		return PAGE_KEEP;
6011da177e4SLinus Torvalds 	}
6021da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6031da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
604703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6051da177e4SLinus Torvalds 		return PAGE_KEEP;
6061da177e4SLinus Torvalds 
6071da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6081da177e4SLinus Torvalds 		int res;
6091da177e4SLinus Torvalds 		struct writeback_control wbc = {
6101da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6111da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
612111ebb6eSOGAWA Hirofumi 			.range_start = 0,
613111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6141da177e4SLinus Torvalds 			.for_reclaim = 1,
6151da177e4SLinus Torvalds 		};
6161da177e4SLinus Torvalds 
6171da177e4SLinus Torvalds 		SetPageReclaim(page);
6181da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6191da177e4SLinus Torvalds 		if (res < 0)
6201da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
621994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6221da177e4SLinus Torvalds 			ClearPageReclaim(page);
6231da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6241da177e4SLinus Torvalds 		}
625c661b078SAndy Whitcroft 
6261da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6271da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6281da177e4SLinus Torvalds 			ClearPageReclaim(page);
6291da177e4SLinus Torvalds 		}
6303aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
631c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6321da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6331da177e4SLinus Torvalds 	}
6341da177e4SLinus Torvalds 
6351da177e4SLinus Torvalds 	return PAGE_CLEAN;
6361da177e4SLinus Torvalds }
6371da177e4SLinus Torvalds 
638a649fd92SAndrew Morton /*
639e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
640e286781dSNick Piggin  * gets returned with a refcount of 0.
641a649fd92SAndrew Morton  */
642a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
643a528910eSJohannes Weiner 			    bool reclaimed)
64449d2e9ccSChristoph Lameter {
645c4843a75SGreg Thelen 	unsigned long flags;
646bd4c82c2SHuang Ying 	int refcount;
647c4843a75SGreg Thelen 
64828e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
64928e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
65049d2e9ccSChristoph Lameter 
651c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
65249d2e9ccSChristoph Lameter 	/*
6530fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6540fd0e6b0SNick Piggin 	 *
6550fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6560fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6570fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6580fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6590fd0e6b0SNick Piggin 	 *
6600fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6610fd0e6b0SNick Piggin 	 * [user mapping goes away]
6620fd0e6b0SNick Piggin 	 * write_to(page);
6630fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6640fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6650fd0e6b0SNick Piggin 	 * put_page(page);
6660fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6670fd0e6b0SNick Piggin 	 *
6680fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6690fd0e6b0SNick Piggin 	 *
6700fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6710fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6720139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6730fd0e6b0SNick Piggin 	 *
6740fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6750fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
67649d2e9ccSChristoph Lameter 	 */
677bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
678bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
679bd4c82c2SHuang Ying 	else
680bd4c82c2SHuang Ying 		refcount = 2;
681bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
68249d2e9ccSChristoph Lameter 		goto cannot_free;
683e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
684e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
685bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
68649d2e9ccSChristoph Lameter 		goto cannot_free;
687e286781dSNick Piggin 	}
68849d2e9ccSChristoph Lameter 
68949d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
69049d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6910a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
69249d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
693c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
69475f6d6d2SMinchan Kim 		put_swap_page(page, swap);
695e286781dSNick Piggin 	} else {
6966072d13cSLinus Torvalds 		void (*freepage)(struct page *);
697a528910eSJohannes Weiner 		void *shadow = NULL;
6986072d13cSLinus Torvalds 
6996072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
700a528910eSJohannes Weiner 		/*
701a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
702a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
703a528910eSJohannes Weiner 		 *
704a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
705a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
706a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
707a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
708a528910eSJohannes Weiner 		 * back.
709f9fe48beSRoss Zwisler 		 *
710f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
711f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
712f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
713f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
714f9fe48beSRoss Zwisler 		 * same page_tree.
715a528910eSJohannes Weiner 		 */
716a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
717f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
718a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
71962cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
720c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7216072d13cSLinus Torvalds 
7226072d13cSLinus Torvalds 		if (freepage != NULL)
7236072d13cSLinus Torvalds 			freepage(page);
724e286781dSNick Piggin 	}
725e286781dSNick Piggin 
72649d2e9ccSChristoph Lameter 	return 1;
72749d2e9ccSChristoph Lameter 
72849d2e9ccSChristoph Lameter cannot_free:
729c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
73049d2e9ccSChristoph Lameter 	return 0;
73149d2e9ccSChristoph Lameter }
73249d2e9ccSChristoph Lameter 
7331da177e4SLinus Torvalds /*
734e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
735e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
736e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
737e286781dSNick Piggin  * this page.
738e286781dSNick Piggin  */
739e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
740e286781dSNick Piggin {
741a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
742e286781dSNick Piggin 		/*
743e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
744e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
745e286781dSNick Piggin 		 * atomic operation.
746e286781dSNick Piggin 		 */
747fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
748e286781dSNick Piggin 		return 1;
749e286781dSNick Piggin 	}
750e286781dSNick Piggin 	return 0;
751e286781dSNick Piggin }
752e286781dSNick Piggin 
753894bc310SLee Schermerhorn /**
754894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
755894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
756894bc310SLee Schermerhorn  *
757894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
758894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
759894bc310SLee Schermerhorn  *
760894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
761894bc310SLee Schermerhorn  */
762894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
763894bc310SLee Schermerhorn {
764c53954a0SMel Gorman 	lru_cache_add(page);
765894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
766894bc310SLee Schermerhorn }
767894bc310SLee Schermerhorn 
768dfc8d636SJohannes Weiner enum page_references {
769dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
770dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
77164574746SJohannes Weiner 	PAGEREF_KEEP,
772dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
773dfc8d636SJohannes Weiner };
774dfc8d636SJohannes Weiner 
775dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
776dfc8d636SJohannes Weiner 						  struct scan_control *sc)
777dfc8d636SJohannes Weiner {
77864574746SJohannes Weiner 	int referenced_ptes, referenced_page;
779dfc8d636SJohannes Weiner 	unsigned long vm_flags;
780dfc8d636SJohannes Weiner 
781c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
782c3ac9a8aSJohannes Weiner 					  &vm_flags);
78364574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
784dfc8d636SJohannes Weiner 
785dfc8d636SJohannes Weiner 	/*
786dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
787dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
788dfc8d636SJohannes Weiner 	 */
789dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
790dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
791dfc8d636SJohannes Weiner 
79264574746SJohannes Weiner 	if (referenced_ptes) {
793e4898273SMichal Hocko 		if (PageSwapBacked(page))
79464574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
79564574746SJohannes Weiner 		/*
79664574746SJohannes Weiner 		 * All mapped pages start out with page table
79764574746SJohannes Weiner 		 * references from the instantiating fault, so we need
79864574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
79964574746SJohannes Weiner 		 * than once.
80064574746SJohannes Weiner 		 *
80164574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
80264574746SJohannes Weiner 		 * inactive list.  Another page table reference will
80364574746SJohannes Weiner 		 * lead to its activation.
80464574746SJohannes Weiner 		 *
80564574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
80664574746SJohannes Weiner 		 * so that recently deactivated but used pages are
80764574746SJohannes Weiner 		 * quickly recovered.
80864574746SJohannes Weiner 		 */
80964574746SJohannes Weiner 		SetPageReferenced(page);
81064574746SJohannes Weiner 
81134dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
812dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
813dfc8d636SJohannes Weiner 
814c909e993SKonstantin Khlebnikov 		/*
815c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
816c909e993SKonstantin Khlebnikov 		 */
817c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
818c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
819c909e993SKonstantin Khlebnikov 
82064574746SJohannes Weiner 		return PAGEREF_KEEP;
82164574746SJohannes Weiner 	}
82264574746SJohannes Weiner 
823dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8242e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
825dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
82664574746SJohannes Weiner 
82764574746SJohannes Weiner 	return PAGEREF_RECLAIM;
828dfc8d636SJohannes Weiner }
829dfc8d636SJohannes Weiner 
830e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
831e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
832e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
833e2be15f6SMel Gorman {
834b4597226SMel Gorman 	struct address_space *mapping;
835b4597226SMel Gorman 
836e2be15f6SMel Gorman 	/*
837e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
838e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
839e2be15f6SMel Gorman 	 */
840802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
841802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
842e2be15f6SMel Gorman 		*dirty = false;
843e2be15f6SMel Gorman 		*writeback = false;
844e2be15f6SMel Gorman 		return;
845e2be15f6SMel Gorman 	}
846e2be15f6SMel Gorman 
847e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
848e2be15f6SMel Gorman 	*dirty = PageDirty(page);
849e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
850b4597226SMel Gorman 
851b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
852b4597226SMel Gorman 	if (!page_has_private(page))
853b4597226SMel Gorman 		return;
854b4597226SMel Gorman 
855b4597226SMel Gorman 	mapping = page_mapping(page);
856b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
857b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
858e2be15f6SMel Gorman }
859e2be15f6SMel Gorman 
8603c710c1aSMichal Hocko struct reclaim_stat {
8613c710c1aSMichal Hocko 	unsigned nr_dirty;
8623c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty;
8633c710c1aSMichal Hocko 	unsigned nr_congested;
8643c710c1aSMichal Hocko 	unsigned nr_writeback;
8653c710c1aSMichal Hocko 	unsigned nr_immediate;
8665bccd166SMichal Hocko 	unsigned nr_activate;
8675bccd166SMichal Hocko 	unsigned nr_ref_keep;
8685bccd166SMichal Hocko 	unsigned nr_unmap_fail;
8693c710c1aSMichal Hocko };
8703c710c1aSMichal Hocko 
871e286781dSNick Piggin /*
8721742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
8731da177e4SLinus Torvalds  */
8741742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
875599d0c95SMel Gorman 				      struct pglist_data *pgdat,
876f84f6e2bSMel Gorman 				      struct scan_control *sc,
87702c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
8783c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
87902c6de8dSMinchan Kim 				      bool force_reclaim)
8801da177e4SLinus Torvalds {
8811da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
882abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
8831da177e4SLinus Torvalds 	int pgactivate = 0;
8843c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
8853c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
8863c710c1aSMichal Hocko 	unsigned nr_congested = 0;
8873c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
8883c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
8893c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
8905bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
8915bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
8921da177e4SLinus Torvalds 
8931da177e4SLinus Torvalds 	cond_resched();
8941da177e4SLinus Torvalds 
8951da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
8961da177e4SLinus Torvalds 		struct address_space *mapping;
8971da177e4SLinus Torvalds 		struct page *page;
8981da177e4SLinus Torvalds 		int may_enter_fs;
89902c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
900e2be15f6SMel Gorman 		bool dirty, writeback;
9011da177e4SLinus Torvalds 
9021da177e4SLinus Torvalds 		cond_resched();
9031da177e4SLinus Torvalds 
9041da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9051da177e4SLinus Torvalds 		list_del(&page->lru);
9061da177e4SLinus Torvalds 
907529ae9aaSNick Piggin 		if (!trylock_page(page))
9081da177e4SLinus Torvalds 			goto keep;
9091da177e4SLinus Torvalds 
910309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9111da177e4SLinus Torvalds 
9121da177e4SLinus Torvalds 		sc->nr_scanned++;
91380e43426SChristoph Lameter 
91439b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
915ad6b6704SMinchan Kim 			goto activate_locked;
916894bc310SLee Schermerhorn 
917a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
91880e43426SChristoph Lameter 			goto keep_locked;
91980e43426SChristoph Lameter 
9201da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
921802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
922802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
9231da177e4SLinus Torvalds 			sc->nr_scanned++;
9241da177e4SLinus Torvalds 
925c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
926c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
927c661b078SAndy Whitcroft 
928e62e384eSMichal Hocko 		/*
929*894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
930e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
931e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
932e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
933e2be15f6SMel Gorman 		 */
934e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
935e2be15f6SMel Gorman 		if (dirty || writeback)
936e2be15f6SMel Gorman 			nr_dirty++;
937e2be15f6SMel Gorman 
938e2be15f6SMel Gorman 		if (dirty && !writeback)
939e2be15f6SMel Gorman 			nr_unqueued_dirty++;
940e2be15f6SMel Gorman 
941d04e8acdSMel Gorman 		/*
942d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
943d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
944d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
945d04e8acdSMel Gorman 		 * end of the LRU a second time.
946d04e8acdSMel Gorman 		 */
947e2be15f6SMel Gorman 		mapping = page_mapping(page);
9481da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
949703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
950d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
951e2be15f6SMel Gorman 			nr_congested++;
952e2be15f6SMel Gorman 
953e2be15f6SMel Gorman 		/*
954283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
955283aba9fSMel Gorman 		 * are three cases to consider.
956e62e384eSMichal Hocko 		 *
957283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
958283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
959283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
960283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
961283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
962283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
963283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
964b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
965b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
966c3b94f44SHugh Dickins 		 *
96797c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
968ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
969ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
970ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
97197c9341fSTejun Heo 		 *    reclaim and continue scanning.
972283aba9fSMel Gorman 		 *
973ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
974ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
975283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
976283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
977283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
978283aba9fSMel Gorman 		 *    would probably show more reasons.
979283aba9fSMel Gorman 		 *
9807fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
981283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
982283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
983283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
984283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
985c55e8d03SJohannes Weiner 		 *
986c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
987c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
988c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
989c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
990c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
991c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
992c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
993c55e8d03SJohannes Weiner 		 * takes to write them to disk.
994e62e384eSMichal Hocko 		 */
995283aba9fSMel Gorman 		if (PageWriteback(page)) {
996283aba9fSMel Gorman 			/* Case 1 above */
997283aba9fSMel Gorman 			if (current_is_kswapd() &&
998283aba9fSMel Gorman 			    PageReclaim(page) &&
999599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1000b1a6f21eSMel Gorman 				nr_immediate++;
1001c55e8d03SJohannes Weiner 				goto activate_locked;
1002283aba9fSMel Gorman 
1003283aba9fSMel Gorman 			/* Case 2 above */
100497c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1005ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1006c3b94f44SHugh Dickins 				/*
1007c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1008c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1009c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1010c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1011c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1012c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1013c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1014c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1015c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1016c3b94f44SHugh Dickins 				 */
1017c3b94f44SHugh Dickins 				SetPageReclaim(page);
101892df3a72SMel Gorman 				nr_writeback++;
1019c55e8d03SJohannes Weiner 				goto activate_locked;
1020283aba9fSMel Gorman 
1021283aba9fSMel Gorman 			/* Case 3 above */
1022283aba9fSMel Gorman 			} else {
10237fadc820SHugh Dickins 				unlock_page(page);
1024c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10257fadc820SHugh Dickins 				/* then go back and try same page again */
10267fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10277fadc820SHugh Dickins 				continue;
1028e62e384eSMichal Hocko 			}
1029283aba9fSMel Gorman 		}
10301da177e4SLinus Torvalds 
103102c6de8dSMinchan Kim 		if (!force_reclaim)
10326a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
103302c6de8dSMinchan Kim 
1034dfc8d636SJohannes Weiner 		switch (references) {
1035dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10361da177e4SLinus Torvalds 			goto activate_locked;
103764574746SJohannes Weiner 		case PAGEREF_KEEP:
10385bccd166SMichal Hocko 			nr_ref_keep++;
103964574746SJohannes Weiner 			goto keep_locked;
1040dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1041dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1042dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1043dfc8d636SJohannes Weiner 		}
10441da177e4SLinus Torvalds 
10451da177e4SLinus Torvalds 		/*
10461da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
10471da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1048802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
10491da177e4SLinus Torvalds 		 */
1050bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1051bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
105263eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
105363eb6b93SHugh Dickins 					goto keep_locked;
1054747552b1SHuang Ying 				if (PageTransHuge(page)) {
1055b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1056747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1057b8f593cdSHuang Ying 						goto activate_locked;
1058747552b1SHuang Ying 					/*
1059747552b1SHuang Ying 					 * Split pages without a PMD map right
1060747552b1SHuang Ying 					 * away. Chances are some or all of the
1061747552b1SHuang Ying 					 * tail pages can be freed without IO.
1062747552b1SHuang Ying 					 */
1063747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1064bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1065bd4c82c2SHuang Ying 								    page_list))
1066747552b1SHuang Ying 						goto activate_locked;
1067747552b1SHuang Ying 				}
10680f074658SMinchan Kim 				if (!add_to_swap(page)) {
10690f074658SMinchan Kim 					if (!PageTransHuge(page))
10701da177e4SLinus Torvalds 						goto activate_locked;
1071bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1072bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1073bd4c82c2SHuang Ying 								    page_list))
10740f074658SMinchan Kim 						goto activate_locked;
1075fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1076fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1077fe490cc0SHuang Ying #endif
10780f074658SMinchan Kim 					if (!add_to_swap(page))
10790f074658SMinchan Kim 						goto activate_locked;
10800f074658SMinchan Kim 				}
10810f074658SMinchan Kim 
108263eb6b93SHugh Dickins 				may_enter_fs = 1;
10831da177e4SLinus Torvalds 
1084e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
10851da177e4SLinus Torvalds 				mapping = page_mapping(page);
1086bd4c82c2SHuang Ying 			}
10877751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
10887751b2daSKirill A. Shutemov 			/* Split file THP */
10897751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
10907751b2daSKirill A. Shutemov 				goto keep_locked;
1091e2be15f6SMel Gorman 		}
10921da177e4SLinus Torvalds 
10931da177e4SLinus Torvalds 		/*
10941da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
10951da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
10961da177e4SLinus Torvalds 		 */
1097802a3a92SShaohua Li 		if (page_mapped(page)) {
1098bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1099bd4c82c2SHuang Ying 
1100bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1101bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1102bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
11035bccd166SMichal Hocko 				nr_unmap_fail++;
11041da177e4SLinus Torvalds 				goto activate_locked;
11051da177e4SLinus Torvalds 			}
11061da177e4SLinus Torvalds 		}
11071da177e4SLinus Torvalds 
11081da177e4SLinus Torvalds 		if (PageDirty(page)) {
1109ee72886dSMel Gorman 			/*
11104eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
11114eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
11124eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
11134eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
11144eda4823SJohannes Weiner 			 * write pages when we've encountered many
11154eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
11164eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
11174eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1118ee72886dSMel Gorman 			 */
1119f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11204eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1121599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
112249ea7eb6SMel Gorman 				/*
112349ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
112449ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
112549ea7eb6SMel Gorman 				 * except we already have the page isolated
112649ea7eb6SMel Gorman 				 * and know it's dirty
112749ea7eb6SMel Gorman 				 */
1128c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
112949ea7eb6SMel Gorman 				SetPageReclaim(page);
113049ea7eb6SMel Gorman 
1131c55e8d03SJohannes Weiner 				goto activate_locked;
1132ee72886dSMel Gorman 			}
1133ee72886dSMel Gorman 
1134dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11351da177e4SLinus Torvalds 				goto keep_locked;
11364dd4b920SAndrew Morton 			if (!may_enter_fs)
11371da177e4SLinus Torvalds 				goto keep_locked;
113852a8363eSChristoph Lameter 			if (!sc->may_writepage)
11391da177e4SLinus Torvalds 				goto keep_locked;
11401da177e4SLinus Torvalds 
1141d950c947SMel Gorman 			/*
1142d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1143d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1144d950c947SMel Gorman 			 * starts and then write it out here.
1145d950c947SMel Gorman 			 */
1146d950c947SMel Gorman 			try_to_unmap_flush_dirty();
11477d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
11481da177e4SLinus Torvalds 			case PAGE_KEEP:
11491da177e4SLinus Torvalds 				goto keep_locked;
11501da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
11511da177e4SLinus Torvalds 				goto activate_locked;
11521da177e4SLinus Torvalds 			case PAGE_SUCCESS:
11537d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
115441ac1999SMel Gorman 					goto keep;
11557d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
11561da177e4SLinus Torvalds 					goto keep;
11577d3579e8SKOSAKI Motohiro 
11581da177e4SLinus Torvalds 				/*
11591da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
11601da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
11611da177e4SLinus Torvalds 				 */
1162529ae9aaSNick Piggin 				if (!trylock_page(page))
11631da177e4SLinus Torvalds 					goto keep;
11641da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
11651da177e4SLinus Torvalds 					goto keep_locked;
11661da177e4SLinus Torvalds 				mapping = page_mapping(page);
11671da177e4SLinus Torvalds 			case PAGE_CLEAN:
11681da177e4SLinus Torvalds 				; /* try to free the page below */
11691da177e4SLinus Torvalds 			}
11701da177e4SLinus Torvalds 		}
11711da177e4SLinus Torvalds 
11721da177e4SLinus Torvalds 		/*
11731da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
11741da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
11751da177e4SLinus Torvalds 		 * the page as well.
11761da177e4SLinus Torvalds 		 *
11771da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
11781da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
11791da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
11801da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
11811da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
11821da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
11831da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
11841da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
11851da177e4SLinus Torvalds 		 *
11861da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
11871da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
11881da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
11891da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
11901da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
11911da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
11921da177e4SLinus Torvalds 		 */
1193266cf658SDavid Howells 		if (page_has_private(page)) {
11941da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
11951da177e4SLinus Torvalds 				goto activate_locked;
1196e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1197e286781dSNick Piggin 				unlock_page(page);
1198e286781dSNick Piggin 				if (put_page_testzero(page))
11991da177e4SLinus Torvalds 					goto free_it;
1200e286781dSNick Piggin 				else {
1201e286781dSNick Piggin 					/*
1202e286781dSNick Piggin 					 * rare race with speculative reference.
1203e286781dSNick Piggin 					 * the speculative reference will free
1204e286781dSNick Piggin 					 * this page shortly, so we may
1205e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1206e286781dSNick Piggin 					 * leave it off the LRU).
1207e286781dSNick Piggin 					 */
1208e286781dSNick Piggin 					nr_reclaimed++;
1209e286781dSNick Piggin 					continue;
1210e286781dSNick Piggin 				}
1211e286781dSNick Piggin 			}
12121da177e4SLinus Torvalds 		}
12131da177e4SLinus Torvalds 
1214802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1215802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1216802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
121749d2e9ccSChristoph Lameter 				goto keep_locked;
1218802a3a92SShaohua Li 			if (PageDirty(page)) {
1219802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1220802a3a92SShaohua Li 				goto keep_locked;
1221802a3a92SShaohua Li 			}
12221da177e4SLinus Torvalds 
1223802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
12242262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1225802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1226802a3a92SShaohua Li 			goto keep_locked;
1227a978d6f5SNick Piggin 		/*
1228a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1229a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1230a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1231a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1232a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1233a978d6f5SNick Piggin 		 */
123448c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1235e286781dSNick Piggin free_it:
123605ff5137SAndrew Morton 		nr_reclaimed++;
1237abe4c3b5SMel Gorman 
1238abe4c3b5SMel Gorman 		/*
1239abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1240abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1241abe4c3b5SMel Gorman 		 */
1242bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1243bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1244bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1245bd4c82c2SHuang Ying 		} else
1246abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
12471da177e4SLinus Torvalds 		continue;
12481da177e4SLinus Torvalds 
12491da177e4SLinus Torvalds activate_locked:
125068a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1251ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1252ad6b6704SMinchan Kim 						PageMlocked(page)))
1253a2c43eedSHugh Dickins 			try_to_free_swap(page);
1254309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1255ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
12561da177e4SLinus Torvalds 			SetPageActive(page);
12571da177e4SLinus Torvalds 			pgactivate++;
12582262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1259ad6b6704SMinchan Kim 		}
12601da177e4SLinus Torvalds keep_locked:
12611da177e4SLinus Torvalds 		unlock_page(page);
12621da177e4SLinus Torvalds keep:
12631da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1264309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
12651da177e4SLinus Torvalds 	}
1266abe4c3b5SMel Gorman 
1267747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
126872b252aeSMel Gorman 	try_to_unmap_flush();
12692d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1270abe4c3b5SMel Gorman 
12711da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1272f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
12730a31bc97SJohannes Weiner 
12743c710c1aSMichal Hocko 	if (stat) {
12753c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
12763c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
12773c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
12783c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
12793c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
12805bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
12815bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
12825bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
12833c710c1aSMichal Hocko 	}
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 	};
12953c710c1aSMichal Hocko 	unsigned long ret;
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,
1308a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
130902c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1310599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
131102c6de8dSMinchan Kim 	return ret;
131202c6de8dSMinchan Kim }
131302c6de8dSMinchan Kim 
13145ad333ebSAndy Whitcroft /*
13155ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13165ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13175ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13185ad333ebSAndy Whitcroft  *
13195ad333ebSAndy Whitcroft  * page:	page to consider
13205ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13215ad333ebSAndy Whitcroft  *
13225ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13235ad333ebSAndy Whitcroft  */
1324f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13255ad333ebSAndy Whitcroft {
13265ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13275ad333ebSAndy Whitcroft 
13285ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13295ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13305ad333ebSAndy Whitcroft 		return ret;
13315ad333ebSAndy Whitcroft 
1332e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1333e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1334894bc310SLee Schermerhorn 		return ret;
1335894bc310SLee Schermerhorn 
13365ad333ebSAndy Whitcroft 	ret = -EBUSY;
133708e552c6SKAMEZAWA Hiroyuki 
1338c8244935SMel Gorman 	/*
1339c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1340c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1341c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1342c8244935SMel Gorman 	 *
1343c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1344c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1345c8244935SMel Gorman 	 */
13461276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1347c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1348c8244935SMel Gorman 		if (PageWriteback(page))
134939deaf85SMinchan Kim 			return ret;
135039deaf85SMinchan Kim 
1351c8244935SMel Gorman 		if (PageDirty(page)) {
1352c8244935SMel Gorman 			struct address_space *mapping;
135369d763fcSMel Gorman 			bool migrate_dirty;
1354c8244935SMel Gorman 
1355c8244935SMel Gorman 			/*
1356c8244935SMel Gorman 			 * Only pages without mappings or that have a
1357c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
135869d763fcSMel Gorman 			 * without blocking. However, we can be racing with
135969d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
136069d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
136169d763fcSMel Gorman 			 * the page lock until after the page is removed
136269d763fcSMel Gorman 			 * from the page cache.
1363c8244935SMel Gorman 			 */
136469d763fcSMel Gorman 			if (!trylock_page(page))
136569d763fcSMel Gorman 				return ret;
136669d763fcSMel Gorman 
1367c8244935SMel Gorman 			mapping = page_mapping(page);
136869d763fcSMel Gorman 			migrate_dirty = mapping && mapping->a_ops->migratepage;
136969d763fcSMel Gorman 			unlock_page(page);
137069d763fcSMel Gorman 			if (!migrate_dirty)
1371c8244935SMel Gorman 				return ret;
1372c8244935SMel Gorman 		}
1373c8244935SMel Gorman 	}
1374c8244935SMel Gorman 
1375f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1376f80c0673SMinchan Kim 		return ret;
1377f80c0673SMinchan Kim 
13785ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
13795ad333ebSAndy Whitcroft 		/*
13805ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
13815ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
13825ad333ebSAndy Whitcroft 		 * page release code relies on it.
13835ad333ebSAndy Whitcroft 		 */
13845ad333ebSAndy Whitcroft 		ClearPageLRU(page);
13855ad333ebSAndy Whitcroft 		ret = 0;
13865ad333ebSAndy Whitcroft 	}
13875ad333ebSAndy Whitcroft 
13885ad333ebSAndy Whitcroft 	return ret;
13895ad333ebSAndy Whitcroft }
13905ad333ebSAndy Whitcroft 
13917ee36a14SMel Gorman 
13927ee36a14SMel Gorman /*
13937ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
13947ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
13957ee36a14SMel Gorman  */
13967ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1397b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
13987ee36a14SMel Gorman {
13997ee36a14SMel Gorman 	int zid;
14007ee36a14SMel Gorman 
14017ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14027ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14037ee36a14SMel Gorman 			continue;
14047ee36a14SMel Gorman 
14057ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1406b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1407b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1408b4536f0cSMichal Hocko #endif
14097ee36a14SMel Gorman 	}
14107ee36a14SMel Gorman 
14117ee36a14SMel Gorman }
14127ee36a14SMel Gorman 
141349d2e9ccSChristoph Lameter /*
1414a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14151da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14161da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14171da177e4SLinus Torvalds  *
14181da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14191da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14201da177e4SLinus Torvalds  *
14211da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14221da177e4SLinus Torvalds  *
1423791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
14245dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14251da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1426f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1427fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14285ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14293cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14301da177e4SLinus Torvalds  *
14311da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14321da177e4SLinus Torvalds  */
143369e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14345dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1435fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14363cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14371da177e4SLinus Torvalds {
143875b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
143969e05944SAndrew Morton 	unsigned long nr_taken = 0;
1440599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14417cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
14423db65812SJohannes Weiner 	unsigned long skipped = 0;
1443791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1444b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14451da177e4SLinus Torvalds 
1446791b48b6SMinchan Kim 	scan = 0;
1447791b48b6SMinchan Kim 	for (total_scan = 0;
1448791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1449791b48b6SMinchan Kim 	     total_scan++) {
14505ad333ebSAndy Whitcroft 		struct page *page;
14515ad333ebSAndy Whitcroft 
14521da177e4SLinus Torvalds 		page = lru_to_page(src);
14531da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
14541da177e4SLinus Torvalds 
1455309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
14568d438f96SNick Piggin 
1457b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1458b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
14597cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1460b2e18757SMel Gorman 			continue;
1461b2e18757SMel Gorman 		}
1462b2e18757SMel Gorman 
1463791b48b6SMinchan Kim 		/*
1464791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1465791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1466791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1467791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1468791b48b6SMinchan Kim 		 */
1469791b48b6SMinchan Kim 		scan++;
1470f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
14715ad333ebSAndy Whitcroft 		case 0:
1472599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1473599d0c95SMel Gorman 			nr_taken += nr_pages;
1474599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
14755ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
14765ad333ebSAndy Whitcroft 			break;
14777c8ee9a8SNick Piggin 
14785ad333ebSAndy Whitcroft 		case -EBUSY:
14795ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
14805ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
14815ad333ebSAndy Whitcroft 			continue;
14825ad333ebSAndy Whitcroft 
14835ad333ebSAndy Whitcroft 		default:
14845ad333ebSAndy Whitcroft 			BUG();
14855ad333ebSAndy Whitcroft 		}
14865ad333ebSAndy Whitcroft 	}
14871da177e4SLinus Torvalds 
1488b2e18757SMel Gorman 	/*
1489b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1490b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1491b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1492b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1493b2e18757SMel Gorman 	 * system at risk of premature OOM.
1494b2e18757SMel Gorman 	 */
14957cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
14967cc30fcfSMel Gorman 		int zid;
14977cc30fcfSMel Gorman 
14983db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
14997cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15007cc30fcfSMel Gorman 			if (!nr_skipped[zid])
15017cc30fcfSMel Gorman 				continue;
15027cc30fcfSMel Gorman 
15037cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
15041265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
15057cc30fcfSMel Gorman 		}
15067cc30fcfSMel Gorman 	}
1507791b48b6SMinchan Kim 	*nr_scanned = total_scan;
15081265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1509791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1510b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15111da177e4SLinus Torvalds 	return nr_taken;
15121da177e4SLinus Torvalds }
15131da177e4SLinus Torvalds 
151462695a84SNick Piggin /**
151562695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
151662695a84SNick Piggin  * @page: page to isolate from its LRU list
151762695a84SNick Piggin  *
151862695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
151962695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
152062695a84SNick Piggin  *
152162695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
152262695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
152362695a84SNick Piggin  *
152462695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1525894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1526894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1527894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
152862695a84SNick Piggin  *
152962695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
153062695a84SNick Piggin  * found will be decremented.
153162695a84SNick Piggin  *
153262695a84SNick Piggin  * Restrictions:
1533a5d09bedSMike Rapoport  *
153462695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
153562695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
153662695a84SNick Piggin  *     without a stable reference).
153762695a84SNick Piggin  * (2) the lru_lock must not be held.
153862695a84SNick Piggin  * (3) interrupts must be enabled.
153962695a84SNick Piggin  */
154062695a84SNick Piggin int isolate_lru_page(struct page *page)
154162695a84SNick Piggin {
154262695a84SNick Piggin 	int ret = -EBUSY;
154362695a84SNick Piggin 
1544309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1545cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15460c917313SKonstantin Khlebnikov 
154762695a84SNick Piggin 	if (PageLRU(page)) {
154862695a84SNick Piggin 		struct zone *zone = page_zone(page);
1549fa9add64SHugh Dickins 		struct lruvec *lruvec;
155062695a84SNick Piggin 
1551a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1552599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
15530c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1554894bc310SLee Schermerhorn 			int lru = page_lru(page);
15550c917313SKonstantin Khlebnikov 			get_page(page);
155662695a84SNick Piggin 			ClearPageLRU(page);
1557fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1558fa9add64SHugh Dickins 			ret = 0;
155962695a84SNick Piggin 		}
1560a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
156162695a84SNick Piggin 	}
156262695a84SNick Piggin 	return ret;
156362695a84SNick Piggin }
156462695a84SNick Piggin 
15655ad333ebSAndy Whitcroft /*
1566d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1567d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1568d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1569d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1570d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
157135cd7815SRik van Riel  */
1572599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
157335cd7815SRik van Riel 		struct scan_control *sc)
157435cd7815SRik van Riel {
157535cd7815SRik van Riel 	unsigned long inactive, isolated;
157635cd7815SRik van Riel 
157735cd7815SRik van Riel 	if (current_is_kswapd())
157835cd7815SRik van Riel 		return 0;
157935cd7815SRik van Riel 
158097c9341fSTejun Heo 	if (!sane_reclaim(sc))
158135cd7815SRik van Riel 		return 0;
158235cd7815SRik van Riel 
158335cd7815SRik van Riel 	if (file) {
1584599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1585599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
158635cd7815SRik van Riel 	} else {
1587599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1588599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
158935cd7815SRik van Riel 	}
159035cd7815SRik van Riel 
15913cf23841SFengguang Wu 	/*
15923cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
15933cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
15943cf23841SFengguang Wu 	 * deadlock.
15953cf23841SFengguang Wu 	 */
1596d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
15973cf23841SFengguang Wu 		inactive >>= 3;
15983cf23841SFengguang Wu 
159935cd7815SRik van Riel 	return isolated > inactive;
160035cd7815SRik van Riel }
160135cd7815SRik van Riel 
160266635629SMel Gorman static noinline_for_stack void
160375b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
160466635629SMel Gorman {
160527ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1606599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16073f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
160866635629SMel Gorman 
160966635629SMel Gorman 	/*
161066635629SMel Gorman 	 * Put back any unfreeable pages.
161166635629SMel Gorman 	 */
161266635629SMel Gorman 	while (!list_empty(page_list)) {
16133f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
161466635629SMel Gorman 		int lru;
16153f79768fSHugh Dickins 
1616309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
161766635629SMel Gorman 		list_del(&page->lru);
161839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1619599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
162066635629SMel Gorman 			putback_lru_page(page);
1621599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
162266635629SMel Gorman 			continue;
162366635629SMel Gorman 		}
1624fa9add64SHugh Dickins 
1625599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1626fa9add64SHugh Dickins 
16277a608572SLinus Torvalds 		SetPageLRU(page);
162866635629SMel Gorman 		lru = page_lru(page);
1629fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1630fa9add64SHugh Dickins 
163166635629SMel Gorman 		if (is_active_lru(lru)) {
163266635629SMel Gorman 			int file = is_file_lru(lru);
16339992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16349992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
163566635629SMel Gorman 		}
16362bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16372bcf8879SHugh Dickins 			__ClearPageLRU(page);
16382bcf8879SHugh Dickins 			__ClearPageActive(page);
1639fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16402bcf8879SHugh Dickins 
16412bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1642599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1643747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16442bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1645599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16462bcf8879SHugh Dickins 			} else
16472bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
164866635629SMel Gorman 		}
164966635629SMel Gorman 	}
165066635629SMel Gorman 
16513f79768fSHugh Dickins 	/*
16523f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
16533f79768fSHugh Dickins 	 */
16543f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
165566635629SMel Gorman }
165666635629SMel Gorman 
165766635629SMel Gorman /*
1658399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1659399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1660399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1661399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1662399ba0b9SNeilBrown  */
1663399ba0b9SNeilBrown static int current_may_throttle(void)
1664399ba0b9SNeilBrown {
1665399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1666399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1667399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1668399ba0b9SNeilBrown }
1669399ba0b9SNeilBrown 
1670399ba0b9SNeilBrown /*
1671b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
16721742f19fSAndrew Morton  * of reclaimed pages
16731da177e4SLinus Torvalds  */
167466635629SMel Gorman static noinline_for_stack unsigned long
16751a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
16769e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
16771da177e4SLinus Torvalds {
16781da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1679e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
168005ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1681e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
16823c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1683f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
16843cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1685599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16861a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1687db73ee0dSMichal Hocko 	bool stalled = false;
168878dc583dSKOSAKI Motohiro 
1689599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1690db73ee0dSMichal Hocko 		if (stalled)
1691db73ee0dSMichal Hocko 			return 0;
1692db73ee0dSMichal Hocko 
1693db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1694db73ee0dSMichal Hocko 		msleep(100);
1695db73ee0dSMichal Hocko 		stalled = true;
169635cd7815SRik van Riel 
169735cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
169835cd7815SRik van Riel 		if (fatal_signal_pending(current))
169935cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
170035cd7815SRik van Riel 	}
170135cd7815SRik van Riel 
17021da177e4SLinus Torvalds 	lru_add_drain();
1703f80c0673SMinchan Kim 
1704f80c0673SMinchan Kim 	if (!sc->may_unmap)
170561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1706f80c0673SMinchan Kim 
1707599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17081da177e4SLinus Torvalds 
17095dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17105dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
171195d918fcSKonstantin Khlebnikov 
1712599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17139d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
171495d918fcSKonstantin Khlebnikov 
17152262185cSRoman Gushchin 	if (current_is_kswapd()) {
17162262185cSRoman Gushchin 		if (global_reclaim(sc))
1717599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
17182262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
17192262185cSRoman Gushchin 				   nr_scanned);
17202262185cSRoman Gushchin 	} else {
17212262185cSRoman Gushchin 		if (global_reclaim(sc))
1722599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
17232262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
17242262185cSRoman Gushchin 				   nr_scanned);
1725b35ea17bSKOSAKI Motohiro 	}
1726599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1727d563c050SHillf Danton 
1728d563c050SHillf Danton 	if (nr_taken == 0)
172966635629SMel Gorman 		return 0;
1730b35ea17bSKOSAKI Motohiro 
1731a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
17323c710c1aSMichal Hocko 				&stat, false);
1733c661b078SAndy Whitcroft 
1734599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17353f79768fSHugh Dickins 
17362262185cSRoman Gushchin 	if (current_is_kswapd()) {
17372262185cSRoman Gushchin 		if (global_reclaim(sc))
1738599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
17392262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
17402262185cSRoman Gushchin 				   nr_reclaimed);
17412262185cSRoman Gushchin 	} else {
17422262185cSRoman Gushchin 		if (global_reclaim(sc))
1743599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
17442262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
17452262185cSRoman Gushchin 				   nr_reclaimed);
1746904249aaSYing Han 	}
1747a74609faSNick Piggin 
174827ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
17493f79768fSHugh Dickins 
1750599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
17513f79768fSHugh Dickins 
1752599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
17533f79768fSHugh Dickins 
1754747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
17552d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1756e11da5b4SMel Gorman 
175792df3a72SMel Gorman 	/*
175892df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
175992df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
176092df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
176192df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
176292df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
176392df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
176492df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
176592df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
176692df3a72SMel Gorman 	 *
1767*894befecSAndrey Ryabinin 	 * Once a node is flagged PGDAT_WRITEBACK, kswapd will count the number
17688e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
17698e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
177092df3a72SMel Gorman 	 */
17713c710c1aSMichal Hocko 	if (stat.nr_writeback && stat.nr_writeback == nr_taken)
1772599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
177392df3a72SMel Gorman 
1774d43006d5SMel Gorman 	/*
17751c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
17761c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
17771c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
17781c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
17791c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
17801c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
17811c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
17821c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
17831c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
17841c610d5fSAndrey Ryabinin 	 */
17851c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
17861c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
17871c610d5fSAndrey Ryabinin 
17881c610d5fSAndrey Ryabinin 	/*
178997c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
179097c9341fSTejun Heo 	 * stalling here.
1791d43006d5SMel Gorman 	 */
179297c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1793b1a6f21eSMel Gorman 		/*
1794*894befecSAndrey Ryabinin 		 * Tag a node as congested if all the dirty pages scanned were
17958e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
17968e950282SMel Gorman 		 */
17973c710c1aSMichal Hocko 		if (stat.nr_dirty && stat.nr_dirty == stat.nr_congested)
1798599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
17998e950282SMel Gorman 
18001c610d5fSAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim. */
18011c610d5fSAndrey Ryabinin 		if (stat.nr_unqueued_dirty == nr_taken)
1802599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1803b1a6f21eSMel Gorman 
1804b1a6f21eSMel Gorman 		/*
1805b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1806b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1807b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1808b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1809b1a6f21eSMel Gorman 		 */
18103c710c1aSMichal Hocko 		if (stat.nr_immediate && current_may_throttle())
1811b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1812e2be15f6SMel Gorman 	}
1813d43006d5SMel Gorman 
18148e950282SMel Gorman 	/*
1815*894befecSAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs and node
18168e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18178e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18188e950282SMel Gorman 	 */
1819399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1820399ba0b9SNeilBrown 	    current_may_throttle())
1821599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18228e950282SMel Gorman 
1823599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1824599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
18255bccd166SMichal Hocko 			stat.nr_dirty,  stat.nr_writeback,
18265bccd166SMichal Hocko 			stat.nr_congested, stat.nr_immediate,
18275bccd166SMichal Hocko 			stat.nr_activate, stat.nr_ref_keep,
18285bccd166SMichal Hocko 			stat.nr_unmap_fail,
1829ba5e9579Syalin wang 			sc->priority, file);
183005ff5137SAndrew Morton 	return nr_reclaimed;
18311da177e4SLinus Torvalds }
18321da177e4SLinus Torvalds 
18333bb1a852SMartin Bligh /*
18341cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18351cfb419bSKAMEZAWA Hiroyuki  *
18361cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18371cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18381cfb419bSKAMEZAWA Hiroyuki  *
18391cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1840a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18411cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1842a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18431cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18441cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18451cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18461cfb419bSKAMEZAWA Hiroyuki  *
18470139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18481cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
18499d998b4fSMichal Hocko  *
18509d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
18511cfb419bSKAMEZAWA Hiroyuki  */
18521cfb419bSKAMEZAWA Hiroyuki 
18539d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
18543eb4140fSWu Fengguang 				     struct list_head *list,
18552bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18563eb4140fSWu Fengguang 				     enum lru_list lru)
18573eb4140fSWu Fengguang {
1858599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18593eb4140fSWu Fengguang 	struct page *page;
1860fa9add64SHugh Dickins 	int nr_pages;
18619d998b4fSMichal Hocko 	int nr_moved = 0;
18623eb4140fSWu Fengguang 
18633eb4140fSWu Fengguang 	while (!list_empty(list)) {
18643eb4140fSWu Fengguang 		page = lru_to_page(list);
1865599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18663eb4140fSWu Fengguang 
1867309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18683eb4140fSWu Fengguang 		SetPageLRU(page);
18693eb4140fSWu Fengguang 
1870fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1871599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1872925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
18733eb4140fSWu Fengguang 
18742bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18752bcf8879SHugh Dickins 			__ClearPageLRU(page);
18762bcf8879SHugh Dickins 			__ClearPageActive(page);
1877fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18782bcf8879SHugh Dickins 
18792bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1880599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1881747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18822bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1883599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18842bcf8879SHugh Dickins 			} else
18852bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18869d998b4fSMichal Hocko 		} else {
18879d998b4fSMichal Hocko 			nr_moved += nr_pages;
18883eb4140fSWu Fengguang 		}
18893eb4140fSWu Fengguang 	}
18909d5e6a9fSHugh Dickins 
18912262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
1892f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
18932262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
18942262185cSRoman Gushchin 				   nr_moved);
18952262185cSRoman Gushchin 	}
18969d998b4fSMichal Hocko 
18979d998b4fSMichal Hocko 	return nr_moved;
18983eb4140fSWu Fengguang }
18991cfb419bSKAMEZAWA Hiroyuki 
1900f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19011a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1902f16015fbSJohannes Weiner 			       struct scan_control *sc,
19039e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19041cfb419bSKAMEZAWA Hiroyuki {
190544c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1906f626012dSHugh Dickins 	unsigned long nr_scanned;
19076fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19081cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19098cab4754SWu Fengguang 	LIST_HEAD(l_active);
1910b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19111cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19121a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19139d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
19149d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
1915f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19163cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1917599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19181cfb419bSKAMEZAWA Hiroyuki 
19191da177e4SLinus Torvalds 	lru_add_drain();
1920f80c0673SMinchan Kim 
1921f80c0673SMinchan Kim 	if (!sc->may_unmap)
192261317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1923f80c0673SMinchan Kim 
1924599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1925925b7673SJohannes Weiner 
19265dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19275dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
192889b5fae5SJohannes Weiner 
1929599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1930b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19311cfb419bSKAMEZAWA Hiroyuki 
1932599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19332262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
19349d5e6a9fSHugh Dickins 
1935599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19361da177e4SLinus Torvalds 
19371da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19381da177e4SLinus Torvalds 		cond_resched();
19391da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19401da177e4SLinus Torvalds 		list_del(&page->lru);
19417e9cd484SRik van Riel 
194239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1943894bc310SLee Schermerhorn 			putback_lru_page(page);
1944894bc310SLee Schermerhorn 			continue;
1945894bc310SLee Schermerhorn 		}
1946894bc310SLee Schermerhorn 
1947cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1948cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1949cc715d99SMel Gorman 				if (page_has_private(page))
1950cc715d99SMel Gorman 					try_to_release_page(page, 0);
1951cc715d99SMel Gorman 				unlock_page(page);
1952cc715d99SMel Gorman 			}
1953cc715d99SMel Gorman 		}
1954cc715d99SMel Gorman 
1955c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1956c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19579992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19588cab4754SWu Fengguang 			/*
19598cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19608cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19618cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19628cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19638cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19648cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19658cab4754SWu Fengguang 			 * so we ignore them here.
19668cab4754SWu Fengguang 			 */
196741e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19688cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19698cab4754SWu Fengguang 				continue;
19708cab4754SWu Fengguang 			}
19718cab4754SWu Fengguang 		}
19727e9cd484SRik van Riel 
19735205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19741da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19751da177e4SLinus Torvalds 	}
19761da177e4SLinus Torvalds 
1977b555749aSAndrew Morton 	/*
19788cab4754SWu Fengguang 	 * Move pages back to the lru list.
1979b555749aSAndrew Morton 	 */
1980599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19814f98a2feSRik van Riel 	/*
19828cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19838cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19848cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19857c0db9e9SJerome Marchand 	 * get_scan_count.
1986556adecbSRik van Riel 	 */
1987b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1988556adecbSRik van Riel 
19899d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
19909d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1991599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1992599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19932bcf8879SHugh Dickins 
1994747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
19952d4894b5SMel Gorman 	free_unref_page_list(&l_hold);
19969d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
19979d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
19981da177e4SLinus Torvalds }
19991da177e4SLinus Torvalds 
200059dc76b0SRik van Riel /*
200159dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
200259dc76b0SRik van Riel  * to do too much work.
200314797e23SKOSAKI Motohiro  *
200459dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
200559dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
200659dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
200759dc76b0SRik van Riel  *
200859dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
200959dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
201059dc76b0SRik van Riel  *
20112a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
20122a2e4885SJohannes Weiner  *
201359dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
20143a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
201559dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
201659dc76b0SRik van Riel  *
201759dc76b0SRik van Riel  * total     target    max
201859dc76b0SRik van Riel  * memory    ratio     inactive
201959dc76b0SRik van Riel  * -------------------------------------
202059dc76b0SRik van Riel  *   10MB       1         5MB
202159dc76b0SRik van Riel  *  100MB       1        50MB
202259dc76b0SRik van Riel  *    1GB       3       250MB
202359dc76b0SRik van Riel  *   10GB      10       0.9GB
202459dc76b0SRik van Riel  *  100GB      31         3GB
202559dc76b0SRik van Riel  *    1TB     101        10GB
202659dc76b0SRik van Riel  *   10TB     320        32GB
202714797e23SKOSAKI Motohiro  */
2028f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
20292a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
20302a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
203114797e23SKOSAKI Motohiro {
2032fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
20332a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20342a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
20352a2e4885SJohannes Weiner 	unsigned long inactive, active;
20362a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
20372a2e4885SJohannes Weiner 	unsigned long refaults;
203859dc76b0SRik van Riel 	unsigned long gb;
203959dc76b0SRik van Riel 
204074e3f3c3SMinchan Kim 	/*
204174e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
204274e3f3c3SMinchan Kim 	 * is pointless.
204374e3f3c3SMinchan Kim 	 */
204459dc76b0SRik van Riel 	if (!file && !total_swap_pages)
204542e2e457SYaowei Bai 		return false;
204674e3f3c3SMinchan Kim 
2047fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2048fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2049f8d1a311SMel Gorman 
20502a2e4885SJohannes Weiner 	if (memcg)
2051ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
20522a2e4885SJohannes Weiner 	else
20532a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
20542a2e4885SJohannes Weiner 
20552a2e4885SJohannes Weiner 	/*
20562a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
20572a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
20582a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
20592a2e4885SJohannes Weiner 	 */
20602a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
20612a2e4885SJohannes Weiner 		inactive_ratio = 0;
20622a2e4885SJohannes Weiner 	} else {
206359dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
206459dc76b0SRik van Riel 		if (gb)
206559dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2066b39415b2SRik van Riel 		else
206759dc76b0SRik van Riel 			inactive_ratio = 1;
20682a2e4885SJohannes Weiner 	}
206959dc76b0SRik van Riel 
20702a2e4885SJohannes Weiner 	if (actual_reclaim)
20712a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2072fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2073fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2074fd538803SMichal Hocko 			inactive_ratio, file);
2075fd538803SMichal Hocko 
207659dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2077b39415b2SRik van Riel }
2078b39415b2SRik van Riel 
20794f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
20802a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
20812a2e4885SJohannes Weiner 				 struct scan_control *sc)
2082b69408e8SChristoph Lameter {
2083b39415b2SRik van Riel 	if (is_active_lru(lru)) {
20842a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
20852a2e4885SJohannes Weiner 					 memcg, sc, true))
20861a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2087556adecbSRik van Riel 		return 0;
2088556adecbSRik van Riel 	}
2089556adecbSRik van Riel 
20901a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2091b69408e8SChristoph Lameter }
2092b69408e8SChristoph Lameter 
20939a265114SJohannes Weiner enum scan_balance {
20949a265114SJohannes Weiner 	SCAN_EQUAL,
20959a265114SJohannes Weiner 	SCAN_FRACT,
20969a265114SJohannes Weiner 	SCAN_ANON,
20979a265114SJohannes Weiner 	SCAN_FILE,
20989a265114SJohannes Weiner };
20999a265114SJohannes Weiner 
21001da177e4SLinus Torvalds /*
21014f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
21024f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
21034f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
21044f98a2feSRik van Riel  * onto the active list instead of evict.
21054f98a2feSRik van Riel  *
2106be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2107be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
21084f98a2feSRik van Riel  */
210933377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
21106b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
21116b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
21124f98a2feSRik van Riel {
211333377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
211490126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
21159a265114SJohannes Weiner 	u64 fraction[2];
21169a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2117599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21189a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
21199a265114SJohannes Weiner 	enum scan_balance scan_balance;
21200bf1457fSJohannes Weiner 	unsigned long anon, file;
21219a265114SJohannes Weiner 	unsigned long ap, fp;
21229a265114SJohannes Weiner 	enum lru_list lru;
212376a33fc3SShaohua Li 
212476a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2125d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21269a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
212776a33fc3SShaohua Li 		goto out;
212876a33fc3SShaohua Li 	}
21294f98a2feSRik van Riel 
213010316b31SJohannes Weiner 	/*
213110316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
213210316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
213310316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
213410316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
213510316b31SJohannes Weiner 	 * too expensive.
213610316b31SJohannes Weiner 	 */
213702695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21389a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
213910316b31SJohannes Weiner 		goto out;
214010316b31SJohannes Weiner 	}
214110316b31SJohannes Weiner 
214210316b31SJohannes Weiner 	/*
214310316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
214410316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
214510316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
214610316b31SJohannes Weiner 	 */
214702695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21489a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
214910316b31SJohannes Weiner 		goto out;
215010316b31SJohannes Weiner 	}
215110316b31SJohannes Weiner 
215211d16c25SJohannes Weiner 	/*
215362376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
215462376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
215562376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
215662376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
215762376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
215862376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
215962376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
216062376251SJohannes Weiner 	 */
216162376251SJohannes Weiner 	if (global_reclaim(sc)) {
2162599d0c95SMel Gorman 		unsigned long pgdatfile;
2163599d0c95SMel Gorman 		unsigned long pgdatfree;
2164599d0c95SMel Gorman 		int z;
2165599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
216662376251SJohannes Weiner 
2167599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2168599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2169599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21702ab051e1SJerome Marchand 
2171599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2172599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
21736aa303deSMel Gorman 			if (!managed_zone(zone))
2174599d0c95SMel Gorman 				continue;
2175599d0c95SMel Gorman 
2176599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2177599d0c95SMel Gorman 		}
2178599d0c95SMel Gorman 
2179599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
218006226226SDavid Rientjes 			/*
218106226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
218206226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
218306226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
218406226226SDavid Rientjes 			 */
218506226226SDavid Rientjes 			if (!inactive_list_is_low(lruvec, false, memcg, sc, false) &&
218606226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
218706226226SDavid Rientjes 					>> sc->priority) {
218862376251SJohannes Weiner 				scan_balance = SCAN_ANON;
218962376251SJohannes Weiner 				goto out;
219062376251SJohannes Weiner 			}
219162376251SJohannes Weiner 		}
219206226226SDavid Rientjes 	}
219362376251SJohannes Weiner 
219462376251SJohannes Weiner 	/*
2195316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2196316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2197316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2198316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2199316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2200316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2201316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2202e9868505SRik van Riel 	 */
22032a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
220471ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
22059a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2206e9868505SRik van Riel 		goto out;
22074f98a2feSRik van Riel 	}
22084f98a2feSRik van Riel 
22099a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22109a265114SJohannes Weiner 
22114f98a2feSRik van Riel 	/*
221258c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
221358c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
221458c37f6eSKOSAKI Motohiro 	 */
221502695175SJohannes Weiner 	anon_prio = swappiness;
221675b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
221758c37f6eSKOSAKI Motohiro 
221858c37f6eSKOSAKI Motohiro 	/*
22194f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22204f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22214f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22224f98a2feSRik van Riel 	 *
22234f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22244f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22254f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22264f98a2feSRik van Riel 	 *
22274f98a2feSRik van Riel 	 * anon in [0], file in [1]
22284f98a2feSRik van Riel 	 */
22292ab051e1SJerome Marchand 
2230fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2231fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2232fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2233fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
22342ab051e1SJerome Marchand 
2235599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
223658c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22376e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22386e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22394f98a2feSRik van Riel 	}
22404f98a2feSRik van Riel 
22416e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22426e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22436e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22444f98a2feSRik van Riel 	}
22454f98a2feSRik van Riel 
22464f98a2feSRik van Riel 	/*
224700d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
224800d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
224900d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22504f98a2feSRik van Riel 	 */
2251fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22526e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22534f98a2feSRik van Riel 
2254fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22556e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2256599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22574f98a2feSRik van Riel 
225876a33fc3SShaohua Li 	fraction[0] = ap;
225976a33fc3SShaohua Li 	fraction[1] = fp;
226076a33fc3SShaohua Li 	denominator = ap + fp + 1;
226176a33fc3SShaohua Li out:
22626b4f7799SJohannes Weiner 	*lru_pages = 0;
22634111304dSHugh Dickins 	for_each_evictable_lru(lru) {
22644111304dSHugh Dickins 		int file = is_file_lru(lru);
2265d778df51SJohannes Weiner 		unsigned long size;
226676a33fc3SShaohua Li 		unsigned long scan;
226776a33fc3SShaohua Li 
226871ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2269d778df51SJohannes Weiner 		scan = size >> sc->priority;
2270688035f7SJohannes Weiner 		/*
2271688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2272688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2273688035f7SJohannes Weiner 		 */
2274688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2275d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
22769a265114SJohannes Weiner 
22779a265114SJohannes Weiner 		switch (scan_balance) {
22789a265114SJohannes Weiner 		case SCAN_EQUAL:
22799a265114SJohannes Weiner 			/* Scan lists relative to size */
22809a265114SJohannes Weiner 			break;
22819a265114SJohannes Weiner 		case SCAN_FRACT:
22829a265114SJohannes Weiner 			/*
22839a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
22849a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
22859a265114SJohannes Weiner 			 */
22866f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
22876f04f48dSSuleiman Souhlal 					 denominator);
22889a265114SJohannes Weiner 			break;
22899a265114SJohannes Weiner 		case SCAN_FILE:
22909a265114SJohannes Weiner 		case SCAN_ANON:
22919a265114SJohannes Weiner 			/* Scan one type exclusively */
22926b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
22936b4f7799SJohannes Weiner 				size = 0;
22949a265114SJohannes Weiner 				scan = 0;
22956b4f7799SJohannes Weiner 			}
22969a265114SJohannes Weiner 			break;
22979a265114SJohannes Weiner 		default:
22989a265114SJohannes Weiner 			/* Look ma, no brain */
22999a265114SJohannes Weiner 			BUG();
23009a265114SJohannes Weiner 		}
23016b4f7799SJohannes Weiner 
23026b4f7799SJohannes Weiner 		*lru_pages += size;
23034111304dSHugh Dickins 		nr[lru] = scan;
230476a33fc3SShaohua Li 	}
23056e08a369SWu Fengguang }
23064f98a2feSRik van Riel 
23079b4f98cdSJohannes Weiner /*
2308a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23099b4f98cdSJohannes Weiner  */
2310a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23116b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23129b4f98cdSJohannes Weiner {
2313ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23149b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2315e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23169b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23179b4f98cdSJohannes Weiner 	enum lru_list lru;
23189b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23199b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23209b4f98cdSJohannes Weiner 	struct blk_plug plug;
23211a501907SMel Gorman 	bool scan_adjusted;
23229b4f98cdSJohannes Weiner 
232333377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23249b4f98cdSJohannes Weiner 
2325e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2326e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2327e82e0561SMel Gorman 
23281a501907SMel Gorman 	/*
23291a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23301a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23311a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23321a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23331a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23341a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23351a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23361a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23371a501907SMel Gorman 	 * dropped to zero at the first pass.
23381a501907SMel Gorman 	 */
23391a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23401a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23411a501907SMel Gorman 
23429b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23439b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23449b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2345e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2346e82e0561SMel Gorman 		unsigned long nr_scanned;
2347e82e0561SMel Gorman 
23489b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23499b4f98cdSJohannes Weiner 			if (nr[lru]) {
23509b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23519b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23529b4f98cdSJohannes Weiner 
23539b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23542a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
23559b4f98cdSJohannes Weiner 			}
23569b4f98cdSJohannes Weiner 		}
2357e82e0561SMel Gorman 
2358bd041733SMichal Hocko 		cond_resched();
2359bd041733SMichal Hocko 
2360e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2361e82e0561SMel Gorman 			continue;
2362e82e0561SMel Gorman 
23639b4f98cdSJohannes Weiner 		/*
2364e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23651a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2366e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2367e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2368e82e0561SMel Gorman 		 * proportional to the original scan target.
2369e82e0561SMel Gorman 		 */
2370e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2371e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2372e82e0561SMel Gorman 
23731a501907SMel Gorman 		/*
23741a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23751a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23761a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23771a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23781a501907SMel Gorman 		 */
23791a501907SMel Gorman 		if (!nr_file || !nr_anon)
23801a501907SMel Gorman 			break;
23811a501907SMel Gorman 
2382e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2383e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2384e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2385e82e0561SMel Gorman 			lru = LRU_BASE;
2386e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2387e82e0561SMel Gorman 		} else {
2388e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2389e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2390e82e0561SMel Gorman 			lru = LRU_FILE;
2391e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2392e82e0561SMel Gorman 		}
2393e82e0561SMel Gorman 
2394e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2395e82e0561SMel Gorman 		nr[lru] = 0;
2396e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2397e82e0561SMel Gorman 
2398e82e0561SMel Gorman 		/*
2399e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2400e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2401e82e0561SMel Gorman 		 */
2402e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2403e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2404e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2405e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2406e82e0561SMel Gorman 
2407e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2408e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2409e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2410e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2411e82e0561SMel Gorman 
2412e82e0561SMel Gorman 		scan_adjusted = true;
24139b4f98cdSJohannes Weiner 	}
24149b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24159b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24169b4f98cdSJohannes Weiner 
24179b4f98cdSJohannes Weiner 	/*
24189b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24199b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24209b4f98cdSJohannes Weiner 	 */
24212a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
24229b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24239b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24249b4f98cdSJohannes Weiner }
24259b4f98cdSJohannes Weiner 
242623b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24279e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
242823b9da55SMel Gorman {
2429d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
243023b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24319e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
243223b9da55SMel Gorman 		return true;
243323b9da55SMel Gorman 
243423b9da55SMel Gorman 	return false;
243523b9da55SMel Gorman }
243623b9da55SMel Gorman 
24374f98a2feSRik van Riel /*
243823b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
243923b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
244023b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
244123b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
244223b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24433e7d3449SMel Gorman  */
2444a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24453e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24463e7d3449SMel Gorman 					unsigned long nr_scanned,
24473e7d3449SMel Gorman 					struct scan_control *sc)
24483e7d3449SMel Gorman {
24493e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24503e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2451a9dd0a83SMel Gorman 	int z;
24523e7d3449SMel Gorman 
24533e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24549e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24553e7d3449SMel Gorman 		return false;
24563e7d3449SMel Gorman 
24572876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2458dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
24593e7d3449SMel Gorman 		/*
2460dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
24612876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24622876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2463dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
24643e7d3449SMel Gorman 		 */
24653e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24663e7d3449SMel Gorman 			return false;
24672876592fSMel Gorman 	} else {
24682876592fSMel Gorman 		/*
2469dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
24702876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24712876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24722876592fSMel Gorman 		 * pages that were scanned. This will return to the
24732876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24742876592fSMel Gorman 		 * the resulting allocation attempt fails
24752876592fSMel Gorman 		 */
24762876592fSMel Gorman 		if (!nr_reclaimed)
24772876592fSMel Gorman 			return false;
24782876592fSMel Gorman 	}
24793e7d3449SMel Gorman 
24803e7d3449SMel Gorman 	/*
24813e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24823e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24833e7d3449SMel Gorman 	 */
24849861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2485a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2486ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2487a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
24883e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24893e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24903e7d3449SMel Gorman 		return true;
24913e7d3449SMel Gorman 
24923e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2493a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2494a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
24956aa303deSMel Gorman 		if (!managed_zone(zone))
2496a9dd0a83SMel Gorman 			continue;
2497a9dd0a83SMel Gorman 
2498a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2499cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25003e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25013e7d3449SMel Gorman 			return false;
25023e7d3449SMel Gorman 		default:
2503a9dd0a83SMel Gorman 			/* check next zone */
2504a9dd0a83SMel Gorman 			;
25053e7d3449SMel Gorman 		}
25063e7d3449SMel Gorman 	}
2507a9dd0a83SMel Gorman 	return true;
2508a9dd0a83SMel Gorman }
25093e7d3449SMel Gorman 
2510970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2511f16015fbSJohannes Weiner {
2512cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25139b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25142344d7e4SJohannes Weiner 	bool reclaimable = false;
25159b4f98cdSJohannes Weiner 
25169b4f98cdSJohannes Weiner 	do {
25175660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25185660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2519ef8f2327SMel Gorman 			.pgdat = pgdat,
25209e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25215660048cSJohannes Weiner 		};
2522a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2523694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25245660048cSJohannes Weiner 
25259b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25269b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25279b4f98cdSJohannes Weiner 
2528694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2529694fbc0fSAndrew Morton 		do {
25306b4f7799SJohannes Weiner 			unsigned long lru_pages;
25318e8ae645SJohannes Weiner 			unsigned long reclaimed;
2532cb731d6cSVladimir Davydov 			unsigned long scanned;
25339b4f98cdSJohannes Weiner 
2534241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2535d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2536d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2537241994edSJohannes Weiner 					continue;
2538d6622f63SYisheng Xie 				}
253931176c78SJohannes Weiner 				mem_cgroup_event(memcg, MEMCG_LOW);
2540241994edSJohannes Weiner 			}
2541241994edSJohannes Weiner 
25428e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2543cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2544a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2545a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2546f9be23d6SKonstantin Khlebnikov 
2547b5afba29SVladimir Davydov 			if (memcg)
2548a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
25499092c71bSJosef Bacik 					    memcg, sc->priority);
2550cb731d6cSVladimir Davydov 
25518e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25528e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25538e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25548e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25558e8ae645SJohannes Weiner 
25565660048cSJohannes Weiner 			/*
2557a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2558a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2559a9dd0a83SMel Gorman 			 * node.
2560a394cb8eSMichal Hocko 			 *
2561a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2562a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2563a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2564a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25655660048cSJohannes Weiner 			 */
2566a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2567a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25685660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25695660048cSJohannes Weiner 				break;
25705660048cSJohannes Weiner 			}
2571241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
257270ddf637SAnton Vorontsov 
2573b2e18757SMel Gorman 		if (global_reclaim(sc))
2574a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25759092c71bSJosef Bacik 				    sc->priority);
25766b4f7799SJohannes Weiner 
25776b4f7799SJohannes Weiner 		if (reclaim_state) {
2578cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25796b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25806b4f7799SJohannes Weiner 		}
25816b4f7799SJohannes Weiner 
25828e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25838e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
258470ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
258570ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
258670ddf637SAnton Vorontsov 
25872344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
25882344d7e4SJohannes Weiner 			reclaimable = true;
25892344d7e4SJohannes Weiner 
2590a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
25919b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
25922344d7e4SJohannes Weiner 
2593c73322d0SJohannes Weiner 	/*
2594c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2595c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2596c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2597c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2598c73322d0SJohannes Weiner 	 */
2599c73322d0SJohannes Weiner 	if (reclaimable)
2600c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2601c73322d0SJohannes Weiner 
26022344d7e4SJohannes Weiner 	return reclaimable;
2603f16015fbSJohannes Weiner }
2604f16015fbSJohannes Weiner 
260553853e2dSVlastimil Babka /*
2606fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2607fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2608fdd4c614SVlastimil Babka  * should reclaim first.
260953853e2dSVlastimil Babka  */
26104f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2611fe4b1b24SMel Gorman {
261231483b6aSMel Gorman 	unsigned long watermark;
2613fdd4c614SVlastimil Babka 	enum compact_result suitable;
2614fe4b1b24SMel Gorman 
2615fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2616fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2617fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2618fdd4c614SVlastimil Babka 		return true;
2619fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2620fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2621fe4b1b24SMel Gorman 		return false;
2622fe4b1b24SMel Gorman 
2623fdd4c614SVlastimil Babka 	/*
2624fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2625fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2626fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2627fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2628fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2629fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2630fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2631fdd4c614SVlastimil Babka 	 */
2632fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2633fdd4c614SVlastimil Babka 
2634fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2635fe4b1b24SMel Gorman }
2636fe4b1b24SMel Gorman 
26371da177e4SLinus Torvalds /*
26381da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
26391da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
26401da177e4SLinus Torvalds  * request.
26411da177e4SLinus Torvalds  *
26421da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
26431da177e4SLinus Torvalds  * scan then give up on it.
26441da177e4SLinus Torvalds  */
26450a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
26461da177e4SLinus Torvalds {
2647dd1a239fSMel Gorman 	struct zoneref *z;
264854a6eb5cSMel Gorman 	struct zone *zone;
26490608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
26500608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2651619d0d76SWeijie Yang 	gfp_t orig_mask;
265279dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
26531cfb419bSKAMEZAWA Hiroyuki 
2654cc715d99SMel Gorman 	/*
2655cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2656cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2657cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2658cc715d99SMel Gorman 	 */
2659619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2660b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2661cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
26624f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2663b2e18757SMel Gorman 	}
2664cc715d99SMel Gorman 
2665d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2666b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2667b2e18757SMel Gorman 		/*
26681cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
26691cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
26701cfb419bSKAMEZAWA Hiroyuki 		 */
267189b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2672344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2673344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
26741da177e4SLinus Torvalds 				continue;
267565ec02cbSVladimir Davydov 
2676e0887c19SRik van Riel 			/*
2677e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2678e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2679e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2680e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2681e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2682c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2683c7cfa37bSCopot Alexandru 			 * page allocations.
2684e0887c19SRik van Riel 			 */
26850b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
26860b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
26874f588331SMel Gorman 			    compaction_ready(zone, sc)) {
26880b06496aSJohannes Weiner 				sc->compaction_ready = true;
2689e0887c19SRik van Riel 				continue;
2690e0887c19SRik van Riel 			}
26910b06496aSJohannes Weiner 
26920608f43dSAndrew Morton 			/*
269379dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
269479dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
269579dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
269679dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
269779dafcdcSMel Gorman 			 */
269879dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
269979dafcdcSMel Gorman 				continue;
270079dafcdcSMel Gorman 
270179dafcdcSMel Gorman 			/*
27020608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27030608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27040608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27050608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27060608f43dSAndrew Morton 			 */
27070608f43dSAndrew Morton 			nr_soft_scanned = 0;
2708ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27090608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27100608f43dSAndrew Morton 						&nr_soft_scanned);
27110608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27120608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2713ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2714ac34a1a3SKAMEZAWA Hiroyuki 		}
2715d149e3b2SYing Han 
271679dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
271779dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
271879dafcdcSMel Gorman 			continue;
271979dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2720970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27211da177e4SLinus Torvalds 	}
2722e0c23279SMel Gorman 
272365ec02cbSVladimir Davydov 	/*
2724619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2725619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2726619d0d76SWeijie Yang 	 */
2727619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27281da177e4SLinus Torvalds }
27291da177e4SLinus Torvalds 
27302a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
27312a2e4885SJohannes Weiner {
27322a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
27332a2e4885SJohannes Weiner 
27342a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
27352a2e4885SJohannes Weiner 	do {
27362a2e4885SJohannes Weiner 		unsigned long refaults;
27372a2e4885SJohannes Weiner 		struct lruvec *lruvec;
27382a2e4885SJohannes Weiner 
27392a2e4885SJohannes Weiner 		if (memcg)
2740ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
27412a2e4885SJohannes Weiner 		else
27422a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
27432a2e4885SJohannes Weiner 
27442a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
27452a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
27462a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
27472a2e4885SJohannes Weiner }
27482a2e4885SJohannes Weiner 
27491da177e4SLinus Torvalds /*
27501da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
27511da177e4SLinus Torvalds  *
27521da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
27531da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
27541da177e4SLinus Torvalds  *
27551da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
27561da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
27575b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
27585b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
27595b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
27605b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2761a41f24eaSNishanth Aravamudan  *
2762a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2763a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
27641da177e4SLinus Torvalds  */
2765dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
27663115cd91SVladimir Davydov 					  struct scan_control *sc)
27671da177e4SLinus Torvalds {
2768241994edSJohannes Weiner 	int initial_priority = sc->priority;
27692a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
27702a2e4885SJohannes Weiner 	struct zoneref *z;
27712a2e4885SJohannes Weiner 	struct zone *zone;
2772241994edSJohannes Weiner retry:
2773873b4771SKeika Kobayashi 	delayacct_freepages_start();
2774873b4771SKeika Kobayashi 
277589b5fae5SJohannes Weiner 	if (global_reclaim(sc))
27767cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
27771da177e4SLinus Torvalds 
27789e3b2f8cSKonstantin Khlebnikov 	do {
277970ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
278070ddf637SAnton Vorontsov 				sc->priority);
278166e1707bSBalbir Singh 		sc->nr_scanned = 0;
27820a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2783e0c23279SMel Gorman 
2784bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
27850b06496aSJohannes Weiner 			break;
27860b06496aSJohannes Weiner 
27870b06496aSJohannes Weiner 		if (sc->compaction_ready)
27880b06496aSJohannes Weiner 			break;
27891da177e4SLinus Torvalds 
27901da177e4SLinus Torvalds 		/*
27910e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
27920e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
27930e50ce3bSMinchan Kim 		 */
27940e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
27950e50ce3bSMinchan Kim 			sc->may_writepage = 1;
27960b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2797bb21c7ceSKOSAKI Motohiro 
27982a2e4885SJohannes Weiner 	last_pgdat = NULL;
27992a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
28002a2e4885SJohannes Weiner 					sc->nodemask) {
28012a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
28022a2e4885SJohannes Weiner 			continue;
28032a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
28042a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
28052a2e4885SJohannes Weiner 	}
28062a2e4885SJohannes Weiner 
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. */
2817d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
2818241994edSJohannes Weiner 		sc->priority = initial_priority;
2819d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
2820d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
2821241994edSJohannes Weiner 		goto retry;
2822241994edSJohannes Weiner 	}
2823241994edSJohannes Weiner 
2824bb21c7ceSKOSAKI Motohiro 	return 0;
28251da177e4SLinus Torvalds }
28261da177e4SLinus Torvalds 
2827c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
28285515061dSMel Gorman {
28295515061dSMel Gorman 	struct zone *zone;
28305515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
28315515061dSMel Gorman 	unsigned long free_pages = 0;
28325515061dSMel Gorman 	int i;
28335515061dSMel Gorman 	bool wmark_ok;
28345515061dSMel Gorman 
2835c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
2836c73322d0SJohannes Weiner 		return true;
2837c73322d0SJohannes Weiner 
28385515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
28395515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2840d450abd8SJohannes Weiner 		if (!managed_zone(zone))
2841d450abd8SJohannes Weiner 			continue;
2842d450abd8SJohannes Weiner 
2843d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
2844675becceSMel Gorman 			continue;
2845675becceSMel Gorman 
28465515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
28475515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
28485515061dSMel Gorman 	}
28495515061dSMel Gorman 
2850675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2851675becceSMel Gorman 	if (!pfmemalloc_reserve)
2852675becceSMel Gorman 		return true;
2853675becceSMel Gorman 
28545515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
28555515061dSMel Gorman 
28565515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
28575515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
285838087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
28595515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
28605515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
28615515061dSMel Gorman 	}
28625515061dSMel Gorman 
28635515061dSMel Gorman 	return wmark_ok;
28645515061dSMel Gorman }
28655515061dSMel Gorman 
28665515061dSMel Gorman /*
28675515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
28685515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
28695515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
287050694c28SMel Gorman  * when the low watermark is reached.
287150694c28SMel Gorman  *
287250694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
287350694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
28745515061dSMel Gorman  */
287550694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
28765515061dSMel Gorman 					nodemask_t *nodemask)
28775515061dSMel Gorman {
2878675becceSMel Gorman 	struct zoneref *z;
28795515061dSMel Gorman 	struct zone *zone;
2880675becceSMel Gorman 	pg_data_t *pgdat = NULL;
28815515061dSMel Gorman 
28825515061dSMel Gorman 	/*
28835515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
28845515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
28855515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
28865515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
28875515061dSMel Gorman 	 * processes to block on log_wait_commit().
28885515061dSMel Gorman 	 */
28895515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
289050694c28SMel Gorman 		goto out;
289150694c28SMel Gorman 
289250694c28SMel Gorman 	/*
289350694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
289450694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
289550694c28SMel Gorman 	 */
289650694c28SMel Gorman 	if (fatal_signal_pending(current))
289750694c28SMel Gorman 		goto out;
28985515061dSMel Gorman 
2899675becceSMel Gorman 	/*
2900675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2901675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2902675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2903675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2904675becceSMel Gorman 	 *
2905675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2906675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2907675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2908675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2909675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2910675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2911675becceSMel Gorman 	 * should make reasonable progress.
2912675becceSMel Gorman 	 */
2913675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
291417636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2915675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2916675becceSMel Gorman 			continue;
2917675becceSMel Gorman 
2918675becceSMel Gorman 		/* Throttle based on the first usable node */
29195515061dSMel Gorman 		pgdat = zone->zone_pgdat;
2920c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
292150694c28SMel Gorman 			goto out;
2922675becceSMel Gorman 		break;
2923675becceSMel Gorman 	}
2924675becceSMel Gorman 
2925675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2926675becceSMel Gorman 	if (!pgdat)
2927675becceSMel Gorman 		goto out;
29285515061dSMel Gorman 
292968243e76SMel Gorman 	/* Account for the throttling */
293068243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
293168243e76SMel Gorman 
29325515061dSMel Gorman 	/*
29335515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
29345515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
29355515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
29365515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
29375515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
29385515061dSMel Gorman 	 * second before continuing.
29395515061dSMel Gorman 	 */
29405515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
29415515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2942c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
294350694c28SMel Gorman 
294450694c28SMel Gorman 		goto check_pending;
29455515061dSMel Gorman 	}
29465515061dSMel Gorman 
29475515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
29485515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2949c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
295050694c28SMel Gorman 
295150694c28SMel Gorman check_pending:
295250694c28SMel Gorman 	if (fatal_signal_pending(current))
295350694c28SMel Gorman 		return true;
295450694c28SMel Gorman 
295550694c28SMel Gorman out:
295650694c28SMel Gorman 	return false;
29575515061dSMel Gorman }
29585515061dSMel Gorman 
2959dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2960327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
296166e1707bSBalbir Singh {
296233906bc5SMel Gorman 	unsigned long nr_reclaimed;
296366e1707bSBalbir Singh 	struct scan_control sc = {
296422fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
2965f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
2966b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
2967ee814fe2SJohannes Weiner 		.order = order,
2968ee814fe2SJohannes Weiner 		.nodemask = nodemask,
2969ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
2970ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
2971a6dc60f8SJohannes Weiner 		.may_unmap = 1,
29722e2e4259SKOSAKI Motohiro 		.may_swap = 1,
297366e1707bSBalbir Singh 	};
297466e1707bSBalbir Singh 
29755515061dSMel Gorman 	/*
297650694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
297750694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
297850694c28SMel Gorman 	 * point.
29795515061dSMel Gorman 	 */
2980f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
29815515061dSMel Gorman 		return 1;
29825515061dSMel Gorman 
298333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
298433906bc5SMel Gorman 				sc.may_writepage,
2985f2f43e56SNick Desaulniers 				sc.gfp_mask,
2986e5146b12SMel Gorman 				sc.reclaim_idx);
298733906bc5SMel Gorman 
29883115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
298933906bc5SMel Gorman 
299033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
299133906bc5SMel Gorman 
299233906bc5SMel Gorman 	return nr_reclaimed;
299366e1707bSBalbir Singh }
299466e1707bSBalbir Singh 
2995c255a458SAndrew Morton #ifdef CONFIG_MEMCG
299666e1707bSBalbir Singh 
2997a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
29984e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
2999ef8f2327SMel Gorman 						pg_data_t *pgdat,
30000ae5e89cSYing Han 						unsigned long *nr_scanned)
30014e416953SBalbir Singh {
30024e416953SBalbir Singh 	struct scan_control sc = {
3003b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3004ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
30054e416953SBalbir Singh 		.may_writepage = !laptop_mode,
30064e416953SBalbir Singh 		.may_unmap = 1,
3007b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
30084e416953SBalbir Singh 		.may_swap = !noswap,
30094e416953SBalbir Singh 	};
30106b4f7799SJohannes Weiner 	unsigned long lru_pages;
30110ae5e89cSYing Han 
30124e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
30134e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3014bdce6d9eSKOSAKI Motohiro 
30159e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3016bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3017e5146b12SMel Gorman 						      sc.gfp_mask,
3018e5146b12SMel Gorman 						      sc.reclaim_idx);
3019bdce6d9eSKOSAKI Motohiro 
30204e416953SBalbir Singh 	/*
30214e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
30224e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3023a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30244e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
30254e416953SBalbir Singh 	 * the priority and make it zero.
30264e416953SBalbir Singh 	 */
3027ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3028bdce6d9eSKOSAKI Motohiro 
3029bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3030bdce6d9eSKOSAKI Motohiro 
30310ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
30324e416953SBalbir Singh 	return sc.nr_reclaimed;
30334e416953SBalbir Singh }
30344e416953SBalbir Singh 
303572835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3036b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
30378c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3038b70a2a21SJohannes Weiner 					   bool may_swap)
303966e1707bSBalbir Singh {
30404e416953SBalbir Singh 	struct zonelist *zonelist;
3041bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3042889976dbSYing Han 	int nid;
3043499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
304466e1707bSBalbir Singh 	struct scan_control sc = {
3045b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
30467dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3047ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3048b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3049ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3050ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
305166e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3052a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3053b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3054a09ed5e0SYing Han 	};
305566e1707bSBalbir Singh 
3056889976dbSYing Han 	/*
3057889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3058889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3059889976dbSYing Han 	 * scan does not need to be the current node.
3060889976dbSYing Han 	 */
306172835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3062889976dbSYing Han 
3063c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3064bdce6d9eSKOSAKI Motohiro 
3065bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3066bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3067e5146b12SMel Gorman 					    sc.gfp_mask,
3068e5146b12SMel Gorman 					    sc.reclaim_idx);
3069bdce6d9eSKOSAKI Motohiro 
3070499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
30713115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3072499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3073bdce6d9eSKOSAKI Motohiro 
3074bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3075bdce6d9eSKOSAKI Motohiro 
3076bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
307766e1707bSBalbir Singh }
307866e1707bSBalbir Singh #endif
307966e1707bSBalbir Singh 
30801d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3081ef8f2327SMel Gorman 				struct scan_control *sc)
3082f16015fbSJohannes Weiner {
3083b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3084b95a2f2dSJohannes Weiner 
3085b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3086b95a2f2dSJohannes Weiner 		return;
3087b95a2f2dSJohannes Weiner 
3088b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3089b95a2f2dSJohannes Weiner 	do {
3090ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3091f16015fbSJohannes Weiner 
30922a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
30931a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
30949e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3095b95a2f2dSJohannes Weiner 
3096b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3097b95a2f2dSJohannes Weiner 	} while (memcg);
3098f16015fbSJohannes Weiner }
3099f16015fbSJohannes Weiner 
3100e716f2ebSMel Gorman /*
3101e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3102e716f2ebSMel Gorman  * and classzone_idx
3103e716f2ebSMel Gorman  */
3104e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
310560cefed4SJohannes Weiner {
3106e716f2ebSMel Gorman 	int i;
3107e716f2ebSMel Gorman 	unsigned long mark = -1;
3108e716f2ebSMel Gorman 	struct zone *zone;
310960cefed4SJohannes Weiner 
3110e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3111e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
31126256c6b4SMel Gorman 
3113e716f2ebSMel Gorman 		if (!managed_zone(zone))
3114e716f2ebSMel Gorman 			continue;
3115e716f2ebSMel Gorman 
3116e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3117e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
31186256c6b4SMel Gorman 			return true;
311960cefed4SJohannes Weiner 	}
312060cefed4SJohannes Weiner 
3121e716f2ebSMel Gorman 	/*
3122e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3123e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3124e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3125e716f2ebSMel Gorman 	 */
3126e716f2ebSMel Gorman 	if (mark == -1)
3127e716f2ebSMel Gorman 		return true;
3128e716f2ebSMel Gorman 
3129e716f2ebSMel Gorman 	return false;
3130e716f2ebSMel Gorman }
3131e716f2ebSMel Gorman 
3132631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3133631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3134631b6e08SMel Gorman {
3135631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3136631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3137631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3138631b6e08SMel Gorman }
3139631b6e08SMel Gorman 
31401741c877SMel Gorman /*
31415515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
31425515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
31435515061dSMel Gorman  *
31445515061dSMel Gorman  * Returns true if kswapd is ready to sleep
31455515061dSMel Gorman  */
3146d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3147f50de2d3SMel Gorman {
31485515061dSMel Gorman 	/*
31499e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3150c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
31519e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
31529e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
31539e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
31549e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
31559e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
31569e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
31579e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
31589e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
31599e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
31605515061dSMel Gorman 	 */
31619e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
31629e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3163f50de2d3SMel Gorman 
3164c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3165c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3166c73322d0SJohannes Weiner 		return true;
3167c73322d0SJohannes Weiner 
3168e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3169631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3170333b0a45SShantanu Goel 		return true;
31711d82de61SMel Gorman 	}
31721d82de61SMel Gorman 
3173333b0a45SShantanu Goel 	return false;
3174f50de2d3SMel Gorman }
3175f50de2d3SMel Gorman 
31761da177e4SLinus Torvalds /*
31771d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
31781d82de61SMel Gorman  * zone that is currently unbalanced.
3179b8e83b94SMel Gorman  *
3180b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3181283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3182283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
318375485363SMel Gorman  */
31841d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3185accf6242SVlastimil Babka 			       struct scan_control *sc)
318675485363SMel Gorman {
31871d82de61SMel Gorman 	struct zone *zone;
31881d82de61SMel Gorman 	int z;
318975485363SMel Gorman 
31901d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
31911d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3192970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
31931d82de61SMel Gorman 		zone = pgdat->node_zones + z;
31946aa303deSMel Gorman 		if (!managed_zone(zone))
31951d82de61SMel Gorman 			continue;
31967c954f6dSMel Gorman 
31971d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
31987c954f6dSMel Gorman 	}
31997c954f6dSMel Gorman 
32001d82de61SMel Gorman 	/*
32011d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
32021d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
32031d82de61SMel Gorman 	 */
3204970a39a3SMel Gorman 	shrink_node(pgdat, sc);
32051d82de61SMel Gorman 
32061d82de61SMel Gorman 	/*
32071d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
32081d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
32091d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
32101d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
32111d82de61SMel Gorman 	 * can direct reclaim/compact.
32121d82de61SMel Gorman 	 */
32139861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
32141d82de61SMel Gorman 		sc->order = 0;
32151d82de61SMel Gorman 
3216b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
321775485363SMel Gorman }
321875485363SMel Gorman 
321975485363SMel Gorman /*
32201d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
32211d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
32221d82de61SMel Gorman  * balanced.
32231da177e4SLinus Torvalds  *
32241d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
32251da177e4SLinus Torvalds  *
32261da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
322741858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
32281d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
32291d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
32301d82de61SMel Gorman  * balanced.
32311da177e4SLinus Torvalds  */
3232accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
32331da177e4SLinus Torvalds {
32341da177e4SLinus Torvalds 	int i;
32350608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
32360608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
32371d82de61SMel Gorman 	struct zone *zone;
3238179e9639SAndrew Morton 	struct scan_control sc = {
3239179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3240ee814fe2SJohannes Weiner 		.order = order,
3241b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3242ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3243a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32442e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3245179e9639SAndrew Morton 	};
3246f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
32471da177e4SLinus Torvalds 
32489e3b2f8cSKonstantin Khlebnikov 	do {
3249c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3250b8e83b94SMel Gorman 		bool raise_priority = true;
3251b8e83b94SMel Gorman 
325284c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
32531da177e4SLinus Torvalds 
325486c79f6bSMel Gorman 		/*
325584c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
325684c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
325784c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
325884c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
325984c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
326084c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
326184c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
326284c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
326386c79f6bSMel Gorman 		 */
326486c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
326586c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
326686c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
32676aa303deSMel Gorman 				if (!managed_zone(zone))
326886c79f6bSMel Gorman 					continue;
326986c79f6bSMel Gorman 
3270970a39a3SMel Gorman 				sc.reclaim_idx = i;
327186c79f6bSMel Gorman 				break;
327286c79f6bSMel Gorman 			}
327386c79f6bSMel Gorman 		}
327486c79f6bSMel Gorman 
327586c79f6bSMel Gorman 		/*
3276e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3277e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3278e716f2ebSMel Gorman 		 * have adjusted it.
327986c79f6bSMel Gorman 		 */
3280e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
32811da177e4SLinus Torvalds 			goto out;
3282e1dbeda6SAndrew Morton 
32831da177e4SLinus Torvalds 		/*
32841d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
32851d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
32861d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
32871d82de61SMel Gorman 		 * about consistent aging.
32881d82de61SMel Gorman 		 */
3289ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
32901d82de61SMel Gorman 
32911d82de61SMel Gorman 		/*
3292b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3293b7ea3c41SMel Gorman 		 * even in laptop mode.
3294b7ea3c41SMel Gorman 		 */
3295047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3296b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3297b7ea3c41SMel Gorman 
32981d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
32991da177e4SLinus Torvalds 		sc.nr_scanned = 0;
33000608f43dSAndrew Morton 		nr_soft_scanned = 0;
3301ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
33021d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
33030608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
33040608f43dSAndrew Morton 
330532a4330dSRik van Riel 		/*
33061d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
33071d82de61SMel Gorman 		 * enough pages are already being scanned that that high
33081d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
330932a4330dSRik van Riel 		 */
3310970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3311b8e83b94SMel Gorman 			raise_priority = false;
3312d7868daeSMel Gorman 
33135515061dSMel Gorman 		/*
33145515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
33155515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
33165515061dSMel Gorman 		 * able to safely make forward progress. Wake them
33175515061dSMel Gorman 		 */
33185515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3319c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3320cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
33215515061dSMel Gorman 
3322b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3323b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3324b8e83b94SMel Gorman 			break;
3325b8e83b94SMel Gorman 
3326b8e83b94SMel Gorman 		/*
3327b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3328b8e83b94SMel Gorman 		 * progress in reclaiming pages
3329b8e83b94SMel Gorman 		 */
3330c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3331c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3332b8e83b94SMel Gorman 			sc.priority--;
33331d82de61SMel Gorman 	} while (sc.priority >= 1);
33341da177e4SLinus Torvalds 
3335c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3336c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3337c73322d0SJohannes Weiner 
3338b8e83b94SMel Gorman out:
33392a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
33400abdee2bSMel Gorman 	/*
33411d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
33421d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
33431d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
33441d82de61SMel Gorman 	 * remain at the higher level.
33450abdee2bSMel Gorman 	 */
33461d82de61SMel Gorman 	return sc.order;
33471da177e4SLinus Torvalds }
33481da177e4SLinus Torvalds 
3349e716f2ebSMel Gorman /*
3350e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3351e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3352e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3353e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3354e716f2ebSMel Gorman  * was recently woke for.
3355e716f2ebSMel Gorman  */
3356e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3357e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3358e716f2ebSMel Gorman {
3359e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3360e716f2ebSMel Gorman 		return classzone_idx;
3361e716f2ebSMel Gorman 
3362e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3363e716f2ebSMel Gorman }
3364e716f2ebSMel Gorman 
336538087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
336638087d9bSMel Gorman 				unsigned int classzone_idx)
3367f0bc0a60SKOSAKI Motohiro {
3368f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3369f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3370f0bc0a60SKOSAKI Motohiro 
3371f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3372f0bc0a60SKOSAKI Motohiro 		return;
3373f0bc0a60SKOSAKI Motohiro 
3374f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3375f0bc0a60SKOSAKI Motohiro 
3376333b0a45SShantanu Goel 	/*
3377333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3378333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3379333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3380333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3381333b0a45SShantanu Goel 	 * succeed.
3382333b0a45SShantanu Goel 	 */
3383d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3384fd901c95SVlastimil Babka 		/*
3385fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3386fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3387fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3388fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3389fd901c95SVlastimil Babka 		 */
3390fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3391fd901c95SVlastimil Babka 
3392fd901c95SVlastimil Babka 		/*
3393fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3394fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3395fd901c95SVlastimil Babka 		 */
339638087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3397fd901c95SVlastimil Babka 
3398f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
339938087d9bSMel Gorman 
340038087d9bSMel Gorman 		/*
340138087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
340238087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
340338087d9bSMel Gorman 		 * the previous request that slept prematurely.
340438087d9bSMel Gorman 		 */
340538087d9bSMel Gorman 		if (remaining) {
3406e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
340738087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
340838087d9bSMel Gorman 		}
340938087d9bSMel Gorman 
3410f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3411f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3412f0bc0a60SKOSAKI Motohiro 	}
3413f0bc0a60SKOSAKI Motohiro 
3414f0bc0a60SKOSAKI Motohiro 	/*
3415f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3416f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3417f0bc0a60SKOSAKI Motohiro 	 */
3418d9f21d42SMel Gorman 	if (!remaining &&
3419d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3420f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3421f0bc0a60SKOSAKI Motohiro 
3422f0bc0a60SKOSAKI Motohiro 		/*
3423f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3424f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3425f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3426f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3427f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3428f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3429f0bc0a60SKOSAKI Motohiro 		 */
3430f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
34311c7e7f6cSAaditya Kumar 
34321c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3433f0bc0a60SKOSAKI Motohiro 			schedule();
34341c7e7f6cSAaditya Kumar 
3435f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3436f0bc0a60SKOSAKI Motohiro 	} else {
3437f0bc0a60SKOSAKI Motohiro 		if (remaining)
3438f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3439f0bc0a60SKOSAKI Motohiro 		else
3440f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3441f0bc0a60SKOSAKI Motohiro 	}
3442f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3443f0bc0a60SKOSAKI Motohiro }
3444f0bc0a60SKOSAKI Motohiro 
34451da177e4SLinus Torvalds /*
34461da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
34471da177e4SLinus Torvalds  * from the init process.
34481da177e4SLinus Torvalds  *
34491da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
34501da177e4SLinus Torvalds  * free memory available even if there is no other activity
34511da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
34521da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
34531da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
34541da177e4SLinus Torvalds  *
34551da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
34561da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
34571da177e4SLinus Torvalds  */
34581da177e4SLinus Torvalds static int kswapd(void *p)
34591da177e4SLinus Torvalds {
3460e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3461e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
34621da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
34631da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3464f0bc0a60SKOSAKI Motohiro 
34651da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
34661da177e4SLinus Torvalds 		.reclaimed_slab = 0,
34671da177e4SLinus Torvalds 	};
3468a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
34691da177e4SLinus Torvalds 
3470174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3471c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
34721da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
34731da177e4SLinus Torvalds 
34741da177e4SLinus Torvalds 	/*
34751da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
34761da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
34771da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
34781da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
34791da177e4SLinus Torvalds 	 *
34801da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
34811da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
34821da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
34831da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
34841da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
34851da177e4SLinus Torvalds 	 */
3486930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
348783144186SRafael J. Wysocki 	set_freezable();
34881da177e4SLinus Torvalds 
3489e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3490e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
34911da177e4SLinus Torvalds 	for ( ; ; ) {
34926f6313d4SJeff Liu 		bool ret;
34933e1d1d28SChristoph Lameter 
3494e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3495e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3496e716f2ebSMel Gorman 
349738087d9bSMel Gorman kswapd_try_sleep:
349838087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
349938087d9bSMel Gorman 					classzone_idx);
3500215ddd66SMel Gorman 
350138087d9bSMel Gorman 		/* Read the new order and classzone_idx */
350238087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3503e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
350438087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3505e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35061da177e4SLinus Torvalds 
35078fe23e05SDavid Rientjes 		ret = try_to_freeze();
35088fe23e05SDavid Rientjes 		if (kthread_should_stop())
35098fe23e05SDavid Rientjes 			break;
35108fe23e05SDavid Rientjes 
35118fe23e05SDavid Rientjes 		/*
35128fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
35138fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3514b1296cc4SRafael J. Wysocki 		 */
351538087d9bSMel Gorman 		if (ret)
351638087d9bSMel Gorman 			continue;
35171d82de61SMel Gorman 
351838087d9bSMel Gorman 		/*
351938087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
352038087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
352138087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
352238087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
352338087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
352438087d9bSMel Gorman 		 * request (alloc_order).
352538087d9bSMel Gorman 		 */
3526e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3527e5146b12SMel Gorman 						alloc_order);
3528d92a8cfcSPeter Zijlstra 		fs_reclaim_acquire(GFP_KERNEL);
352938087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
3530d92a8cfcSPeter Zijlstra 		fs_reclaim_release(GFP_KERNEL);
353138087d9bSMel Gorman 		if (reclaim_order < alloc_order)
353238087d9bSMel Gorman 			goto kswapd_try_sleep;
353333906bc5SMel Gorman 	}
3534b0a8cc58STakamori Yamaguchi 
353571abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3536b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
353771abdc15SJohannes Weiner 
35381da177e4SLinus Torvalds 	return 0;
35391da177e4SLinus Torvalds }
35401da177e4SLinus Torvalds 
35411da177e4SLinus Torvalds /*
35425ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
35435ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
35445ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
35455ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
35465ecd9d40SDavid Rientjes  * needed.
35471da177e4SLinus Torvalds  */
35485ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
35495ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
35501da177e4SLinus Torvalds {
35511da177e4SLinus Torvalds 	pg_data_t *pgdat;
35521da177e4SLinus Torvalds 
35536aa303deSMel Gorman 	if (!managed_zone(zone))
35541da177e4SLinus Torvalds 		return;
35551da177e4SLinus Torvalds 
35565ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
35571da177e4SLinus Torvalds 		return;
355888f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3559e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3560e716f2ebSMel Gorman 							   classzone_idx);
356138087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
35628d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
35631da177e4SLinus Torvalds 		return;
3564e1a55637SMel Gorman 
35655ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
35665ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
35675ecd9d40SDavid Rientjes 	    pgdat_balanced(pgdat, order, classzone_idx)) {
35685ecd9d40SDavid Rientjes 		/*
35695ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
35705ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
35715ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
35725ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
35735ecd9d40SDavid Rientjes 		 * ratelimit its work.
35745ecd9d40SDavid Rientjes 		 */
35755ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
35765ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3577c73322d0SJohannes Weiner 		return;
35785ecd9d40SDavid Rientjes 	}
3579c73322d0SJohannes Weiner 
35805ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
35815ecd9d40SDavid Rientjes 				      gfp_flags);
35828d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
35831da177e4SLinus Torvalds }
35841da177e4SLinus Torvalds 
3585c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
35861da177e4SLinus Torvalds /*
35877b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3588d6277db4SRafael J. Wysocki  * freed pages.
3589d6277db4SRafael J. Wysocki  *
3590d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3591d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3592d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
35931da177e4SLinus Torvalds  */
35947b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
35951da177e4SLinus Torvalds {
3596d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3597d6277db4SRafael J. Wysocki 	struct scan_control sc = {
35987b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3599ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3600b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
36019e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3602ee814fe2SJohannes Weiner 		.may_writepage = 1,
3603ee814fe2SJohannes Weiner 		.may_unmap = 1,
3604ee814fe2SJohannes Weiner 		.may_swap = 1,
3605ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
36061da177e4SLinus Torvalds 	};
36077b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
36087b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
36097b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3610499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
36111da177e4SLinus Torvalds 
3612499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3613d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
3614d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
36157b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3616d6277db4SRafael J. Wysocki 
36173115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3618d6277db4SRafael J. Wysocki 
36197b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3620d92a8cfcSPeter Zijlstra 	fs_reclaim_release(sc.gfp_mask);
3621499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3622d6277db4SRafael J. Wysocki 
36237b51755cSKOSAKI Motohiro 	return nr_reclaimed;
36241da177e4SLinus Torvalds }
3625c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
36261da177e4SLinus Torvalds 
36271da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
36281da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
36291da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
36301da177e4SLinus Torvalds    restore their cpu bindings. */
3631517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
36321da177e4SLinus Torvalds {
363358c0a4a7SYasunori Goto 	int nid;
36341da177e4SLinus Torvalds 
363548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3636c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3637a70f7302SRusty Russell 		const struct cpumask *mask;
3638a70f7302SRusty Russell 
3639a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3640c5f59f08SMike Travis 
36413e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
36421da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3643c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
36441da177e4SLinus Torvalds 	}
3645517bbed9SSebastian Andrzej Siewior 	return 0;
36461da177e4SLinus Torvalds }
36471da177e4SLinus Torvalds 
36483218ae14SYasunori Goto /*
36493218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
36503218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
36513218ae14SYasunori Goto  */
36523218ae14SYasunori Goto int kswapd_run(int nid)
36533218ae14SYasunori Goto {
36543218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
36553218ae14SYasunori Goto 	int ret = 0;
36563218ae14SYasunori Goto 
36573218ae14SYasunori Goto 	if (pgdat->kswapd)
36583218ae14SYasunori Goto 		return 0;
36593218ae14SYasunori Goto 
36603218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
36613218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
36623218ae14SYasunori Goto 		/* failure at boot is fatal */
3663c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3664d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3665d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3666d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
36673218ae14SYasunori Goto 	}
36683218ae14SYasunori Goto 	return ret;
36693218ae14SYasunori Goto }
36703218ae14SYasunori Goto 
36718fe23e05SDavid Rientjes /*
3672d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3673bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
36748fe23e05SDavid Rientjes  */
36758fe23e05SDavid Rientjes void kswapd_stop(int nid)
36768fe23e05SDavid Rientjes {
36778fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
36788fe23e05SDavid Rientjes 
3679d8adde17SJiang Liu 	if (kswapd) {
36808fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3681d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3682d8adde17SJiang Liu 	}
36838fe23e05SDavid Rientjes }
36848fe23e05SDavid Rientjes 
36851da177e4SLinus Torvalds static int __init kswapd_init(void)
36861da177e4SLinus Torvalds {
3687517bbed9SSebastian Andrzej Siewior 	int nid, ret;
368869e05944SAndrew Morton 
36891da177e4SLinus Torvalds 	swap_setup();
369048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
36913218ae14SYasunori Goto  		kswapd_run(nid);
3692517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3693517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3694517bbed9SSebastian Andrzej Siewior 					NULL);
3695517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
36961da177e4SLinus Torvalds 	return 0;
36971da177e4SLinus Torvalds }
36981da177e4SLinus Torvalds 
36991da177e4SLinus Torvalds module_init(kswapd_init)
37009eeff239SChristoph Lameter 
37019eeff239SChristoph Lameter #ifdef CONFIG_NUMA
37029eeff239SChristoph Lameter /*
3703a5f5f91dSMel Gorman  * Node reclaim mode
37049eeff239SChristoph Lameter  *
3705a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
37069eeff239SChristoph Lameter  * the watermarks.
37079eeff239SChristoph Lameter  */
3708a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
37099eeff239SChristoph Lameter 
37101b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
37117d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
37121b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
371395bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
37141b2ffb78SChristoph Lameter 
37159eeff239SChristoph Lameter /*
3716a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3717a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3718a92f7126SChristoph Lameter  * a zone.
3719a92f7126SChristoph Lameter  */
3720a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3721a92f7126SChristoph Lameter 
37229eeff239SChristoph Lameter /*
3723a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
37249614634fSChristoph Lameter  * occur.
37259614634fSChristoph Lameter  */
37269614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
37279614634fSChristoph Lameter 
37289614634fSChristoph Lameter /*
37290ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
37300ff38490SChristoph Lameter  * slab reclaim needs to occur.
37310ff38490SChristoph Lameter  */
37320ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
37330ff38490SChristoph Lameter 
373411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
373590afa5deSMel Gorman {
373611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
373711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
373811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
373990afa5deSMel Gorman 
374090afa5deSMel Gorman 	/*
374190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
374290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
374390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
374490afa5deSMel Gorman 	 */
374590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
374690afa5deSMel Gorman }
374790afa5deSMel Gorman 
374890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3749a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
375090afa5deSMel Gorman {
3751d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3752d031a157SAlexandru Moise 	unsigned long delta = 0;
375390afa5deSMel Gorman 
375490afa5deSMel Gorman 	/*
375595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
375690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
375711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
375890afa5deSMel Gorman 	 * a better estimate
375990afa5deSMel Gorman 	 */
3760a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3761a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
376290afa5deSMel Gorman 	else
3763a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
376490afa5deSMel Gorman 
376590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3766a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3767a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
376890afa5deSMel Gorman 
376990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
377090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
377190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
377290afa5deSMel Gorman 
377390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
377490afa5deSMel Gorman }
377590afa5deSMel Gorman 
37760ff38490SChristoph Lameter /*
3777a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
37789eeff239SChristoph Lameter  */
3779a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
37809eeff239SChristoph Lameter {
37817fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
378269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
37839eeff239SChristoph Lameter 	struct task_struct *p = current;
37849eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3785499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
3786179e9639SAndrew Morton 	struct scan_control sc = {
378762b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3788f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3789bd2f6199SJohannes Weiner 		.order = order,
3790a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3791a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3792a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3793ee814fe2SJohannes Weiner 		.may_swap = 1,
3794f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
3795179e9639SAndrew Morton 	};
37969eeff239SChristoph Lameter 
37979eeff239SChristoph Lameter 	cond_resched();
3798d4f7796eSChristoph Lameter 	/*
379995bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3800d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
380195bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3802d4f7796eSChristoph Lameter 	 */
3803499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3804499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
3805d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
38069eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
38079eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3808c84db23cSChristoph Lameter 
3809a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3810a92f7126SChristoph Lameter 		/*
3811*894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
38120ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3813a92f7126SChristoph Lameter 		 */
3814a92f7126SChristoph Lameter 		do {
3815970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
38169e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
38170ff38490SChristoph Lameter 	}
3818a92f7126SChristoph Lameter 
38199eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3820d92a8cfcSPeter Zijlstra 	fs_reclaim_release(gfp_mask);
3821499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
3822499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3823a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
38249eeff239SChristoph Lameter }
3825179e9639SAndrew Morton 
3826a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3827179e9639SAndrew Morton {
3828d773ed6bSDavid Rientjes 	int ret;
3829179e9639SAndrew Morton 
3830179e9639SAndrew Morton 	/*
3831a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
38320ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
383334aa1330SChristoph Lameter 	 *
38349614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
38359614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3836a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3837a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
38389614634fSChristoph Lameter 	 * unmapped file backed pages.
3839179e9639SAndrew Morton 	 */
3840a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3841385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3842a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3843179e9639SAndrew Morton 
3844179e9639SAndrew Morton 	/*
3845d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3846179e9639SAndrew Morton 	 */
3847d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3848a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3849179e9639SAndrew Morton 
3850179e9639SAndrew Morton 	/*
3851a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3852179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3853179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3854179e9639SAndrew Morton 	 * as wide as possible.
3855179e9639SAndrew Morton 	 */
3856a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3857a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3858d773ed6bSDavid Rientjes 
3859a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3860a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3861fa5e084eSMel Gorman 
3862a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3863a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3864d773ed6bSDavid Rientjes 
386524cf7251SMel Gorman 	if (!ret)
386624cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
386724cf7251SMel Gorman 
3868d773ed6bSDavid Rientjes 	return ret;
3869179e9639SAndrew Morton }
38709eeff239SChristoph Lameter #endif
3871894bc310SLee Schermerhorn 
3872894bc310SLee Schermerhorn /*
3873894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3874894bc310SLee Schermerhorn  * @page: the page to test
3875894bc310SLee Schermerhorn  *
3876894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
387739b5f29aSHugh Dickins  * lists vs unevictable list.
3878894bc310SLee Schermerhorn  *
3879894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3880ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3881b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3882ba9ddf49SLee Schermerhorn  *
3883894bc310SLee Schermerhorn  */
388439b5f29aSHugh Dickins int page_evictable(struct page *page)
3885894bc310SLee Schermerhorn {
3886e92bb4ddSHuang Ying 	int ret;
3887e92bb4ddSHuang Ying 
3888e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
3889e92bb4ddSHuang Ying 	rcu_read_lock();
3890e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3891e92bb4ddSHuang Ying 	rcu_read_unlock();
3892e92bb4ddSHuang Ying 	return ret;
3893894bc310SLee Schermerhorn }
389489e004eaSLee Schermerhorn 
389585046579SHugh Dickins #ifdef CONFIG_SHMEM
389689e004eaSLee Schermerhorn /**
389724513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
389824513264SHugh Dickins  * @pages:	array of pages to check
389924513264SHugh Dickins  * @nr_pages:	number of pages to check
390089e004eaSLee Schermerhorn  *
390124513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
390285046579SHugh Dickins  *
390385046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
390489e004eaSLee Schermerhorn  */
390524513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
390689e004eaSLee Schermerhorn {
3907925b7673SJohannes Weiner 	struct lruvec *lruvec;
3908785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
390924513264SHugh Dickins 	int pgscanned = 0;
391024513264SHugh Dickins 	int pgrescued = 0;
391189e004eaSLee Schermerhorn 	int i;
391289e004eaSLee Schermerhorn 
391324513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
391424513264SHugh Dickins 		struct page *page = pages[i];
3915785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
391689e004eaSLee Schermerhorn 
391724513264SHugh Dickins 		pgscanned++;
3918785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3919785b99feSMel Gorman 			if (pgdat)
3920785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3921785b99feSMel Gorman 			pgdat = pagepgdat;
3922785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
392389e004eaSLee Schermerhorn 		}
3924785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
392589e004eaSLee Schermerhorn 
392624513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
392724513264SHugh Dickins 			continue;
392889e004eaSLee Schermerhorn 
392939b5f29aSHugh Dickins 		if (page_evictable(page)) {
393024513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
393124513264SHugh Dickins 
3932309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
393324513264SHugh Dickins 			ClearPageUnevictable(page);
3934fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3935fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
393624513264SHugh Dickins 			pgrescued++;
393789e004eaSLee Schermerhorn 		}
393889e004eaSLee Schermerhorn 	}
393924513264SHugh Dickins 
3940785b99feSMel Gorman 	if (pgdat) {
394124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
394224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3943785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
394424513264SHugh Dickins 	}
394585046579SHugh Dickins }
394685046579SHugh Dickins #endif /* CONFIG_SHMEM */
3947