xref: /openbmc/linux/mm/vmscan.c (revision 69d763fc6d3aee787a3e8c8c35092b4f4960fa5d)
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 
4451d3d4437SGlauber Costa 	if (!down_read_trylock(&shrinker_rwsem)) {
4461d3d4437SGlauber Costa 		/*
4471d3d4437SGlauber Costa 		 * If we would return 0, our callers would understand that we
4481d3d4437SGlauber Costa 		 * have nothing else to shrink and give up trying. By returning
4491d3d4437SGlauber Costa 		 * 1 we keep it going and assume we'll be able to shrink next
4501d3d4437SGlauber Costa 		 * time.
4511d3d4437SGlauber Costa 		 */
4521d3d4437SGlauber Costa 		freed = 1;
4531d3d4437SGlauber Costa 		goto out;
4541d3d4437SGlauber Costa 	}
4551d3d4437SGlauber Costa 
4561d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
4576b4f7799SJohannes Weiner 		struct shrink_control sc = {
4586b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
4596b4f7799SJohannes Weiner 			.nid = nid,
460cb731d6cSVladimir Davydov 			.memcg = memcg,
4616b4f7799SJohannes Weiner 		};
4626b4f7799SJohannes Weiner 
4630fc9f58aSVladimir Davydov 		/*
4640fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
4650fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
4660fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
4670fc9f58aSVladimir Davydov 		 */
4680fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
4690fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
470cb731d6cSVladimir Davydov 			continue;
471cb731d6cSVladimir Davydov 
4726b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
4736b4f7799SJohannes Weiner 			sc.nid = 0;
4746b4f7799SJohannes Weiner 
4759092c71bSJosef Bacik 		freed += do_shrink_slab(&sc, shrinker, priority);
476e496612cSMinchan Kim 		/*
477e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
478e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
479e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
480e496612cSMinchan Kim 		 */
481e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
482e496612cSMinchan Kim 			freed = freed ? : 1;
483e496612cSMinchan Kim 			break;
484e496612cSMinchan Kim 		}
485ec97097bSVladimir Davydov 	}
4861d3d4437SGlauber Costa 
4871da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
488f06590bdSMinchan Kim out:
489f06590bdSMinchan Kim 	cond_resched();
49024f7c6b9SDave Chinner 	return freed;
4911da177e4SLinus Torvalds }
4921da177e4SLinus Torvalds 
493cb731d6cSVladimir Davydov void drop_slab_node(int nid)
494cb731d6cSVladimir Davydov {
495cb731d6cSVladimir Davydov 	unsigned long freed;
496cb731d6cSVladimir Davydov 
497cb731d6cSVladimir Davydov 	do {
498cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
499cb731d6cSVladimir Davydov 
500cb731d6cSVladimir Davydov 		freed = 0;
501cb731d6cSVladimir Davydov 		do {
5029092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
503cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
504cb731d6cSVladimir Davydov 	} while (freed > 10);
505cb731d6cSVladimir Davydov }
506cb731d6cSVladimir Davydov 
507cb731d6cSVladimir Davydov void drop_slab(void)
508cb731d6cSVladimir Davydov {
509cb731d6cSVladimir Davydov 	int nid;
510cb731d6cSVladimir Davydov 
511cb731d6cSVladimir Davydov 	for_each_online_node(nid)
512cb731d6cSVladimir Davydov 		drop_slab_node(nid);
513cb731d6cSVladimir Davydov }
514cb731d6cSVladimir Davydov 
5151da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5161da177e4SLinus Torvalds {
517ceddc3a5SJohannes Weiner 	/*
518ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
519ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
520ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
521ceddc3a5SJohannes Weiner 	 */
522bd4c82c2SHuang Ying 	int radix_pins = PageTransHuge(page) && PageSwapCache(page) ?
523bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
524bd4c82c2SHuang Ying 	return page_count(page) - page_has_private(page) == 1 + radix_pins;
5251da177e4SLinus Torvalds }
5261da177e4SLinus Torvalds 
527703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5281da177e4SLinus Torvalds {
529930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5301da177e4SLinus Torvalds 		return 1;
531703c2708STejun Heo 	if (!inode_write_congested(inode))
5321da177e4SLinus Torvalds 		return 1;
533703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5341da177e4SLinus Torvalds 		return 1;
5351da177e4SLinus Torvalds 	return 0;
5361da177e4SLinus Torvalds }
5371da177e4SLinus Torvalds 
5381da177e4SLinus Torvalds /*
5391da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5401da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5411da177e4SLinus Torvalds  * fsync(), msync() or close().
5421da177e4SLinus Torvalds  *
5431da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
5441da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
5451da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
5461da177e4SLinus Torvalds  *
5471da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
5481da177e4SLinus Torvalds  * __GFP_FS.
5491da177e4SLinus Torvalds  */
5501da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
5511da177e4SLinus Torvalds 				struct page *page, int error)
5521da177e4SLinus Torvalds {
5537eaceaccSJens Axboe 	lock_page(page);
5543e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
5553e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
5561da177e4SLinus Torvalds 	unlock_page(page);
5571da177e4SLinus Torvalds }
5581da177e4SLinus Torvalds 
55904e62a29SChristoph Lameter /* possible outcome of pageout() */
56004e62a29SChristoph Lameter typedef enum {
56104e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
56204e62a29SChristoph Lameter 	PAGE_KEEP,
56304e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
56404e62a29SChristoph Lameter 	PAGE_ACTIVATE,
56504e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
56604e62a29SChristoph Lameter 	PAGE_SUCCESS,
56704e62a29SChristoph Lameter 	/* page is clean and locked */
56804e62a29SChristoph Lameter 	PAGE_CLEAN,
56904e62a29SChristoph Lameter } pageout_t;
57004e62a29SChristoph Lameter 
5711da177e4SLinus Torvalds /*
5721742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
5731742f19fSAndrew Morton  * Calls ->writepage().
5741da177e4SLinus Torvalds  */
575c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
5767d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
5771da177e4SLinus Torvalds {
5781da177e4SLinus Torvalds 	/*
5791da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
5801da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
5811da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
5821da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
5831da177e4SLinus Torvalds 	 * PagePrivate for that.
5841da177e4SLinus Torvalds 	 *
5858174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
5861da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
5871da177e4SLinus Torvalds 	 * will block.
5881da177e4SLinus Torvalds 	 *
5891da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
5901da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
5911da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
5921da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
5931da177e4SLinus Torvalds 	 */
5941da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
5951da177e4SLinus Torvalds 		return PAGE_KEEP;
5961da177e4SLinus Torvalds 	if (!mapping) {
5971da177e4SLinus Torvalds 		/*
5981da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
5991da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
6001da177e4SLinus Torvalds 		 */
601266cf658SDavid Howells 		if (page_has_private(page)) {
6021da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
6031da177e4SLinus Torvalds 				ClearPageDirty(page);
604b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
6051da177e4SLinus Torvalds 				return PAGE_CLEAN;
6061da177e4SLinus Torvalds 			}
6071da177e4SLinus Torvalds 		}
6081da177e4SLinus Torvalds 		return PAGE_KEEP;
6091da177e4SLinus Torvalds 	}
6101da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6111da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
612703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6131da177e4SLinus Torvalds 		return PAGE_KEEP;
6141da177e4SLinus Torvalds 
6151da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6161da177e4SLinus Torvalds 		int res;
6171da177e4SLinus Torvalds 		struct writeback_control wbc = {
6181da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6191da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
620111ebb6eSOGAWA Hirofumi 			.range_start = 0,
621111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6221da177e4SLinus Torvalds 			.for_reclaim = 1,
6231da177e4SLinus Torvalds 		};
6241da177e4SLinus Torvalds 
6251da177e4SLinus Torvalds 		SetPageReclaim(page);
6261da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6271da177e4SLinus Torvalds 		if (res < 0)
6281da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
629994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6301da177e4SLinus Torvalds 			ClearPageReclaim(page);
6311da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6321da177e4SLinus Torvalds 		}
633c661b078SAndy Whitcroft 
6341da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6351da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6361da177e4SLinus Torvalds 			ClearPageReclaim(page);
6371da177e4SLinus Torvalds 		}
6383aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
639c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6401da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6411da177e4SLinus Torvalds 	}
6421da177e4SLinus Torvalds 
6431da177e4SLinus Torvalds 	return PAGE_CLEAN;
6441da177e4SLinus Torvalds }
6451da177e4SLinus Torvalds 
646a649fd92SAndrew Morton /*
647e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
648e286781dSNick Piggin  * gets returned with a refcount of 0.
649a649fd92SAndrew Morton  */
650a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
651a528910eSJohannes Weiner 			    bool reclaimed)
65249d2e9ccSChristoph Lameter {
653c4843a75SGreg Thelen 	unsigned long flags;
654bd4c82c2SHuang Ying 	int refcount;
655c4843a75SGreg Thelen 
65628e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
65728e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
65849d2e9ccSChristoph Lameter 
659c4843a75SGreg Thelen 	spin_lock_irqsave(&mapping->tree_lock, flags);
66049d2e9ccSChristoph Lameter 	/*
6610fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
6620fd0e6b0SNick Piggin 	 *
6630fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
6640fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
6650fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
6660fd0e6b0SNick Piggin 	 * here, then the following race may occur:
6670fd0e6b0SNick Piggin 	 *
6680fd0e6b0SNick Piggin 	 * get_user_pages(&page);
6690fd0e6b0SNick Piggin 	 * [user mapping goes away]
6700fd0e6b0SNick Piggin 	 * write_to(page);
6710fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
6720fd0e6b0SNick Piggin 	 * SetPageDirty(page);
6730fd0e6b0SNick Piggin 	 * put_page(page);
6740fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
6750fd0e6b0SNick Piggin 	 *
6760fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
6770fd0e6b0SNick Piggin 	 *
6780fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
6790fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
6800139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
6810fd0e6b0SNick Piggin 	 *
6820fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
6830fd0e6b0SNick Piggin 	 * and thus under tree_lock, then this ordering is not required.
68449d2e9ccSChristoph Lameter 	 */
685bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
686bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
687bd4c82c2SHuang Ying 	else
688bd4c82c2SHuang Ying 		refcount = 2;
689bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
69049d2e9ccSChristoph Lameter 		goto cannot_free;
691e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
692e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
693bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
69449d2e9ccSChristoph Lameter 		goto cannot_free;
695e286781dSNick Piggin 	}
69649d2e9ccSChristoph Lameter 
69749d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
69849d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
6990a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
70049d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
701c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
70275f6d6d2SMinchan Kim 		put_swap_page(page, swap);
703e286781dSNick Piggin 	} else {
7046072d13cSLinus Torvalds 		void (*freepage)(struct page *);
705a528910eSJohannes Weiner 		void *shadow = NULL;
7066072d13cSLinus Torvalds 
7076072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
708a528910eSJohannes Weiner 		/*
709a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
710a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
711a528910eSJohannes Weiner 		 *
712a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
713a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
714a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
715a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
716a528910eSJohannes Weiner 		 * back.
717f9fe48beSRoss Zwisler 		 *
718f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
719f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
720f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
721f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
722f9fe48beSRoss Zwisler 		 * same page_tree.
723a528910eSJohannes Weiner 		 */
724a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
725f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
726a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
72762cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
728c4843a75SGreg Thelen 		spin_unlock_irqrestore(&mapping->tree_lock, flags);
7296072d13cSLinus Torvalds 
7306072d13cSLinus Torvalds 		if (freepage != NULL)
7316072d13cSLinus Torvalds 			freepage(page);
732e286781dSNick Piggin 	}
733e286781dSNick Piggin 
73449d2e9ccSChristoph Lameter 	return 1;
73549d2e9ccSChristoph Lameter 
73649d2e9ccSChristoph Lameter cannot_free:
737c4843a75SGreg Thelen 	spin_unlock_irqrestore(&mapping->tree_lock, flags);
73849d2e9ccSChristoph Lameter 	return 0;
73949d2e9ccSChristoph Lameter }
74049d2e9ccSChristoph Lameter 
7411da177e4SLinus Torvalds /*
742e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
743e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
744e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
745e286781dSNick Piggin  * this page.
746e286781dSNick Piggin  */
747e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
748e286781dSNick Piggin {
749a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
750e286781dSNick Piggin 		/*
751e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
752e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
753e286781dSNick Piggin 		 * atomic operation.
754e286781dSNick Piggin 		 */
755fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
756e286781dSNick Piggin 		return 1;
757e286781dSNick Piggin 	}
758e286781dSNick Piggin 	return 0;
759e286781dSNick Piggin }
760e286781dSNick Piggin 
761894bc310SLee Schermerhorn /**
762894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
763894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
764894bc310SLee Schermerhorn  *
765894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
766894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
767894bc310SLee Schermerhorn  *
768894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
769894bc310SLee Schermerhorn  */
770894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
771894bc310SLee Schermerhorn {
7720ec3b74cSVlastimil Babka 	bool is_unevictable;
773bbfd28eeSLee Schermerhorn 	int was_unevictable = PageUnevictable(page);
774894bc310SLee Schermerhorn 
775309381feSSasha Levin 	VM_BUG_ON_PAGE(PageLRU(page), page);
776894bc310SLee Schermerhorn 
777894bc310SLee Schermerhorn redo:
778894bc310SLee Schermerhorn 	ClearPageUnevictable(page);
779894bc310SLee Schermerhorn 
78039b5f29aSHugh Dickins 	if (page_evictable(page)) {
781894bc310SLee Schermerhorn 		/*
782894bc310SLee Schermerhorn 		 * For evictable pages, we can use the cache.
783894bc310SLee Schermerhorn 		 * In event of a race, worst case is we end up with an
784894bc310SLee Schermerhorn 		 * unevictable page on [in]active list.
785894bc310SLee Schermerhorn 		 * We know how to handle that.
786894bc310SLee Schermerhorn 		 */
7870ec3b74cSVlastimil Babka 		is_unevictable = false;
788c53954a0SMel Gorman 		lru_cache_add(page);
789894bc310SLee Schermerhorn 	} else {
790894bc310SLee Schermerhorn 		/*
791894bc310SLee Schermerhorn 		 * Put unevictable pages directly on zone's unevictable
792894bc310SLee Schermerhorn 		 * list.
793894bc310SLee Schermerhorn 		 */
7940ec3b74cSVlastimil Babka 		is_unevictable = true;
795894bc310SLee Schermerhorn 		add_page_to_unevictable_list(page);
7966a7b9548SJohannes Weiner 		/*
79721ee9f39SMinchan Kim 		 * When racing with an mlock or AS_UNEVICTABLE clearing
79821ee9f39SMinchan Kim 		 * (page is unlocked) make sure that if the other thread
79921ee9f39SMinchan Kim 		 * does not observe our setting of PG_lru and fails
80024513264SHugh Dickins 		 * isolation/check_move_unevictable_pages,
80121ee9f39SMinchan Kim 		 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
8026a7b9548SJohannes Weiner 		 * the page back to the evictable list.
8036a7b9548SJohannes Weiner 		 *
80421ee9f39SMinchan Kim 		 * The other side is TestClearPageMlocked() or shmem_lock().
8056a7b9548SJohannes Weiner 		 */
8066a7b9548SJohannes Weiner 		smp_mb();
807894bc310SLee Schermerhorn 	}
808894bc310SLee Schermerhorn 
809894bc310SLee Schermerhorn 	/*
810894bc310SLee Schermerhorn 	 * page's status can change while we move it among lru. If an evictable
811894bc310SLee Schermerhorn 	 * page is on unevictable list, it never be freed. To avoid that,
812894bc310SLee Schermerhorn 	 * check after we added it to the list, again.
813894bc310SLee Schermerhorn 	 */
8140ec3b74cSVlastimil Babka 	if (is_unevictable && page_evictable(page)) {
815894bc310SLee Schermerhorn 		if (!isolate_lru_page(page)) {
816894bc310SLee Schermerhorn 			put_page(page);
817894bc310SLee Schermerhorn 			goto redo;
818894bc310SLee Schermerhorn 		}
819894bc310SLee Schermerhorn 		/* This means someone else dropped this page from LRU
820894bc310SLee Schermerhorn 		 * So, it will be freed or putback to LRU again. There is
821894bc310SLee Schermerhorn 		 * nothing to do here.
822894bc310SLee Schermerhorn 		 */
823894bc310SLee Schermerhorn 	}
824894bc310SLee Schermerhorn 
8250ec3b74cSVlastimil Babka 	if (was_unevictable && !is_unevictable)
826bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGRESCUED);
8270ec3b74cSVlastimil Babka 	else if (!was_unevictable && is_unevictable)
828bbfd28eeSLee Schermerhorn 		count_vm_event(UNEVICTABLE_PGCULLED);
829bbfd28eeSLee Schermerhorn 
830894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
831894bc310SLee Schermerhorn }
832894bc310SLee Schermerhorn 
833dfc8d636SJohannes Weiner enum page_references {
834dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
835dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
83664574746SJohannes Weiner 	PAGEREF_KEEP,
837dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
838dfc8d636SJohannes Weiner };
839dfc8d636SJohannes Weiner 
840dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
841dfc8d636SJohannes Weiner 						  struct scan_control *sc)
842dfc8d636SJohannes Weiner {
84364574746SJohannes Weiner 	int referenced_ptes, referenced_page;
844dfc8d636SJohannes Weiner 	unsigned long vm_flags;
845dfc8d636SJohannes Weiner 
846c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
847c3ac9a8aSJohannes Weiner 					  &vm_flags);
84864574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
849dfc8d636SJohannes Weiner 
850dfc8d636SJohannes Weiner 	/*
851dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
852dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
853dfc8d636SJohannes Weiner 	 */
854dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
855dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
856dfc8d636SJohannes Weiner 
85764574746SJohannes Weiner 	if (referenced_ptes) {
858e4898273SMichal Hocko 		if (PageSwapBacked(page))
85964574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
86064574746SJohannes Weiner 		/*
86164574746SJohannes Weiner 		 * All mapped pages start out with page table
86264574746SJohannes Weiner 		 * references from the instantiating fault, so we need
86364574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
86464574746SJohannes Weiner 		 * than once.
86564574746SJohannes Weiner 		 *
86664574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
86764574746SJohannes Weiner 		 * inactive list.  Another page table reference will
86864574746SJohannes Weiner 		 * lead to its activation.
86964574746SJohannes Weiner 		 *
87064574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
87164574746SJohannes Weiner 		 * so that recently deactivated but used pages are
87264574746SJohannes Weiner 		 * quickly recovered.
87364574746SJohannes Weiner 		 */
87464574746SJohannes Weiner 		SetPageReferenced(page);
87564574746SJohannes Weiner 
87634dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
877dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
878dfc8d636SJohannes Weiner 
879c909e993SKonstantin Khlebnikov 		/*
880c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
881c909e993SKonstantin Khlebnikov 		 */
882c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
883c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
884c909e993SKonstantin Khlebnikov 
88564574746SJohannes Weiner 		return PAGEREF_KEEP;
88664574746SJohannes Weiner 	}
88764574746SJohannes Weiner 
888dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8892e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
890dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
89164574746SJohannes Weiner 
89264574746SJohannes Weiner 	return PAGEREF_RECLAIM;
893dfc8d636SJohannes Weiner }
894dfc8d636SJohannes Weiner 
895e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
896e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
897e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
898e2be15f6SMel Gorman {
899b4597226SMel Gorman 	struct address_space *mapping;
900b4597226SMel Gorman 
901e2be15f6SMel Gorman 	/*
902e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
903e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
904e2be15f6SMel Gorman 	 */
905802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
906802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
907e2be15f6SMel Gorman 		*dirty = false;
908e2be15f6SMel Gorman 		*writeback = false;
909e2be15f6SMel Gorman 		return;
910e2be15f6SMel Gorman 	}
911e2be15f6SMel Gorman 
912e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
913e2be15f6SMel Gorman 	*dirty = PageDirty(page);
914e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
915b4597226SMel Gorman 
916b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
917b4597226SMel Gorman 	if (!page_has_private(page))
918b4597226SMel Gorman 		return;
919b4597226SMel Gorman 
920b4597226SMel Gorman 	mapping = page_mapping(page);
921b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
922b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
923e2be15f6SMel Gorman }
924e2be15f6SMel Gorman 
9253c710c1aSMichal Hocko struct reclaim_stat {
9263c710c1aSMichal Hocko 	unsigned nr_dirty;
9273c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty;
9283c710c1aSMichal Hocko 	unsigned nr_congested;
9293c710c1aSMichal Hocko 	unsigned nr_writeback;
9303c710c1aSMichal Hocko 	unsigned nr_immediate;
9315bccd166SMichal Hocko 	unsigned nr_activate;
9325bccd166SMichal Hocko 	unsigned nr_ref_keep;
9335bccd166SMichal Hocko 	unsigned nr_unmap_fail;
9343c710c1aSMichal Hocko };
9353c710c1aSMichal Hocko 
936e286781dSNick Piggin /*
9371742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
9381da177e4SLinus Torvalds  */
9391742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
940599d0c95SMel Gorman 				      struct pglist_data *pgdat,
941f84f6e2bSMel Gorman 				      struct scan_control *sc,
94202c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9433c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
94402c6de8dSMinchan Kim 				      bool force_reclaim)
9451da177e4SLinus Torvalds {
9461da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
947abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9481da177e4SLinus Torvalds 	int pgactivate = 0;
9493c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
9503c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
9513c710c1aSMichal Hocko 	unsigned nr_congested = 0;
9523c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
9533c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
9543c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
9555bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
9565bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
9571da177e4SLinus Torvalds 
9581da177e4SLinus Torvalds 	cond_resched();
9591da177e4SLinus Torvalds 
9601da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9611da177e4SLinus Torvalds 		struct address_space *mapping;
9621da177e4SLinus Torvalds 		struct page *page;
9631da177e4SLinus Torvalds 		int may_enter_fs;
96402c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
965e2be15f6SMel Gorman 		bool dirty, writeback;
9661da177e4SLinus Torvalds 
9671da177e4SLinus Torvalds 		cond_resched();
9681da177e4SLinus Torvalds 
9691da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9701da177e4SLinus Torvalds 		list_del(&page->lru);
9711da177e4SLinus Torvalds 
972529ae9aaSNick Piggin 		if (!trylock_page(page))
9731da177e4SLinus Torvalds 			goto keep;
9741da177e4SLinus Torvalds 
975309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9761da177e4SLinus Torvalds 
9771da177e4SLinus Torvalds 		sc->nr_scanned++;
97880e43426SChristoph Lameter 
97939b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
980ad6b6704SMinchan Kim 			goto activate_locked;
981894bc310SLee Schermerhorn 
982a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
98380e43426SChristoph Lameter 			goto keep_locked;
98480e43426SChristoph Lameter 
9851da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
986802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
987802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
9881da177e4SLinus Torvalds 			sc->nr_scanned++;
9891da177e4SLinus Torvalds 
990c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
991c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
992c661b078SAndy Whitcroft 
993e62e384eSMichal Hocko 		/*
994e2be15f6SMel Gorman 		 * The number of dirty pages determines if a zone is marked
995e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
996e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
997e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
998e2be15f6SMel Gorman 		 */
999e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1000e2be15f6SMel Gorman 		if (dirty || writeback)
1001e2be15f6SMel Gorman 			nr_dirty++;
1002e2be15f6SMel Gorman 
1003e2be15f6SMel Gorman 		if (dirty && !writeback)
1004e2be15f6SMel Gorman 			nr_unqueued_dirty++;
1005e2be15f6SMel Gorman 
1006d04e8acdSMel Gorman 		/*
1007d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1008d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1009d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1010d04e8acdSMel Gorman 		 * end of the LRU a second time.
1011d04e8acdSMel Gorman 		 */
1012e2be15f6SMel Gorman 		mapping = page_mapping(page);
10131da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1014703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1015d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1016e2be15f6SMel Gorman 			nr_congested++;
1017e2be15f6SMel Gorman 
1018e2be15f6SMel Gorman 		/*
1019283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1020283aba9fSMel Gorman 		 * are three cases to consider.
1021e62e384eSMichal Hocko 		 *
1022283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1023283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1024283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1025283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1026283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1027283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1028283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1029b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1030b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1031c3b94f44SHugh Dickins 		 *
103297c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1033ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1034ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1035ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
103697c9341fSTejun Heo 		 *    reclaim and continue scanning.
1037283aba9fSMel Gorman 		 *
1038ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1039ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1040283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1041283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1042283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1043283aba9fSMel Gorman 		 *    would probably show more reasons.
1044283aba9fSMel Gorman 		 *
10457fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1046283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1047283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1048283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1049283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1050c55e8d03SJohannes Weiner 		 *
1051c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1052c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1053c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1054c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1055c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1056c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1057c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1058c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1059e62e384eSMichal Hocko 		 */
1060283aba9fSMel Gorman 		if (PageWriteback(page)) {
1061283aba9fSMel Gorman 			/* Case 1 above */
1062283aba9fSMel Gorman 			if (current_is_kswapd() &&
1063283aba9fSMel Gorman 			    PageReclaim(page) &&
1064599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1065b1a6f21eSMel Gorman 				nr_immediate++;
1066c55e8d03SJohannes Weiner 				goto activate_locked;
1067283aba9fSMel Gorman 
1068283aba9fSMel Gorman 			/* Case 2 above */
106997c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1070ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1071c3b94f44SHugh Dickins 				/*
1072c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1073c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1074c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1075c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1076c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1077c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1078c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1079c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1080c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1081c3b94f44SHugh Dickins 				 */
1082c3b94f44SHugh Dickins 				SetPageReclaim(page);
108392df3a72SMel Gorman 				nr_writeback++;
1084c55e8d03SJohannes Weiner 				goto activate_locked;
1085283aba9fSMel Gorman 
1086283aba9fSMel Gorman 			/* Case 3 above */
1087283aba9fSMel Gorman 			} else {
10887fadc820SHugh Dickins 				unlock_page(page);
1089c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10907fadc820SHugh Dickins 				/* then go back and try same page again */
10917fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10927fadc820SHugh Dickins 				continue;
1093e62e384eSMichal Hocko 			}
1094283aba9fSMel Gorman 		}
10951da177e4SLinus Torvalds 
109602c6de8dSMinchan Kim 		if (!force_reclaim)
10976a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
109802c6de8dSMinchan Kim 
1099dfc8d636SJohannes Weiner 		switch (references) {
1100dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
11011da177e4SLinus Torvalds 			goto activate_locked;
110264574746SJohannes Weiner 		case PAGEREF_KEEP:
11035bccd166SMichal Hocko 			nr_ref_keep++;
110464574746SJohannes Weiner 			goto keep_locked;
1105dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1106dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1107dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1108dfc8d636SJohannes Weiner 		}
11091da177e4SLinus Torvalds 
11101da177e4SLinus Torvalds 		/*
11111da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
11121da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1113802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
11141da177e4SLinus Torvalds 		 */
1115bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1116bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
111763eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
111863eb6b93SHugh Dickins 					goto keep_locked;
1119747552b1SHuang Ying 				if (PageTransHuge(page)) {
1120b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1121747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1122b8f593cdSHuang Ying 						goto activate_locked;
1123747552b1SHuang Ying 					/*
1124747552b1SHuang Ying 					 * Split pages without a PMD map right
1125747552b1SHuang Ying 					 * away. Chances are some or all of the
1126747552b1SHuang Ying 					 * tail pages can be freed without IO.
1127747552b1SHuang Ying 					 */
1128747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1129bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1130bd4c82c2SHuang Ying 								    page_list))
1131747552b1SHuang Ying 						goto activate_locked;
1132747552b1SHuang Ying 				}
11330f074658SMinchan Kim 				if (!add_to_swap(page)) {
11340f074658SMinchan Kim 					if (!PageTransHuge(page))
11351da177e4SLinus Torvalds 						goto activate_locked;
1136bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1137bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1138bd4c82c2SHuang Ying 								    page_list))
11390f074658SMinchan Kim 						goto activate_locked;
1140fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1141fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1142fe490cc0SHuang Ying #endif
11430f074658SMinchan Kim 					if (!add_to_swap(page))
11440f074658SMinchan Kim 						goto activate_locked;
11450f074658SMinchan Kim 				}
11460f074658SMinchan Kim 
114763eb6b93SHugh Dickins 				may_enter_fs = 1;
11481da177e4SLinus Torvalds 
1149e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
11501da177e4SLinus Torvalds 				mapping = page_mapping(page);
1151bd4c82c2SHuang Ying 			}
11527751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
11537751b2daSKirill A. Shutemov 			/* Split file THP */
11547751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
11557751b2daSKirill A. Shutemov 				goto keep_locked;
1156e2be15f6SMel Gorman 		}
11571da177e4SLinus Torvalds 
11581da177e4SLinus Torvalds 		/*
11591da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
11601da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
11611da177e4SLinus Torvalds 		 */
1162802a3a92SShaohua Li 		if (page_mapped(page)) {
1163bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1164bd4c82c2SHuang Ying 
1165bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1166bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1167bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
11685bccd166SMichal Hocko 				nr_unmap_fail++;
11691da177e4SLinus Torvalds 				goto activate_locked;
11701da177e4SLinus Torvalds 			}
11711da177e4SLinus Torvalds 		}
11721da177e4SLinus Torvalds 
11731da177e4SLinus Torvalds 		if (PageDirty(page)) {
1174ee72886dSMel Gorman 			/*
11754eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
11764eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
11774eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
11784eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
11794eda4823SJohannes Weiner 			 * write pages when we've encountered many
11804eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
11814eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
11824eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1183ee72886dSMel Gorman 			 */
1184f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11854eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1186599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
118749ea7eb6SMel Gorman 				/*
118849ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
118949ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
119049ea7eb6SMel Gorman 				 * except we already have the page isolated
119149ea7eb6SMel Gorman 				 * and know it's dirty
119249ea7eb6SMel Gorman 				 */
1193c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
119449ea7eb6SMel Gorman 				SetPageReclaim(page);
119549ea7eb6SMel Gorman 
1196c55e8d03SJohannes Weiner 				goto activate_locked;
1197ee72886dSMel Gorman 			}
1198ee72886dSMel Gorman 
1199dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
12001da177e4SLinus Torvalds 				goto keep_locked;
12014dd4b920SAndrew Morton 			if (!may_enter_fs)
12021da177e4SLinus Torvalds 				goto keep_locked;
120352a8363eSChristoph Lameter 			if (!sc->may_writepage)
12041da177e4SLinus Torvalds 				goto keep_locked;
12051da177e4SLinus Torvalds 
1206d950c947SMel Gorman 			/*
1207d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1208d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1209d950c947SMel Gorman 			 * starts and then write it out here.
1210d950c947SMel Gorman 			 */
1211d950c947SMel Gorman 			try_to_unmap_flush_dirty();
12127d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
12131da177e4SLinus Torvalds 			case PAGE_KEEP:
12141da177e4SLinus Torvalds 				goto keep_locked;
12151da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
12161da177e4SLinus Torvalds 				goto activate_locked;
12171da177e4SLinus Torvalds 			case PAGE_SUCCESS:
12187d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
121941ac1999SMel Gorman 					goto keep;
12207d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
12211da177e4SLinus Torvalds 					goto keep;
12227d3579e8SKOSAKI Motohiro 
12231da177e4SLinus Torvalds 				/*
12241da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
12251da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
12261da177e4SLinus Torvalds 				 */
1227529ae9aaSNick Piggin 				if (!trylock_page(page))
12281da177e4SLinus Torvalds 					goto keep;
12291da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
12301da177e4SLinus Torvalds 					goto keep_locked;
12311da177e4SLinus Torvalds 				mapping = page_mapping(page);
12321da177e4SLinus Torvalds 			case PAGE_CLEAN:
12331da177e4SLinus Torvalds 				; /* try to free the page below */
12341da177e4SLinus Torvalds 			}
12351da177e4SLinus Torvalds 		}
12361da177e4SLinus Torvalds 
12371da177e4SLinus Torvalds 		/*
12381da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
12391da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
12401da177e4SLinus Torvalds 		 * the page as well.
12411da177e4SLinus Torvalds 		 *
12421da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
12431da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
12441da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
12451da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
12461da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
12471da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
12481da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
12491da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
12501da177e4SLinus Torvalds 		 *
12511da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
12521da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
12531da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
12541da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
12551da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
12561da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
12571da177e4SLinus Torvalds 		 */
1258266cf658SDavid Howells 		if (page_has_private(page)) {
12591da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
12601da177e4SLinus Torvalds 				goto activate_locked;
1261e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1262e286781dSNick Piggin 				unlock_page(page);
1263e286781dSNick Piggin 				if (put_page_testzero(page))
12641da177e4SLinus Torvalds 					goto free_it;
1265e286781dSNick Piggin 				else {
1266e286781dSNick Piggin 					/*
1267e286781dSNick Piggin 					 * rare race with speculative reference.
1268e286781dSNick Piggin 					 * the speculative reference will free
1269e286781dSNick Piggin 					 * this page shortly, so we may
1270e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1271e286781dSNick Piggin 					 * leave it off the LRU).
1272e286781dSNick Piggin 					 */
1273e286781dSNick Piggin 					nr_reclaimed++;
1274e286781dSNick Piggin 					continue;
1275e286781dSNick Piggin 				}
1276e286781dSNick Piggin 			}
12771da177e4SLinus Torvalds 		}
12781da177e4SLinus Torvalds 
1279802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1280802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1281802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
128249d2e9ccSChristoph Lameter 				goto keep_locked;
1283802a3a92SShaohua Li 			if (PageDirty(page)) {
1284802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1285802a3a92SShaohua Li 				goto keep_locked;
1286802a3a92SShaohua Li 			}
12871da177e4SLinus Torvalds 
1288802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
12892262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1290802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1291802a3a92SShaohua Li 			goto keep_locked;
1292a978d6f5SNick Piggin 		/*
1293a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1294a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1295a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1296a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1297a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1298a978d6f5SNick Piggin 		 */
129948c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1300e286781dSNick Piggin free_it:
130105ff5137SAndrew Morton 		nr_reclaimed++;
1302abe4c3b5SMel Gorman 
1303abe4c3b5SMel Gorman 		/*
1304abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1305abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1306abe4c3b5SMel Gorman 		 */
1307bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1308bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1309bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1310bd4c82c2SHuang Ying 		} else
1311abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
13121da177e4SLinus Torvalds 		continue;
13131da177e4SLinus Torvalds 
13141da177e4SLinus Torvalds activate_locked:
131568a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1316ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1317ad6b6704SMinchan Kim 						PageMlocked(page)))
1318a2c43eedSHugh Dickins 			try_to_free_swap(page);
1319309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1320ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
13211da177e4SLinus Torvalds 			SetPageActive(page);
13221da177e4SLinus Torvalds 			pgactivate++;
13232262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1324ad6b6704SMinchan Kim 		}
13251da177e4SLinus Torvalds keep_locked:
13261da177e4SLinus Torvalds 		unlock_page(page);
13271da177e4SLinus Torvalds keep:
13281da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1329309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
13301da177e4SLinus Torvalds 	}
1331abe4c3b5SMel Gorman 
1332747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
133372b252aeSMel Gorman 	try_to_unmap_flush();
13342d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1335abe4c3b5SMel Gorman 
13361da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1337f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
13380a31bc97SJohannes Weiner 
13393c710c1aSMichal Hocko 	if (stat) {
13403c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
13413c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
13423c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
13433c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
13443c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
13455bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
13465bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
13475bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
13483c710c1aSMichal Hocko 	}
134905ff5137SAndrew Morton 	return nr_reclaimed;
13501da177e4SLinus Torvalds }
13511da177e4SLinus Torvalds 
135202c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
135302c6de8dSMinchan Kim 					    struct list_head *page_list)
135402c6de8dSMinchan Kim {
135502c6de8dSMinchan Kim 	struct scan_control sc = {
135602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
135702c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
135802c6de8dSMinchan Kim 		.may_unmap = 1,
135902c6de8dSMinchan Kim 	};
13603c710c1aSMichal Hocko 	unsigned long ret;
136102c6de8dSMinchan Kim 	struct page *page, *next;
136202c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
136302c6de8dSMinchan Kim 
136402c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1365117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1366b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
136702c6de8dSMinchan Kim 			ClearPageActive(page);
136802c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
136902c6de8dSMinchan Kim 		}
137002c6de8dSMinchan Kim 	}
137102c6de8dSMinchan Kim 
1372599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1373a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
137402c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1375599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
137602c6de8dSMinchan Kim 	return ret;
137702c6de8dSMinchan Kim }
137802c6de8dSMinchan Kim 
13795ad333ebSAndy Whitcroft /*
13805ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13815ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13825ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13835ad333ebSAndy Whitcroft  *
13845ad333ebSAndy Whitcroft  * page:	page to consider
13855ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13865ad333ebSAndy Whitcroft  *
13875ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13885ad333ebSAndy Whitcroft  */
1389f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13905ad333ebSAndy Whitcroft {
13915ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13925ad333ebSAndy Whitcroft 
13935ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13945ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13955ad333ebSAndy Whitcroft 		return ret;
13965ad333ebSAndy Whitcroft 
1397e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1398e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1399894bc310SLee Schermerhorn 		return ret;
1400894bc310SLee Schermerhorn 
14015ad333ebSAndy Whitcroft 	ret = -EBUSY;
140208e552c6SKAMEZAWA Hiroyuki 
1403c8244935SMel Gorman 	/*
1404c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1405c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1406c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1407c8244935SMel Gorman 	 *
1408c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1409c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1410c8244935SMel Gorman 	 */
14111276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1412c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1413c8244935SMel Gorman 		if (PageWriteback(page))
141439deaf85SMinchan Kim 			return ret;
141539deaf85SMinchan Kim 
1416c8244935SMel Gorman 		if (PageDirty(page)) {
1417c8244935SMel Gorman 			struct address_space *mapping;
1418*69d763fcSMel Gorman 			bool migrate_dirty;
1419c8244935SMel Gorman 
1420c8244935SMel Gorman 			/*
1421c8244935SMel Gorman 			 * Only pages without mappings or that have a
1422c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
1423*69d763fcSMel Gorman 			 * without blocking. However, we can be racing with
1424*69d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
1425*69d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
1426*69d763fcSMel Gorman 			 * the page lock until after the page is removed
1427*69d763fcSMel Gorman 			 * from the page cache.
1428c8244935SMel Gorman 			 */
1429*69d763fcSMel Gorman 			if (!trylock_page(page))
1430*69d763fcSMel Gorman 				return ret;
1431*69d763fcSMel Gorman 
1432c8244935SMel Gorman 			mapping = page_mapping(page);
1433*69d763fcSMel Gorman 			migrate_dirty = mapping && mapping->a_ops->migratepage;
1434*69d763fcSMel Gorman 			unlock_page(page);
1435*69d763fcSMel Gorman 			if (!migrate_dirty)
1436c8244935SMel Gorman 				return ret;
1437c8244935SMel Gorman 		}
1438c8244935SMel Gorman 	}
1439c8244935SMel Gorman 
1440f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1441f80c0673SMinchan Kim 		return ret;
1442f80c0673SMinchan Kim 
14435ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
14445ad333ebSAndy Whitcroft 		/*
14455ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
14465ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
14475ad333ebSAndy Whitcroft 		 * page release code relies on it.
14485ad333ebSAndy Whitcroft 		 */
14495ad333ebSAndy Whitcroft 		ClearPageLRU(page);
14505ad333ebSAndy Whitcroft 		ret = 0;
14515ad333ebSAndy Whitcroft 	}
14525ad333ebSAndy Whitcroft 
14535ad333ebSAndy Whitcroft 	return ret;
14545ad333ebSAndy Whitcroft }
14555ad333ebSAndy Whitcroft 
14567ee36a14SMel Gorman 
14577ee36a14SMel Gorman /*
14587ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
14597ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
14607ee36a14SMel Gorman  */
14617ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1462b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
14637ee36a14SMel Gorman {
14647ee36a14SMel Gorman 	int zid;
14657ee36a14SMel Gorman 
14667ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14677ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14687ee36a14SMel Gorman 			continue;
14697ee36a14SMel Gorman 
14707ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1471b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1472b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1473b4536f0cSMichal Hocko #endif
14747ee36a14SMel Gorman 	}
14757ee36a14SMel Gorman 
14767ee36a14SMel Gorman }
14777ee36a14SMel Gorman 
147849d2e9ccSChristoph Lameter /*
1479a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14801da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14811da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14821da177e4SLinus Torvalds  *
14831da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14841da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14851da177e4SLinus Torvalds  *
14861da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14871da177e4SLinus Torvalds  *
1488791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
14895dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14901da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1491f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1492fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14935ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14943cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14951da177e4SLinus Torvalds  *
14961da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14971da177e4SLinus Torvalds  */
149869e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14995dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1500fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
15013cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
15021da177e4SLinus Torvalds {
150375b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
150469e05944SAndrew Morton 	unsigned long nr_taken = 0;
1505599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
15067cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
15073db65812SJohannes Weiner 	unsigned long skipped = 0;
1508791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1509b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
15101da177e4SLinus Torvalds 
1511791b48b6SMinchan Kim 	scan = 0;
1512791b48b6SMinchan Kim 	for (total_scan = 0;
1513791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1514791b48b6SMinchan Kim 	     total_scan++) {
15155ad333ebSAndy Whitcroft 		struct page *page;
15165ad333ebSAndy Whitcroft 
15171da177e4SLinus Torvalds 		page = lru_to_page(src);
15181da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
15191da177e4SLinus Torvalds 
1520309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
15218d438f96SNick Piggin 
1522b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1523b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
15247cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1525b2e18757SMel Gorman 			continue;
1526b2e18757SMel Gorman 		}
1527b2e18757SMel Gorman 
1528791b48b6SMinchan Kim 		/*
1529791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1530791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1531791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1532791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1533791b48b6SMinchan Kim 		 */
1534791b48b6SMinchan Kim 		scan++;
1535f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
15365ad333ebSAndy Whitcroft 		case 0:
1537599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1538599d0c95SMel Gorman 			nr_taken += nr_pages;
1539599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
15405ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
15415ad333ebSAndy Whitcroft 			break;
15427c8ee9a8SNick Piggin 
15435ad333ebSAndy Whitcroft 		case -EBUSY:
15445ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
15455ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
15465ad333ebSAndy Whitcroft 			continue;
15475ad333ebSAndy Whitcroft 
15485ad333ebSAndy Whitcroft 		default:
15495ad333ebSAndy Whitcroft 			BUG();
15505ad333ebSAndy Whitcroft 		}
15515ad333ebSAndy Whitcroft 	}
15521da177e4SLinus Torvalds 
1553b2e18757SMel Gorman 	/*
1554b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1555b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1556b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1557b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1558b2e18757SMel Gorman 	 * system at risk of premature OOM.
1559b2e18757SMel Gorman 	 */
15607cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
15617cc30fcfSMel Gorman 		int zid;
15627cc30fcfSMel Gorman 
15633db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
15647cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15657cc30fcfSMel Gorman 			if (!nr_skipped[zid])
15667cc30fcfSMel Gorman 				continue;
15677cc30fcfSMel Gorman 
15687cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
15691265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
15707cc30fcfSMel Gorman 		}
15717cc30fcfSMel Gorman 	}
1572791b48b6SMinchan Kim 	*nr_scanned = total_scan;
15731265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1574791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1575b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15761da177e4SLinus Torvalds 	return nr_taken;
15771da177e4SLinus Torvalds }
15781da177e4SLinus Torvalds 
157962695a84SNick Piggin /**
158062695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
158162695a84SNick Piggin  * @page: page to isolate from its LRU list
158262695a84SNick Piggin  *
158362695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
158462695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
158562695a84SNick Piggin  *
158662695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
158762695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
158862695a84SNick Piggin  *
158962695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1590894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1591894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1592894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
159362695a84SNick Piggin  *
159462695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
159562695a84SNick Piggin  * found will be decremented.
159662695a84SNick Piggin  *
159762695a84SNick Piggin  * Restrictions:
159862695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
159962695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
160062695a84SNick Piggin  *     without a stable reference).
160162695a84SNick Piggin  * (2) the lru_lock must not be held.
160262695a84SNick Piggin  * (3) interrupts must be enabled.
160362695a84SNick Piggin  */
160462695a84SNick Piggin int isolate_lru_page(struct page *page)
160562695a84SNick Piggin {
160662695a84SNick Piggin 	int ret = -EBUSY;
160762695a84SNick Piggin 
1608309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1609cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
16100c917313SKonstantin Khlebnikov 
161162695a84SNick Piggin 	if (PageLRU(page)) {
161262695a84SNick Piggin 		struct zone *zone = page_zone(page);
1613fa9add64SHugh Dickins 		struct lruvec *lruvec;
161462695a84SNick Piggin 
1615a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1616599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
16170c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1618894bc310SLee Schermerhorn 			int lru = page_lru(page);
16190c917313SKonstantin Khlebnikov 			get_page(page);
162062695a84SNick Piggin 			ClearPageLRU(page);
1621fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1622fa9add64SHugh Dickins 			ret = 0;
162362695a84SNick Piggin 		}
1624a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
162562695a84SNick Piggin 	}
162662695a84SNick Piggin 	return ret;
162762695a84SNick Piggin }
162862695a84SNick Piggin 
16295ad333ebSAndy Whitcroft /*
1630d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1631d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1632d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1633d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1634d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
163535cd7815SRik van Riel  */
1636599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
163735cd7815SRik van Riel 		struct scan_control *sc)
163835cd7815SRik van Riel {
163935cd7815SRik van Riel 	unsigned long inactive, isolated;
164035cd7815SRik van Riel 
164135cd7815SRik van Riel 	if (current_is_kswapd())
164235cd7815SRik van Riel 		return 0;
164335cd7815SRik van Riel 
164497c9341fSTejun Heo 	if (!sane_reclaim(sc))
164535cd7815SRik van Riel 		return 0;
164635cd7815SRik van Riel 
164735cd7815SRik van Riel 	if (file) {
1648599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1649599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
165035cd7815SRik van Riel 	} else {
1651599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1652599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
165335cd7815SRik van Riel 	}
165435cd7815SRik van Riel 
16553cf23841SFengguang Wu 	/*
16563cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
16573cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
16583cf23841SFengguang Wu 	 * deadlock.
16593cf23841SFengguang Wu 	 */
1660d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
16613cf23841SFengguang Wu 		inactive >>= 3;
16623cf23841SFengguang Wu 
166335cd7815SRik van Riel 	return isolated > inactive;
166435cd7815SRik van Riel }
166535cd7815SRik van Riel 
166666635629SMel Gorman static noinline_for_stack void
166775b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
166866635629SMel Gorman {
166927ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1670599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16713f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
167266635629SMel Gorman 
167366635629SMel Gorman 	/*
167466635629SMel Gorman 	 * Put back any unfreeable pages.
167566635629SMel Gorman 	 */
167666635629SMel Gorman 	while (!list_empty(page_list)) {
16773f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
167866635629SMel Gorman 		int lru;
16793f79768fSHugh Dickins 
1680309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
168166635629SMel Gorman 		list_del(&page->lru);
168239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1683599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
168466635629SMel Gorman 			putback_lru_page(page);
1685599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
168666635629SMel Gorman 			continue;
168766635629SMel Gorman 		}
1688fa9add64SHugh Dickins 
1689599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1690fa9add64SHugh Dickins 
16917a608572SLinus Torvalds 		SetPageLRU(page);
169266635629SMel Gorman 		lru = page_lru(page);
1693fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1694fa9add64SHugh Dickins 
169566635629SMel Gorman 		if (is_active_lru(lru)) {
169666635629SMel Gorman 			int file = is_file_lru(lru);
16979992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16989992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
169966635629SMel Gorman 		}
17002bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
17012bcf8879SHugh Dickins 			__ClearPageLRU(page);
17022bcf8879SHugh Dickins 			__ClearPageActive(page);
1703fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
17042bcf8879SHugh Dickins 
17052bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1706599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1707747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
17082bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1709599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
17102bcf8879SHugh Dickins 			} else
17112bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
171266635629SMel Gorman 		}
171366635629SMel Gorman 	}
171466635629SMel Gorman 
17153f79768fSHugh Dickins 	/*
17163f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
17173f79768fSHugh Dickins 	 */
17183f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
171966635629SMel Gorman }
172066635629SMel Gorman 
172166635629SMel Gorman /*
1722399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1723399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1724399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1725399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1726399ba0b9SNeilBrown  */
1727399ba0b9SNeilBrown static int current_may_throttle(void)
1728399ba0b9SNeilBrown {
1729399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1730399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1731399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1732399ba0b9SNeilBrown }
1733399ba0b9SNeilBrown 
1734399ba0b9SNeilBrown /*
1735b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
17361742f19fSAndrew Morton  * of reclaimed pages
17371da177e4SLinus Torvalds  */
173866635629SMel Gorman static noinline_for_stack unsigned long
17391a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
17409e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
17411da177e4SLinus Torvalds {
17421da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1743e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
174405ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1745e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
17463c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1747f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17483cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1749599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17501a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1751db73ee0dSMichal Hocko 	bool stalled = false;
175278dc583dSKOSAKI Motohiro 
1753599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1754db73ee0dSMichal Hocko 		if (stalled)
1755db73ee0dSMichal Hocko 			return 0;
1756db73ee0dSMichal Hocko 
1757db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1758db73ee0dSMichal Hocko 		msleep(100);
1759db73ee0dSMichal Hocko 		stalled = true;
176035cd7815SRik van Riel 
176135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
176235cd7815SRik van Riel 		if (fatal_signal_pending(current))
176335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
176435cd7815SRik van Riel 	}
176535cd7815SRik van Riel 
17661da177e4SLinus Torvalds 	lru_add_drain();
1767f80c0673SMinchan Kim 
1768f80c0673SMinchan Kim 	if (!sc->may_unmap)
176961317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1770f80c0673SMinchan Kim 
1771599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17721da177e4SLinus Torvalds 
17735dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17745dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
177595d918fcSKonstantin Khlebnikov 
1776599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17779d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
177895d918fcSKonstantin Khlebnikov 
17792262185cSRoman Gushchin 	if (current_is_kswapd()) {
17802262185cSRoman Gushchin 		if (global_reclaim(sc))
1781599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
17822262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
17832262185cSRoman Gushchin 				   nr_scanned);
17842262185cSRoman Gushchin 	} else {
17852262185cSRoman Gushchin 		if (global_reclaim(sc))
1786599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
17872262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
17882262185cSRoman Gushchin 				   nr_scanned);
1789b35ea17bSKOSAKI Motohiro 	}
1790599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1791d563c050SHillf Danton 
1792d563c050SHillf Danton 	if (nr_taken == 0)
179366635629SMel Gorman 		return 0;
1794b35ea17bSKOSAKI Motohiro 
1795a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
17963c710c1aSMichal Hocko 				&stat, false);
1797c661b078SAndy Whitcroft 
1798599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17993f79768fSHugh Dickins 
18002262185cSRoman Gushchin 	if (current_is_kswapd()) {
18012262185cSRoman Gushchin 		if (global_reclaim(sc))
1802599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
18032262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
18042262185cSRoman Gushchin 				   nr_reclaimed);
18052262185cSRoman Gushchin 	} else {
18062262185cSRoman Gushchin 		if (global_reclaim(sc))
1807599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
18082262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
18092262185cSRoman Gushchin 				   nr_reclaimed);
1810904249aaSYing Han 	}
1811a74609faSNick Piggin 
181227ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
18133f79768fSHugh Dickins 
1814599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
18153f79768fSHugh Dickins 
1816599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
18173f79768fSHugh Dickins 
1818747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
18192d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1820e11da5b4SMel Gorman 
182192df3a72SMel Gorman 	/*
182292df3a72SMel Gorman 	 * If reclaim is isolating dirty pages under writeback, it implies
182392df3a72SMel Gorman 	 * that the long-lived page allocation rate is exceeding the page
182492df3a72SMel Gorman 	 * laundering rate. Either the global limits are not being effective
182592df3a72SMel Gorman 	 * at throttling processes due to the page distribution throughout
182692df3a72SMel Gorman 	 * zones or there is heavy usage of a slow backing device. The
182792df3a72SMel Gorman 	 * only option is to throttle from reclaim context which is not ideal
182892df3a72SMel Gorman 	 * as there is no guarantee the dirtying process is throttled in the
182992df3a72SMel Gorman 	 * same way balance_dirty_pages() manages.
183092df3a72SMel Gorman 	 *
18318e950282SMel Gorman 	 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
18328e950282SMel Gorman 	 * of pages under pages flagged for immediate reclaim and stall if any
18338e950282SMel Gorman 	 * are encountered in the nr_immediate check below.
183492df3a72SMel Gorman 	 */
18353c710c1aSMichal Hocko 	if (stat.nr_writeback && stat.nr_writeback == nr_taken)
1836599d0c95SMel Gorman 		set_bit(PGDAT_WRITEBACK, &pgdat->flags);
183792df3a72SMel Gorman 
1838d43006d5SMel Gorman 	/*
183997c9341fSTejun Heo 	 * Legacy memcg will stall in page writeback so avoid forcibly
184097c9341fSTejun Heo 	 * stalling here.
1841d43006d5SMel Gorman 	 */
184297c9341fSTejun Heo 	if (sane_reclaim(sc)) {
1843b1a6f21eSMel Gorman 		/*
18448e950282SMel Gorman 		 * Tag a zone as congested if all the dirty pages scanned were
18458e950282SMel Gorman 		 * backed by a congested BDI and wait_iff_congested will stall.
18468e950282SMel Gorman 		 */
18473c710c1aSMichal Hocko 		if (stat.nr_dirty && stat.nr_dirty == stat.nr_congested)
1848599d0c95SMel Gorman 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
18498e950282SMel Gorman 
18508e950282SMel Gorman 		/*
1851b1a6f21eSMel Gorman 		 * If dirty pages are scanned that are not queued for IO, it
1852726d061fSJohannes Weiner 		 * implies that flushers are not doing their job. This can
1853726d061fSJohannes Weiner 		 * happen when memory pressure pushes dirty pages to the end of
1854726d061fSJohannes Weiner 		 * the LRU before the dirty limits are breached and the dirty
1855726d061fSJohannes Weiner 		 * data has expired. It can also happen when the proportion of
1856726d061fSJohannes Weiner 		 * dirty pages grows not through writes but through memory
1857726d061fSJohannes Weiner 		 * pressure reclaiming all the clean cache. And in some cases,
1858726d061fSJohannes Weiner 		 * the flushers simply cannot keep up with the allocation
1859726d061fSJohannes Weiner 		 * rate. Nudge the flusher threads in case they are asleep, but
1860726d061fSJohannes Weiner 		 * also allow kswapd to start writing pages during reclaim.
1861b1a6f21eSMel Gorman 		 */
1862726d061fSJohannes Weiner 		if (stat.nr_unqueued_dirty == nr_taken) {
18639ba4b2dfSJens Axboe 			wakeup_flusher_threads(WB_REASON_VMSCAN);
1864599d0c95SMel Gorman 			set_bit(PGDAT_DIRTY, &pgdat->flags);
1865726d061fSJohannes Weiner 		}
1866b1a6f21eSMel Gorman 
1867b1a6f21eSMel Gorman 		/*
1868b738d764SLinus Torvalds 		 * If kswapd scans pages marked marked for immediate
1869b738d764SLinus Torvalds 		 * reclaim and under writeback (nr_immediate), it implies
1870b738d764SLinus Torvalds 		 * that pages are cycling through the LRU faster than
1871b1a6f21eSMel Gorman 		 * they are written so also forcibly stall.
1872b1a6f21eSMel Gorman 		 */
18733c710c1aSMichal Hocko 		if (stat.nr_immediate && current_may_throttle())
1874b1a6f21eSMel Gorman 			congestion_wait(BLK_RW_ASYNC, HZ/10);
1875e2be15f6SMel Gorman 	}
1876d43006d5SMel Gorman 
18778e950282SMel Gorman 	/*
18788e950282SMel Gorman 	 * Stall direct reclaim for IO completions if underlying BDIs or zone
18798e950282SMel Gorman 	 * is congested. Allow kswapd to continue until it starts encountering
18808e950282SMel Gorman 	 * unqueued dirty pages or cycling through the LRU too quickly.
18818e950282SMel Gorman 	 */
1882399ba0b9SNeilBrown 	if (!sc->hibernation_mode && !current_is_kswapd() &&
1883399ba0b9SNeilBrown 	    current_may_throttle())
1884599d0c95SMel Gorman 		wait_iff_congested(pgdat, BLK_RW_ASYNC, HZ/10);
18858e950282SMel Gorman 
1886599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1887599d0c95SMel Gorman 			nr_scanned, nr_reclaimed,
18885bccd166SMichal Hocko 			stat.nr_dirty,  stat.nr_writeback,
18895bccd166SMichal Hocko 			stat.nr_congested, stat.nr_immediate,
18905bccd166SMichal Hocko 			stat.nr_activate, stat.nr_ref_keep,
18915bccd166SMichal Hocko 			stat.nr_unmap_fail,
1892ba5e9579Syalin wang 			sc->priority, file);
189305ff5137SAndrew Morton 	return nr_reclaimed;
18941da177e4SLinus Torvalds }
18951da177e4SLinus Torvalds 
18963bb1a852SMartin Bligh /*
18971cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18981cfb419bSKAMEZAWA Hiroyuki  *
18991cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
19001cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
19011cfb419bSKAMEZAWA Hiroyuki  *
19021cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1903a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
19041cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1905a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
19061cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
19071cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
19081cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
19091cfb419bSKAMEZAWA Hiroyuki  *
19100139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
19111cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
19129d998b4fSMichal Hocko  *
19139d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
19141cfb419bSKAMEZAWA Hiroyuki  */
19151cfb419bSKAMEZAWA Hiroyuki 
19169d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
19173eb4140fSWu Fengguang 				     struct list_head *list,
19182bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
19193eb4140fSWu Fengguang 				     enum lru_list lru)
19203eb4140fSWu Fengguang {
1921599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19223eb4140fSWu Fengguang 	struct page *page;
1923fa9add64SHugh Dickins 	int nr_pages;
19249d998b4fSMichal Hocko 	int nr_moved = 0;
19253eb4140fSWu Fengguang 
19263eb4140fSWu Fengguang 	while (!list_empty(list)) {
19273eb4140fSWu Fengguang 		page = lru_to_page(list);
1928599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
19293eb4140fSWu Fengguang 
1930309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
19313eb4140fSWu Fengguang 		SetPageLRU(page);
19323eb4140fSWu Fengguang 
1933fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1934599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1935925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
19363eb4140fSWu Fengguang 
19372bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
19382bcf8879SHugh Dickins 			__ClearPageLRU(page);
19392bcf8879SHugh Dickins 			__ClearPageActive(page);
1940fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
19412bcf8879SHugh Dickins 
19422bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1943599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1944747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
19452bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1946599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
19472bcf8879SHugh Dickins 			} else
19482bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
19499d998b4fSMichal Hocko 		} else {
19509d998b4fSMichal Hocko 			nr_moved += nr_pages;
19513eb4140fSWu Fengguang 		}
19523eb4140fSWu Fengguang 	}
19539d5e6a9fSHugh Dickins 
19542262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
1955f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
19562262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
19572262185cSRoman Gushchin 				   nr_moved);
19582262185cSRoman Gushchin 	}
19599d998b4fSMichal Hocko 
19609d998b4fSMichal Hocko 	return nr_moved;
19613eb4140fSWu Fengguang }
19621cfb419bSKAMEZAWA Hiroyuki 
1963f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19641a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1965f16015fbSJohannes Weiner 			       struct scan_control *sc,
19669e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19671cfb419bSKAMEZAWA Hiroyuki {
196844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1969f626012dSHugh Dickins 	unsigned long nr_scanned;
19706fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19711cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19728cab4754SWu Fengguang 	LIST_HEAD(l_active);
1973b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19741cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19751a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19769d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
19779d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
1978f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19793cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1980599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19811cfb419bSKAMEZAWA Hiroyuki 
19821da177e4SLinus Torvalds 	lru_add_drain();
1983f80c0673SMinchan Kim 
1984f80c0673SMinchan Kim 	if (!sc->may_unmap)
198561317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1986f80c0673SMinchan Kim 
1987599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1988925b7673SJohannes Weiner 
19895dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19905dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
199189b5fae5SJohannes Weiner 
1992599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1993b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19941cfb419bSKAMEZAWA Hiroyuki 
1995599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19962262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
19979d5e6a9fSHugh Dickins 
1998599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19991da177e4SLinus Torvalds 
20001da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20011da177e4SLinus Torvalds 		cond_resched();
20021da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20031da177e4SLinus Torvalds 		list_del(&page->lru);
20047e9cd484SRik van Riel 
200539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2006894bc310SLee Schermerhorn 			putback_lru_page(page);
2007894bc310SLee Schermerhorn 			continue;
2008894bc310SLee Schermerhorn 		}
2009894bc310SLee Schermerhorn 
2010cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2011cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2012cc715d99SMel Gorman 				if (page_has_private(page))
2013cc715d99SMel Gorman 					try_to_release_page(page, 0);
2014cc715d99SMel Gorman 				unlock_page(page);
2015cc715d99SMel Gorman 			}
2016cc715d99SMel Gorman 		}
2017cc715d99SMel Gorman 
2018c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2019c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20209992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20218cab4754SWu Fengguang 			/*
20228cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20238cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20248cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20258cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20268cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20278cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20288cab4754SWu Fengguang 			 * so we ignore them here.
20298cab4754SWu Fengguang 			 */
203041e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20318cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20328cab4754SWu Fengguang 				continue;
20338cab4754SWu Fengguang 			}
20348cab4754SWu Fengguang 		}
20357e9cd484SRik van Riel 
20365205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20371da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20381da177e4SLinus Torvalds 	}
20391da177e4SLinus Torvalds 
2040b555749aSAndrew Morton 	/*
20418cab4754SWu Fengguang 	 * Move pages back to the lru list.
2042b555749aSAndrew Morton 	 */
2043599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
20444f98a2feSRik van Riel 	/*
20458cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
20468cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
20478cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
20487c0db9e9SJerome Marchand 	 * get_scan_count.
2049556adecbSRik van Riel 	 */
2050b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2051556adecbSRik van Riel 
20529d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
20539d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
2054599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2055599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20562bcf8879SHugh Dickins 
2057747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
20582d4894b5SMel Gorman 	free_unref_page_list(&l_hold);
20599d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
20609d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
20611da177e4SLinus Torvalds }
20621da177e4SLinus Torvalds 
206359dc76b0SRik van Riel /*
206459dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
206559dc76b0SRik van Riel  * to do too much work.
206614797e23SKOSAKI Motohiro  *
206759dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
206859dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
206959dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
207059dc76b0SRik van Riel  *
207159dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
207259dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
207359dc76b0SRik van Riel  *
20742a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
20752a2e4885SJohannes Weiner  *
207659dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
20773a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
207859dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
207959dc76b0SRik van Riel  *
208059dc76b0SRik van Riel  * total     target    max
208159dc76b0SRik van Riel  * memory    ratio     inactive
208259dc76b0SRik van Riel  * -------------------------------------
208359dc76b0SRik van Riel  *   10MB       1         5MB
208459dc76b0SRik van Riel  *  100MB       1        50MB
208559dc76b0SRik van Riel  *    1GB       3       250MB
208659dc76b0SRik van Riel  *   10GB      10       0.9GB
208759dc76b0SRik van Riel  *  100GB      31         3GB
208859dc76b0SRik van Riel  *    1TB     101        10GB
208959dc76b0SRik van Riel  *   10TB     320        32GB
209014797e23SKOSAKI Motohiro  */
2091f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
20922a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
20932a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
209414797e23SKOSAKI Motohiro {
2095fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
20962a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20972a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
20982a2e4885SJohannes Weiner 	unsigned long inactive, active;
20992a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
21002a2e4885SJohannes Weiner 	unsigned long refaults;
210159dc76b0SRik van Riel 	unsigned long gb;
210259dc76b0SRik van Riel 
210374e3f3c3SMinchan Kim 	/*
210474e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
210574e3f3c3SMinchan Kim 	 * is pointless.
210674e3f3c3SMinchan Kim 	 */
210759dc76b0SRik van Riel 	if (!file && !total_swap_pages)
210842e2e457SYaowei Bai 		return false;
210974e3f3c3SMinchan Kim 
2110fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2111fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2112f8d1a311SMel Gorman 
21132a2e4885SJohannes Weiner 	if (memcg)
2114ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
21152a2e4885SJohannes Weiner 	else
21162a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
21172a2e4885SJohannes Weiner 
21182a2e4885SJohannes Weiner 	/*
21192a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
21202a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
21212a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
21222a2e4885SJohannes Weiner 	 */
21232a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
21242a2e4885SJohannes Weiner 		inactive_ratio = 0;
21252a2e4885SJohannes Weiner 	} else {
212659dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
212759dc76b0SRik van Riel 		if (gb)
212859dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2129b39415b2SRik van Riel 		else
213059dc76b0SRik van Riel 			inactive_ratio = 1;
21312a2e4885SJohannes Weiner 	}
213259dc76b0SRik van Riel 
21332a2e4885SJohannes Weiner 	if (actual_reclaim)
21342a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2135fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2136fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2137fd538803SMichal Hocko 			inactive_ratio, file);
2138fd538803SMichal Hocko 
213959dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2140b39415b2SRik van Riel }
2141b39415b2SRik van Riel 
21424f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
21432a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
21442a2e4885SJohannes Weiner 				 struct scan_control *sc)
2145b69408e8SChristoph Lameter {
2146b39415b2SRik van Riel 	if (is_active_lru(lru)) {
21472a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
21482a2e4885SJohannes Weiner 					 memcg, sc, true))
21491a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2150556adecbSRik van Riel 		return 0;
2151556adecbSRik van Riel 	}
2152556adecbSRik van Riel 
21531a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2154b69408e8SChristoph Lameter }
2155b69408e8SChristoph Lameter 
21569a265114SJohannes Weiner enum scan_balance {
21579a265114SJohannes Weiner 	SCAN_EQUAL,
21589a265114SJohannes Weiner 	SCAN_FRACT,
21599a265114SJohannes Weiner 	SCAN_ANON,
21609a265114SJohannes Weiner 	SCAN_FILE,
21619a265114SJohannes Weiner };
21629a265114SJohannes Weiner 
21631da177e4SLinus Torvalds /*
21644f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
21654f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
21664f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
21674f98a2feSRik van Riel  * onto the active list instead of evict.
21684f98a2feSRik van Riel  *
2169be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2170be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
21714f98a2feSRik van Riel  */
217233377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
21736b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
21746b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
21754f98a2feSRik van Riel {
217633377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
217790126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
21789a265114SJohannes Weiner 	u64 fraction[2];
21799a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2180599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21819a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
21829a265114SJohannes Weiner 	enum scan_balance scan_balance;
21830bf1457fSJohannes Weiner 	unsigned long anon, file;
21849a265114SJohannes Weiner 	unsigned long ap, fp;
21859a265114SJohannes Weiner 	enum lru_list lru;
218676a33fc3SShaohua Li 
218776a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2188d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21899a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
219076a33fc3SShaohua Li 		goto out;
219176a33fc3SShaohua Li 	}
21924f98a2feSRik van Riel 
219310316b31SJohannes Weiner 	/*
219410316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
219510316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
219610316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
219710316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
219810316b31SJohannes Weiner 	 * too expensive.
219910316b31SJohannes Weiner 	 */
220002695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
22019a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
220210316b31SJohannes Weiner 		goto out;
220310316b31SJohannes Weiner 	}
220410316b31SJohannes Weiner 
220510316b31SJohannes Weiner 	/*
220610316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
220710316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
220810316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
220910316b31SJohannes Weiner 	 */
221002695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22119a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
221210316b31SJohannes Weiner 		goto out;
221310316b31SJohannes Weiner 	}
221410316b31SJohannes Weiner 
221511d16c25SJohannes Weiner 	/*
221662376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
221762376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
221862376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
221962376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
222062376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
222162376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
222262376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
222362376251SJohannes Weiner 	 */
222462376251SJohannes Weiner 	if (global_reclaim(sc)) {
2225599d0c95SMel Gorman 		unsigned long pgdatfile;
2226599d0c95SMel Gorman 		unsigned long pgdatfree;
2227599d0c95SMel Gorman 		int z;
2228599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
222962376251SJohannes Weiner 
2230599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2231599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2232599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
22332ab051e1SJerome Marchand 
2234599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2235599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
22366aa303deSMel Gorman 			if (!managed_zone(zone))
2237599d0c95SMel Gorman 				continue;
2238599d0c95SMel Gorman 
2239599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2240599d0c95SMel Gorman 		}
2241599d0c95SMel Gorman 
2242599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
224306226226SDavid Rientjes 			/*
224406226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
224506226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
224606226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
224706226226SDavid Rientjes 			 */
224806226226SDavid Rientjes 			if (!inactive_list_is_low(lruvec, false, memcg, sc, false) &&
224906226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
225006226226SDavid Rientjes 					>> sc->priority) {
225162376251SJohannes Weiner 				scan_balance = SCAN_ANON;
225262376251SJohannes Weiner 				goto out;
225362376251SJohannes Weiner 			}
225462376251SJohannes Weiner 		}
225506226226SDavid Rientjes 	}
225662376251SJohannes Weiner 
225762376251SJohannes Weiner 	/*
2258316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2259316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2260316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2261316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2262316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2263316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2264316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2265e9868505SRik van Riel 	 */
22662a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
226771ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
22689a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2269e9868505SRik van Riel 		goto out;
22704f98a2feSRik van Riel 	}
22714f98a2feSRik van Riel 
22729a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22739a265114SJohannes Weiner 
22744f98a2feSRik van Riel 	/*
227558c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
227658c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
227758c37f6eSKOSAKI Motohiro 	 */
227802695175SJohannes Weiner 	anon_prio = swappiness;
227975b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
228058c37f6eSKOSAKI Motohiro 
228158c37f6eSKOSAKI Motohiro 	/*
22824f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22834f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22844f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22854f98a2feSRik van Riel 	 *
22864f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22874f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22884f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22894f98a2feSRik van Riel 	 *
22904f98a2feSRik van Riel 	 * anon in [0], file in [1]
22914f98a2feSRik van Riel 	 */
22922ab051e1SJerome Marchand 
2293fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2294fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2295fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2296fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
22972ab051e1SJerome Marchand 
2298599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
229958c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
23006e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
23016e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
23024f98a2feSRik van Riel 	}
23034f98a2feSRik van Riel 
23046e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
23056e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
23066e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
23074f98a2feSRik van Riel 	}
23084f98a2feSRik van Riel 
23094f98a2feSRik van Riel 	/*
231000d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
231100d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
231200d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
23134f98a2feSRik van Riel 	 */
2314fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
23156e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
23164f98a2feSRik van Riel 
2317fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
23186e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2319599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
23204f98a2feSRik van Riel 
232176a33fc3SShaohua Li 	fraction[0] = ap;
232276a33fc3SShaohua Li 	fraction[1] = fp;
232376a33fc3SShaohua Li 	denominator = ap + fp + 1;
232476a33fc3SShaohua Li out:
23256b4f7799SJohannes Weiner 	*lru_pages = 0;
23264111304dSHugh Dickins 	for_each_evictable_lru(lru) {
23274111304dSHugh Dickins 		int file = is_file_lru(lru);
2328d778df51SJohannes Weiner 		unsigned long size;
232976a33fc3SShaohua Li 		unsigned long scan;
233076a33fc3SShaohua Li 
233171ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2332d778df51SJohannes Weiner 		scan = size >> sc->priority;
2333688035f7SJohannes Weiner 		/*
2334688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2335688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2336688035f7SJohannes Weiner 		 */
2337688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2338d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
23399a265114SJohannes Weiner 
23409a265114SJohannes Weiner 		switch (scan_balance) {
23419a265114SJohannes Weiner 		case SCAN_EQUAL:
23429a265114SJohannes Weiner 			/* Scan lists relative to size */
23439a265114SJohannes Weiner 			break;
23449a265114SJohannes Weiner 		case SCAN_FRACT:
23459a265114SJohannes Weiner 			/*
23469a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
23479a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
23489a265114SJohannes Weiner 			 */
23496f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
23506f04f48dSSuleiman Souhlal 					 denominator);
23519a265114SJohannes Weiner 			break;
23529a265114SJohannes Weiner 		case SCAN_FILE:
23539a265114SJohannes Weiner 		case SCAN_ANON:
23549a265114SJohannes Weiner 			/* Scan one type exclusively */
23556b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
23566b4f7799SJohannes Weiner 				size = 0;
23579a265114SJohannes Weiner 				scan = 0;
23586b4f7799SJohannes Weiner 			}
23599a265114SJohannes Weiner 			break;
23609a265114SJohannes Weiner 		default:
23619a265114SJohannes Weiner 			/* Look ma, no brain */
23629a265114SJohannes Weiner 			BUG();
23639a265114SJohannes Weiner 		}
23646b4f7799SJohannes Weiner 
23656b4f7799SJohannes Weiner 		*lru_pages += size;
23664111304dSHugh Dickins 		nr[lru] = scan;
236776a33fc3SShaohua Li 	}
23686e08a369SWu Fengguang }
23694f98a2feSRik van Riel 
23709b4f98cdSJohannes Weiner /*
2371a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23729b4f98cdSJohannes Weiner  */
2373a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23746b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23759b4f98cdSJohannes Weiner {
2376ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23779b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2378e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23799b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23809b4f98cdSJohannes Weiner 	enum lru_list lru;
23819b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23829b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23839b4f98cdSJohannes Weiner 	struct blk_plug plug;
23841a501907SMel Gorman 	bool scan_adjusted;
23859b4f98cdSJohannes Weiner 
238633377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23879b4f98cdSJohannes Weiner 
2388e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2389e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2390e82e0561SMel Gorman 
23911a501907SMel Gorman 	/*
23921a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23931a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23941a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23951a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23961a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23971a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23981a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23991a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
24001a501907SMel Gorman 	 * dropped to zero at the first pass.
24011a501907SMel Gorman 	 */
24021a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
24031a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
24041a501907SMel Gorman 
24059b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
24069b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
24079b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2408e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2409e82e0561SMel Gorman 		unsigned long nr_scanned;
2410e82e0561SMel Gorman 
24119b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
24129b4f98cdSJohannes Weiner 			if (nr[lru]) {
24139b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
24149b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
24159b4f98cdSJohannes Weiner 
24169b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
24172a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
24189b4f98cdSJohannes Weiner 			}
24199b4f98cdSJohannes Weiner 		}
2420e82e0561SMel Gorman 
2421bd041733SMichal Hocko 		cond_resched();
2422bd041733SMichal Hocko 
2423e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2424e82e0561SMel Gorman 			continue;
2425e82e0561SMel Gorman 
24269b4f98cdSJohannes Weiner 		/*
2427e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
24281a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2429e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2430e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2431e82e0561SMel Gorman 		 * proportional to the original scan target.
2432e82e0561SMel Gorman 		 */
2433e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2434e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2435e82e0561SMel Gorman 
24361a501907SMel Gorman 		/*
24371a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
24381a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
24391a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
24401a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
24411a501907SMel Gorman 		 */
24421a501907SMel Gorman 		if (!nr_file || !nr_anon)
24431a501907SMel Gorman 			break;
24441a501907SMel Gorman 
2445e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2446e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2447e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2448e82e0561SMel Gorman 			lru = LRU_BASE;
2449e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2450e82e0561SMel Gorman 		} else {
2451e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2452e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2453e82e0561SMel Gorman 			lru = LRU_FILE;
2454e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2455e82e0561SMel Gorman 		}
2456e82e0561SMel Gorman 
2457e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2458e82e0561SMel Gorman 		nr[lru] = 0;
2459e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2460e82e0561SMel Gorman 
2461e82e0561SMel Gorman 		/*
2462e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2463e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2464e82e0561SMel Gorman 		 */
2465e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2466e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2467e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2468e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2469e82e0561SMel Gorman 
2470e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2471e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2472e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2473e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2474e82e0561SMel Gorman 
2475e82e0561SMel Gorman 		scan_adjusted = true;
24769b4f98cdSJohannes Weiner 	}
24779b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24789b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24799b4f98cdSJohannes Weiner 
24809b4f98cdSJohannes Weiner 	/*
24819b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24829b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24839b4f98cdSJohannes Weiner 	 */
24842a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
24859b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24869b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24879b4f98cdSJohannes Weiner }
24889b4f98cdSJohannes Weiner 
248923b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24909e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
249123b9da55SMel Gorman {
2492d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
249323b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24949e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
249523b9da55SMel Gorman 		return true;
249623b9da55SMel Gorman 
249723b9da55SMel Gorman 	return false;
249823b9da55SMel Gorman }
249923b9da55SMel Gorman 
25004f98a2feSRik van Riel /*
250123b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
250223b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
250323b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
250423b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
250523b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
25063e7d3449SMel Gorman  */
2507a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
25083e7d3449SMel Gorman 					unsigned long nr_reclaimed,
25093e7d3449SMel Gorman 					unsigned long nr_scanned,
25103e7d3449SMel Gorman 					struct scan_control *sc)
25113e7d3449SMel Gorman {
25123e7d3449SMel Gorman 	unsigned long pages_for_compaction;
25133e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2514a9dd0a83SMel Gorman 	int z;
25153e7d3449SMel Gorman 
25163e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
25179e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
25183e7d3449SMel Gorman 		return false;
25193e7d3449SMel Gorman 
25202876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2521dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
25223e7d3449SMel Gorman 		/*
2523dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
25242876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
25252876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2526dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
25273e7d3449SMel Gorman 		 */
25283e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
25293e7d3449SMel Gorman 			return false;
25302876592fSMel Gorman 	} else {
25312876592fSMel Gorman 		/*
2532dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
25332876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
25342876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
25352876592fSMel Gorman 		 * pages that were scanned. This will return to the
25362876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
25372876592fSMel Gorman 		 * the resulting allocation attempt fails
25382876592fSMel Gorman 		 */
25392876592fSMel Gorman 		if (!nr_reclaimed)
25402876592fSMel Gorman 			return false;
25412876592fSMel Gorman 	}
25423e7d3449SMel Gorman 
25433e7d3449SMel Gorman 	/*
25443e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
25453e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
25463e7d3449SMel Gorman 	 */
25479861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2548a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2549ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2550a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
25513e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
25523e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
25533e7d3449SMel Gorman 		return true;
25543e7d3449SMel Gorman 
25553e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2556a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2557a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25586aa303deSMel Gorman 		if (!managed_zone(zone))
2559a9dd0a83SMel Gorman 			continue;
2560a9dd0a83SMel Gorman 
2561a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2562cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25633e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25643e7d3449SMel Gorman 			return false;
25653e7d3449SMel Gorman 		default:
2566a9dd0a83SMel Gorman 			/* check next zone */
2567a9dd0a83SMel Gorman 			;
25683e7d3449SMel Gorman 		}
25693e7d3449SMel Gorman 	}
2570a9dd0a83SMel Gorman 	return true;
2571a9dd0a83SMel Gorman }
25723e7d3449SMel Gorman 
2573970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2574f16015fbSJohannes Weiner {
2575cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25769b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25772344d7e4SJohannes Weiner 	bool reclaimable = false;
25789b4f98cdSJohannes Weiner 
25799b4f98cdSJohannes Weiner 	do {
25805660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25815660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2582ef8f2327SMel Gorman 			.pgdat = pgdat,
25839e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25845660048cSJohannes Weiner 		};
2585a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2586694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25875660048cSJohannes Weiner 
25889b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25899b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25909b4f98cdSJohannes Weiner 
2591694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2592694fbc0fSAndrew Morton 		do {
25936b4f7799SJohannes Weiner 			unsigned long lru_pages;
25948e8ae645SJohannes Weiner 			unsigned long reclaimed;
2595cb731d6cSVladimir Davydov 			unsigned long scanned;
25969b4f98cdSJohannes Weiner 
2597241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2598d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2599d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2600241994edSJohannes Weiner 					continue;
2601d6622f63SYisheng Xie 				}
260231176c78SJohannes Weiner 				mem_cgroup_event(memcg, MEMCG_LOW);
2603241994edSJohannes Weiner 			}
2604241994edSJohannes Weiner 
26058e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2606cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2607a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2608a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2609f9be23d6SKonstantin Khlebnikov 
2610b5afba29SVladimir Davydov 			if (memcg)
2611a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
26129092c71bSJosef Bacik 					    memcg, sc->priority);
2613cb731d6cSVladimir Davydov 
26148e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
26158e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
26168e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
26178e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
26188e8ae645SJohannes Weiner 
26195660048cSJohannes Weiner 			/*
2620a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2621a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2622a9dd0a83SMel Gorman 			 * node.
2623a394cb8eSMichal Hocko 			 *
2624a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2625a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2626a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2627a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
26285660048cSJohannes Weiner 			 */
2629a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2630a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
26315660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
26325660048cSJohannes Weiner 				break;
26335660048cSJohannes Weiner 			}
2634241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
263570ddf637SAnton Vorontsov 
2636b2e18757SMel Gorman 		if (global_reclaim(sc))
2637a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
26389092c71bSJosef Bacik 				    sc->priority);
26396b4f7799SJohannes Weiner 
26406b4f7799SJohannes Weiner 		if (reclaim_state) {
2641cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
26426b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
26436b4f7799SJohannes Weiner 		}
26446b4f7799SJohannes Weiner 
26458e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
26468e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
264770ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
264870ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
264970ddf637SAnton Vorontsov 
26502344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
26512344d7e4SJohannes Weiner 			reclaimable = true;
26522344d7e4SJohannes Weiner 
2653a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
26549b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
26552344d7e4SJohannes Weiner 
2656c73322d0SJohannes Weiner 	/*
2657c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2658c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2659c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2660c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2661c73322d0SJohannes Weiner 	 */
2662c73322d0SJohannes Weiner 	if (reclaimable)
2663c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2664c73322d0SJohannes Weiner 
26652344d7e4SJohannes Weiner 	return reclaimable;
2666f16015fbSJohannes Weiner }
2667f16015fbSJohannes Weiner 
266853853e2dSVlastimil Babka /*
2669fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2670fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2671fdd4c614SVlastimil Babka  * should reclaim first.
267253853e2dSVlastimil Babka  */
26734f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2674fe4b1b24SMel Gorman {
267531483b6aSMel Gorman 	unsigned long watermark;
2676fdd4c614SVlastimil Babka 	enum compact_result suitable;
2677fe4b1b24SMel Gorman 
2678fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2679fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2680fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2681fdd4c614SVlastimil Babka 		return true;
2682fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2683fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2684fe4b1b24SMel Gorman 		return false;
2685fe4b1b24SMel Gorman 
2686fdd4c614SVlastimil Babka 	/*
2687fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2688fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2689fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2690fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2691fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2692fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2693fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2694fdd4c614SVlastimil Babka 	 */
2695fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2696fdd4c614SVlastimil Babka 
2697fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2698fe4b1b24SMel Gorman }
2699fe4b1b24SMel Gorman 
27001da177e4SLinus Torvalds /*
27011da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
27021da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
27031da177e4SLinus Torvalds  * request.
27041da177e4SLinus Torvalds  *
27051da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
27061da177e4SLinus Torvalds  * scan then give up on it.
27071da177e4SLinus Torvalds  */
27080a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
27091da177e4SLinus Torvalds {
2710dd1a239fSMel Gorman 	struct zoneref *z;
271154a6eb5cSMel Gorman 	struct zone *zone;
27120608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
27130608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2714619d0d76SWeijie Yang 	gfp_t orig_mask;
271579dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
27161cfb419bSKAMEZAWA Hiroyuki 
2717cc715d99SMel Gorman 	/*
2718cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2719cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2720cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2721cc715d99SMel Gorman 	 */
2722619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2723b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2724cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
27254f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2726b2e18757SMel Gorman 	}
2727cc715d99SMel Gorman 
2728d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2729b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2730b2e18757SMel Gorman 		/*
27311cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
27321cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
27331cfb419bSKAMEZAWA Hiroyuki 		 */
273489b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2735344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2736344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
27371da177e4SLinus Torvalds 				continue;
273865ec02cbSVladimir Davydov 
2739e0887c19SRik van Riel 			/*
2740e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2741e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2742e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2743e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2744e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2745c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2746c7cfa37bSCopot Alexandru 			 * page allocations.
2747e0887c19SRik van Riel 			 */
27480b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
27490b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
27504f588331SMel Gorman 			    compaction_ready(zone, sc)) {
27510b06496aSJohannes Weiner 				sc->compaction_ready = true;
2752e0887c19SRik van Riel 				continue;
2753e0887c19SRik van Riel 			}
27540b06496aSJohannes Weiner 
27550608f43dSAndrew Morton 			/*
275679dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
275779dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
275879dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
275979dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
276079dafcdcSMel Gorman 			 */
276179dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
276279dafcdcSMel Gorman 				continue;
276379dafcdcSMel Gorman 
276479dafcdcSMel Gorman 			/*
27650608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27660608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27670608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27680608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27690608f43dSAndrew Morton 			 */
27700608f43dSAndrew Morton 			nr_soft_scanned = 0;
2771ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27720608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27730608f43dSAndrew Morton 						&nr_soft_scanned);
27740608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27750608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2776ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2777ac34a1a3SKAMEZAWA Hiroyuki 		}
2778d149e3b2SYing Han 
277979dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
278079dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
278179dafcdcSMel Gorman 			continue;
278279dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2783970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27841da177e4SLinus Torvalds 	}
2785e0c23279SMel Gorman 
278665ec02cbSVladimir Davydov 	/*
2787619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2788619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2789619d0d76SWeijie Yang 	 */
2790619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
27911da177e4SLinus Torvalds }
27921da177e4SLinus Torvalds 
27932a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
27942a2e4885SJohannes Weiner {
27952a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
27962a2e4885SJohannes Weiner 
27972a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
27982a2e4885SJohannes Weiner 	do {
27992a2e4885SJohannes Weiner 		unsigned long refaults;
28002a2e4885SJohannes Weiner 		struct lruvec *lruvec;
28012a2e4885SJohannes Weiner 
28022a2e4885SJohannes Weiner 		if (memcg)
2803ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
28042a2e4885SJohannes Weiner 		else
28052a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
28062a2e4885SJohannes Weiner 
28072a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
28082a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
28092a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
28102a2e4885SJohannes Weiner }
28112a2e4885SJohannes Weiner 
28121da177e4SLinus Torvalds /*
28131da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
28141da177e4SLinus Torvalds  *
28151da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
28161da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
28171da177e4SLinus Torvalds  *
28181da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
28191da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
28205b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
28215b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
28225b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
28235b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2824a41f24eaSNishanth Aravamudan  *
2825a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2826a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
28271da177e4SLinus Torvalds  */
2828dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
28293115cd91SVladimir Davydov 					  struct scan_control *sc)
28301da177e4SLinus Torvalds {
2831241994edSJohannes Weiner 	int initial_priority = sc->priority;
28322a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
28332a2e4885SJohannes Weiner 	struct zoneref *z;
28342a2e4885SJohannes Weiner 	struct zone *zone;
2835241994edSJohannes Weiner retry:
2836873b4771SKeika Kobayashi 	delayacct_freepages_start();
2837873b4771SKeika Kobayashi 
283889b5fae5SJohannes Weiner 	if (global_reclaim(sc))
28397cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
28401da177e4SLinus Torvalds 
28419e3b2f8cSKonstantin Khlebnikov 	do {
284270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
284370ddf637SAnton Vorontsov 				sc->priority);
284466e1707bSBalbir Singh 		sc->nr_scanned = 0;
28450a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2846e0c23279SMel Gorman 
2847bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
28480b06496aSJohannes Weiner 			break;
28490b06496aSJohannes Weiner 
28500b06496aSJohannes Weiner 		if (sc->compaction_ready)
28510b06496aSJohannes Weiner 			break;
28521da177e4SLinus Torvalds 
28531da177e4SLinus Torvalds 		/*
28540e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
28550e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
28560e50ce3bSMinchan Kim 		 */
28570e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
28580e50ce3bSMinchan Kim 			sc->may_writepage = 1;
28590b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2860bb21c7ceSKOSAKI Motohiro 
28612a2e4885SJohannes Weiner 	last_pgdat = NULL;
28622a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
28632a2e4885SJohannes Weiner 					sc->nodemask) {
28642a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
28652a2e4885SJohannes Weiner 			continue;
28662a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
28672a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
28682a2e4885SJohannes Weiner 	}
28692a2e4885SJohannes Weiner 
2870873b4771SKeika Kobayashi 	delayacct_freepages_end();
2871873b4771SKeika Kobayashi 
2872bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2873bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2874bb21c7ceSKOSAKI Motohiro 
28750cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
28760b06496aSJohannes Weiner 	if (sc->compaction_ready)
28777335084dSMel Gorman 		return 1;
28787335084dSMel Gorman 
2879241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2880d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
2881241994edSJohannes Weiner 		sc->priority = initial_priority;
2882d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
2883d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
2884241994edSJohannes Weiner 		goto retry;
2885241994edSJohannes Weiner 	}
2886241994edSJohannes Weiner 
2887bb21c7ceSKOSAKI Motohiro 	return 0;
28881da177e4SLinus Torvalds }
28891da177e4SLinus Torvalds 
2890c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
28915515061dSMel Gorman {
28925515061dSMel Gorman 	struct zone *zone;
28935515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
28945515061dSMel Gorman 	unsigned long free_pages = 0;
28955515061dSMel Gorman 	int i;
28965515061dSMel Gorman 	bool wmark_ok;
28975515061dSMel Gorman 
2898c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
2899c73322d0SJohannes Weiner 		return true;
2900c73322d0SJohannes Weiner 
29015515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
29025515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2903d450abd8SJohannes Weiner 		if (!managed_zone(zone))
2904d450abd8SJohannes Weiner 			continue;
2905d450abd8SJohannes Weiner 
2906d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
2907675becceSMel Gorman 			continue;
2908675becceSMel Gorman 
29095515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
29105515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
29115515061dSMel Gorman 	}
29125515061dSMel Gorman 
2913675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2914675becceSMel Gorman 	if (!pfmemalloc_reserve)
2915675becceSMel Gorman 		return true;
2916675becceSMel Gorman 
29175515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
29185515061dSMel Gorman 
29195515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
29205515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
292138087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
29225515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
29235515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
29245515061dSMel Gorman 	}
29255515061dSMel Gorman 
29265515061dSMel Gorman 	return wmark_ok;
29275515061dSMel Gorman }
29285515061dSMel Gorman 
29295515061dSMel Gorman /*
29305515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
29315515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
29325515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
293350694c28SMel Gorman  * when the low watermark is reached.
293450694c28SMel Gorman  *
293550694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
293650694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
29375515061dSMel Gorman  */
293850694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
29395515061dSMel Gorman 					nodemask_t *nodemask)
29405515061dSMel Gorman {
2941675becceSMel Gorman 	struct zoneref *z;
29425515061dSMel Gorman 	struct zone *zone;
2943675becceSMel Gorman 	pg_data_t *pgdat = NULL;
29445515061dSMel Gorman 
29455515061dSMel Gorman 	/*
29465515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
29475515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
29485515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
29495515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
29505515061dSMel Gorman 	 * processes to block on log_wait_commit().
29515515061dSMel Gorman 	 */
29525515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
295350694c28SMel Gorman 		goto out;
295450694c28SMel Gorman 
295550694c28SMel Gorman 	/*
295650694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
295750694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
295850694c28SMel Gorman 	 */
295950694c28SMel Gorman 	if (fatal_signal_pending(current))
296050694c28SMel Gorman 		goto out;
29615515061dSMel Gorman 
2962675becceSMel Gorman 	/*
2963675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2964675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2965675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2966675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2967675becceSMel Gorman 	 *
2968675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2969675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2970675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2971675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2972675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2973675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2974675becceSMel Gorman 	 * should make reasonable progress.
2975675becceSMel Gorman 	 */
2976675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
297717636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2978675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2979675becceSMel Gorman 			continue;
2980675becceSMel Gorman 
2981675becceSMel Gorman 		/* Throttle based on the first usable node */
29825515061dSMel Gorman 		pgdat = zone->zone_pgdat;
2983c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
298450694c28SMel Gorman 			goto out;
2985675becceSMel Gorman 		break;
2986675becceSMel Gorman 	}
2987675becceSMel Gorman 
2988675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
2989675becceSMel Gorman 	if (!pgdat)
2990675becceSMel Gorman 		goto out;
29915515061dSMel Gorman 
299268243e76SMel Gorman 	/* Account for the throttling */
299368243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
299468243e76SMel Gorman 
29955515061dSMel Gorman 	/*
29965515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
29975515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
29985515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
29995515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
30005515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
30015515061dSMel Gorman 	 * second before continuing.
30025515061dSMel Gorman 	 */
30035515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
30045515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3005c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
300650694c28SMel Gorman 
300750694c28SMel Gorman 		goto check_pending;
30085515061dSMel Gorman 	}
30095515061dSMel Gorman 
30105515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
30115515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3012c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
301350694c28SMel Gorman 
301450694c28SMel Gorman check_pending:
301550694c28SMel Gorman 	if (fatal_signal_pending(current))
301650694c28SMel Gorman 		return true;
301750694c28SMel Gorman 
301850694c28SMel Gorman out:
301950694c28SMel Gorman 	return false;
30205515061dSMel Gorman }
30215515061dSMel Gorman 
3022dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3023327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
302466e1707bSBalbir Singh {
302533906bc5SMel Gorman 	unsigned long nr_reclaimed;
302666e1707bSBalbir Singh 	struct scan_control sc = {
302722fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3028f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3029b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3030ee814fe2SJohannes Weiner 		.order = order,
3031ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3032ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3033ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3034a6dc60f8SJohannes Weiner 		.may_unmap = 1,
30352e2e4259SKOSAKI Motohiro 		.may_swap = 1,
303666e1707bSBalbir Singh 	};
303766e1707bSBalbir Singh 
30385515061dSMel Gorman 	/*
303950694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
304050694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
304150694c28SMel Gorman 	 * point.
30425515061dSMel Gorman 	 */
3043f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
30445515061dSMel Gorman 		return 1;
30455515061dSMel Gorman 
304633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
304733906bc5SMel Gorman 				sc.may_writepage,
3048f2f43e56SNick Desaulniers 				sc.gfp_mask,
3049e5146b12SMel Gorman 				sc.reclaim_idx);
305033906bc5SMel Gorman 
30513115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
305233906bc5SMel Gorman 
305333906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
305433906bc5SMel Gorman 
305533906bc5SMel Gorman 	return nr_reclaimed;
305666e1707bSBalbir Singh }
305766e1707bSBalbir Singh 
3058c255a458SAndrew Morton #ifdef CONFIG_MEMCG
305966e1707bSBalbir Singh 
3060a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
30614e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3062ef8f2327SMel Gorman 						pg_data_t *pgdat,
30630ae5e89cSYing Han 						unsigned long *nr_scanned)
30644e416953SBalbir Singh {
30654e416953SBalbir Singh 	struct scan_control sc = {
3066b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3067ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
30684e416953SBalbir Singh 		.may_writepage = !laptop_mode,
30694e416953SBalbir Singh 		.may_unmap = 1,
3070b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
30714e416953SBalbir Singh 		.may_swap = !noswap,
30724e416953SBalbir Singh 	};
30736b4f7799SJohannes Weiner 	unsigned long lru_pages;
30740ae5e89cSYing Han 
30754e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
30764e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3077bdce6d9eSKOSAKI Motohiro 
30789e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3079bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3080e5146b12SMel Gorman 						      sc.gfp_mask,
3081e5146b12SMel Gorman 						      sc.reclaim_idx);
3082bdce6d9eSKOSAKI Motohiro 
30834e416953SBalbir Singh 	/*
30844e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
30854e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3086a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30874e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
30884e416953SBalbir Singh 	 * the priority and make it zero.
30894e416953SBalbir Singh 	 */
3090ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3091bdce6d9eSKOSAKI Motohiro 
3092bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3093bdce6d9eSKOSAKI Motohiro 
30940ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
30954e416953SBalbir Singh 	return sc.nr_reclaimed;
30964e416953SBalbir Singh }
30974e416953SBalbir Singh 
309872835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3099b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
31008c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3101b70a2a21SJohannes Weiner 					   bool may_swap)
310266e1707bSBalbir Singh {
31034e416953SBalbir Singh 	struct zonelist *zonelist;
3104bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3105889976dbSYing Han 	int nid;
3106499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
310766e1707bSBalbir Singh 	struct scan_control sc = {
3108b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
31097dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3110ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3111b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3112ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3113ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
311466e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3115a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3116b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3117a09ed5e0SYing Han 	};
311866e1707bSBalbir Singh 
3119889976dbSYing Han 	/*
3120889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3121889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3122889976dbSYing Han 	 * scan does not need to be the current node.
3123889976dbSYing Han 	 */
312472835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3125889976dbSYing Han 
3126c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3127bdce6d9eSKOSAKI Motohiro 
3128bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3129bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3130e5146b12SMel Gorman 					    sc.gfp_mask,
3131e5146b12SMel Gorman 					    sc.reclaim_idx);
3132bdce6d9eSKOSAKI Motohiro 
3133499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
31343115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3135499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3136bdce6d9eSKOSAKI Motohiro 
3137bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3138bdce6d9eSKOSAKI Motohiro 
3139bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
314066e1707bSBalbir Singh }
314166e1707bSBalbir Singh #endif
314266e1707bSBalbir Singh 
31431d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3144ef8f2327SMel Gorman 				struct scan_control *sc)
3145f16015fbSJohannes Weiner {
3146b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3147b95a2f2dSJohannes Weiner 
3148b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3149b95a2f2dSJohannes Weiner 		return;
3150b95a2f2dSJohannes Weiner 
3151b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3152b95a2f2dSJohannes Weiner 	do {
3153ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3154f16015fbSJohannes Weiner 
31552a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
31561a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
31579e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3158b95a2f2dSJohannes Weiner 
3159b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3160b95a2f2dSJohannes Weiner 	} while (memcg);
3161f16015fbSJohannes Weiner }
3162f16015fbSJohannes Weiner 
3163e716f2ebSMel Gorman /*
3164e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3165e716f2ebSMel Gorman  * and classzone_idx
3166e716f2ebSMel Gorman  */
3167e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
316860cefed4SJohannes Weiner {
3169e716f2ebSMel Gorman 	int i;
3170e716f2ebSMel Gorman 	unsigned long mark = -1;
3171e716f2ebSMel Gorman 	struct zone *zone;
317260cefed4SJohannes Weiner 
3173e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3174e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
31756256c6b4SMel Gorman 
3176e716f2ebSMel Gorman 		if (!managed_zone(zone))
3177e716f2ebSMel Gorman 			continue;
3178e716f2ebSMel Gorman 
3179e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3180e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
31816256c6b4SMel Gorman 			return true;
318260cefed4SJohannes Weiner 	}
318360cefed4SJohannes Weiner 
3184e716f2ebSMel Gorman 	/*
3185e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3186e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3187e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3188e716f2ebSMel Gorman 	 */
3189e716f2ebSMel Gorman 	if (mark == -1)
3190e716f2ebSMel Gorman 		return true;
3191e716f2ebSMel Gorman 
3192e716f2ebSMel Gorman 	return false;
3193e716f2ebSMel Gorman }
3194e716f2ebSMel Gorman 
3195631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3196631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3197631b6e08SMel Gorman {
3198631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3199631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3200631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3201631b6e08SMel Gorman }
3202631b6e08SMel Gorman 
32031741c877SMel Gorman /*
32045515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
32055515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
32065515061dSMel Gorman  *
32075515061dSMel Gorman  * Returns true if kswapd is ready to sleep
32085515061dSMel Gorman  */
3209d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3210f50de2d3SMel Gorman {
32115515061dSMel Gorman 	/*
32129e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3213c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
32149e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
32159e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
32169e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
32179e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
32189e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
32199e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
32209e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
32219e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
32229e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
32235515061dSMel Gorman 	 */
32249e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
32259e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3226f50de2d3SMel Gorman 
3227c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3228c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3229c73322d0SJohannes Weiner 		return true;
3230c73322d0SJohannes Weiner 
3231e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3232631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3233333b0a45SShantanu Goel 		return true;
32341d82de61SMel Gorman 	}
32351d82de61SMel Gorman 
3236333b0a45SShantanu Goel 	return false;
3237f50de2d3SMel Gorman }
3238f50de2d3SMel Gorman 
32391da177e4SLinus Torvalds /*
32401d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
32411d82de61SMel Gorman  * zone that is currently unbalanced.
3242b8e83b94SMel Gorman  *
3243b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3244283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3245283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
324675485363SMel Gorman  */
32471d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3248accf6242SVlastimil Babka 			       struct scan_control *sc)
324975485363SMel Gorman {
32501d82de61SMel Gorman 	struct zone *zone;
32511d82de61SMel Gorman 	int z;
325275485363SMel Gorman 
32531d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
32541d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3255970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
32561d82de61SMel Gorman 		zone = pgdat->node_zones + z;
32576aa303deSMel Gorman 		if (!managed_zone(zone))
32581d82de61SMel Gorman 			continue;
32597c954f6dSMel Gorman 
32601d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
32617c954f6dSMel Gorman 	}
32627c954f6dSMel Gorman 
32631d82de61SMel Gorman 	/*
32641d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
32651d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
32661d82de61SMel Gorman 	 */
3267970a39a3SMel Gorman 	shrink_node(pgdat, sc);
32681d82de61SMel Gorman 
32691d82de61SMel Gorman 	/*
32701d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
32711d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
32721d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
32731d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
32741d82de61SMel Gorman 	 * can direct reclaim/compact.
32751d82de61SMel Gorman 	 */
32769861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
32771d82de61SMel Gorman 		sc->order = 0;
32781d82de61SMel Gorman 
3279b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
328075485363SMel Gorman }
328175485363SMel Gorman 
328275485363SMel Gorman /*
32831d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
32841d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
32851d82de61SMel Gorman  * balanced.
32861da177e4SLinus Torvalds  *
32871d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
32881da177e4SLinus Torvalds  *
32891da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
329041858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
32911d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
32921d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
32931d82de61SMel Gorman  * balanced.
32941da177e4SLinus Torvalds  */
3295accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
32961da177e4SLinus Torvalds {
32971da177e4SLinus Torvalds 	int i;
32980608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
32990608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
33001d82de61SMel Gorman 	struct zone *zone;
3301179e9639SAndrew Morton 	struct scan_control sc = {
3302179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3303ee814fe2SJohannes Weiner 		.order = order,
3304b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3305ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3306a6dc60f8SJohannes Weiner 		.may_unmap = 1,
33072e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3308179e9639SAndrew Morton 	};
3309f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
33101da177e4SLinus Torvalds 
33119e3b2f8cSKonstantin Khlebnikov 	do {
3312c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3313b8e83b94SMel Gorman 		bool raise_priority = true;
3314b8e83b94SMel Gorman 
331584c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
33161da177e4SLinus Torvalds 
331786c79f6bSMel Gorman 		/*
331884c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
331984c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
332084c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
332184c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
332284c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
332384c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
332484c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
332584c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
332686c79f6bSMel Gorman 		 */
332786c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
332886c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
332986c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
33306aa303deSMel Gorman 				if (!managed_zone(zone))
333186c79f6bSMel Gorman 					continue;
333286c79f6bSMel Gorman 
3333970a39a3SMel Gorman 				sc.reclaim_idx = i;
333486c79f6bSMel Gorman 				break;
333586c79f6bSMel Gorman 			}
333686c79f6bSMel Gorman 		}
333786c79f6bSMel Gorman 
333886c79f6bSMel Gorman 		/*
3339e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3340e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3341e716f2ebSMel Gorman 		 * have adjusted it.
334286c79f6bSMel Gorman 		 */
3343e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
33441da177e4SLinus Torvalds 			goto out;
3345e1dbeda6SAndrew Morton 
33461da177e4SLinus Torvalds 		/*
33471d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
33481d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
33491d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
33501d82de61SMel Gorman 		 * about consistent aging.
33511d82de61SMel Gorman 		 */
3352ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
33531d82de61SMel Gorman 
33541d82de61SMel Gorman 		/*
3355b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3356b7ea3c41SMel Gorman 		 * even in laptop mode.
3357b7ea3c41SMel Gorman 		 */
3358047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3359b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3360b7ea3c41SMel Gorman 
33611d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
33621da177e4SLinus Torvalds 		sc.nr_scanned = 0;
33630608f43dSAndrew Morton 		nr_soft_scanned = 0;
3364ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
33651d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
33660608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
33670608f43dSAndrew Morton 
336832a4330dSRik van Riel 		/*
33691d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
33701d82de61SMel Gorman 		 * enough pages are already being scanned that that high
33711d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
337232a4330dSRik van Riel 		 */
3373970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3374b8e83b94SMel Gorman 			raise_priority = false;
3375d7868daeSMel Gorman 
33765515061dSMel Gorman 		/*
33775515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
33785515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
33795515061dSMel Gorman 		 * able to safely make forward progress. Wake them
33805515061dSMel Gorman 		 */
33815515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3382c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3383cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
33845515061dSMel Gorman 
3385b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3386b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3387b8e83b94SMel Gorman 			break;
3388b8e83b94SMel Gorman 
3389b8e83b94SMel Gorman 		/*
3390b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3391b8e83b94SMel Gorman 		 * progress in reclaiming pages
3392b8e83b94SMel Gorman 		 */
3393c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3394c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3395b8e83b94SMel Gorman 			sc.priority--;
33961d82de61SMel Gorman 	} while (sc.priority >= 1);
33971da177e4SLinus Torvalds 
3398c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3399c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3400c73322d0SJohannes Weiner 
3401b8e83b94SMel Gorman out:
34022a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
34030abdee2bSMel Gorman 	/*
34041d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
34051d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
34061d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
34071d82de61SMel Gorman 	 * remain at the higher level.
34080abdee2bSMel Gorman 	 */
34091d82de61SMel Gorman 	return sc.order;
34101da177e4SLinus Torvalds }
34111da177e4SLinus Torvalds 
3412e716f2ebSMel Gorman /*
3413e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3414e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3415e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3416e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3417e716f2ebSMel Gorman  * was recently woke for.
3418e716f2ebSMel Gorman  */
3419e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3420e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3421e716f2ebSMel Gorman {
3422e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3423e716f2ebSMel Gorman 		return classzone_idx;
3424e716f2ebSMel Gorman 
3425e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3426e716f2ebSMel Gorman }
3427e716f2ebSMel Gorman 
342838087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
342938087d9bSMel Gorman 				unsigned int classzone_idx)
3430f0bc0a60SKOSAKI Motohiro {
3431f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3432f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3433f0bc0a60SKOSAKI Motohiro 
3434f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3435f0bc0a60SKOSAKI Motohiro 		return;
3436f0bc0a60SKOSAKI Motohiro 
3437f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3438f0bc0a60SKOSAKI Motohiro 
3439333b0a45SShantanu Goel 	/*
3440333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3441333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3442333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3443333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3444333b0a45SShantanu Goel 	 * succeed.
3445333b0a45SShantanu Goel 	 */
3446d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3447fd901c95SVlastimil Babka 		/*
3448fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3449fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3450fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3451fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3452fd901c95SVlastimil Babka 		 */
3453fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3454fd901c95SVlastimil Babka 
3455fd901c95SVlastimil Babka 		/*
3456fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3457fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3458fd901c95SVlastimil Babka 		 */
345938087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3460fd901c95SVlastimil Babka 
3461f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
346238087d9bSMel Gorman 
346338087d9bSMel Gorman 		/*
346438087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
346538087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
346638087d9bSMel Gorman 		 * the previous request that slept prematurely.
346738087d9bSMel Gorman 		 */
346838087d9bSMel Gorman 		if (remaining) {
3469e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
347038087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
347138087d9bSMel Gorman 		}
347238087d9bSMel Gorman 
3473f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3474f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3475f0bc0a60SKOSAKI Motohiro 	}
3476f0bc0a60SKOSAKI Motohiro 
3477f0bc0a60SKOSAKI Motohiro 	/*
3478f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3479f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3480f0bc0a60SKOSAKI Motohiro 	 */
3481d9f21d42SMel Gorman 	if (!remaining &&
3482d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3483f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3484f0bc0a60SKOSAKI Motohiro 
3485f0bc0a60SKOSAKI Motohiro 		/*
3486f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3487f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3488f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3489f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3490f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3491f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3492f0bc0a60SKOSAKI Motohiro 		 */
3493f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
34941c7e7f6cSAaditya Kumar 
34951c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3496f0bc0a60SKOSAKI Motohiro 			schedule();
34971c7e7f6cSAaditya Kumar 
3498f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3499f0bc0a60SKOSAKI Motohiro 	} else {
3500f0bc0a60SKOSAKI Motohiro 		if (remaining)
3501f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3502f0bc0a60SKOSAKI Motohiro 		else
3503f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3504f0bc0a60SKOSAKI Motohiro 	}
3505f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3506f0bc0a60SKOSAKI Motohiro }
3507f0bc0a60SKOSAKI Motohiro 
35081da177e4SLinus Torvalds /*
35091da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
35101da177e4SLinus Torvalds  * from the init process.
35111da177e4SLinus Torvalds  *
35121da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
35131da177e4SLinus Torvalds  * free memory available even if there is no other activity
35141da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
35151da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
35161da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
35171da177e4SLinus Torvalds  *
35181da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
35191da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
35201da177e4SLinus Torvalds  */
35211da177e4SLinus Torvalds static int kswapd(void *p)
35221da177e4SLinus Torvalds {
3523e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3524e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
35251da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
35261da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3527f0bc0a60SKOSAKI Motohiro 
35281da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
35291da177e4SLinus Torvalds 		.reclaimed_slab = 0,
35301da177e4SLinus Torvalds 	};
3531a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
35321da177e4SLinus Torvalds 
3533174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3534c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
35351da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
35361da177e4SLinus Torvalds 
35371da177e4SLinus Torvalds 	/*
35381da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
35391da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
35401da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
35411da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
35421da177e4SLinus Torvalds 	 *
35431da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
35441da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
35451da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
35461da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
35471da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
35481da177e4SLinus Torvalds 	 */
3549930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
355083144186SRafael J. Wysocki 	set_freezable();
35511da177e4SLinus Torvalds 
3552e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3553e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35541da177e4SLinus Torvalds 	for ( ; ; ) {
35556f6313d4SJeff Liu 		bool ret;
35563e1d1d28SChristoph Lameter 
3557e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3558e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3559e716f2ebSMel Gorman 
356038087d9bSMel Gorman kswapd_try_sleep:
356138087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
356238087d9bSMel Gorman 					classzone_idx);
3563215ddd66SMel Gorman 
356438087d9bSMel Gorman 		/* Read the new order and classzone_idx */
356538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3566e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
356738087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3568e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35691da177e4SLinus Torvalds 
35708fe23e05SDavid Rientjes 		ret = try_to_freeze();
35718fe23e05SDavid Rientjes 		if (kthread_should_stop())
35728fe23e05SDavid Rientjes 			break;
35738fe23e05SDavid Rientjes 
35748fe23e05SDavid Rientjes 		/*
35758fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
35768fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3577b1296cc4SRafael J. Wysocki 		 */
357838087d9bSMel Gorman 		if (ret)
357938087d9bSMel Gorman 			continue;
35801d82de61SMel Gorman 
358138087d9bSMel Gorman 		/*
358238087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
358338087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
358438087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
358538087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
358638087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
358738087d9bSMel Gorman 		 * request (alloc_order).
358838087d9bSMel Gorman 		 */
3589e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3590e5146b12SMel Gorman 						alloc_order);
3591d92a8cfcSPeter Zijlstra 		fs_reclaim_acquire(GFP_KERNEL);
359238087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
3593d92a8cfcSPeter Zijlstra 		fs_reclaim_release(GFP_KERNEL);
359438087d9bSMel Gorman 		if (reclaim_order < alloc_order)
359538087d9bSMel Gorman 			goto kswapd_try_sleep;
359633906bc5SMel Gorman 	}
3597b0a8cc58STakamori Yamaguchi 
359871abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3599b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
360071abdc15SJohannes Weiner 
36011da177e4SLinus Torvalds 	return 0;
36021da177e4SLinus Torvalds }
36031da177e4SLinus Torvalds 
36041da177e4SLinus Torvalds /*
36051da177e4SLinus Torvalds  * A zone is low on free memory, so wake its kswapd task to service it.
36061da177e4SLinus Torvalds  */
360799504748SMel Gorman void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
36081da177e4SLinus Torvalds {
36091da177e4SLinus Torvalds 	pg_data_t *pgdat;
36101da177e4SLinus Torvalds 
36116aa303deSMel Gorman 	if (!managed_zone(zone))
36121da177e4SLinus Torvalds 		return;
36131da177e4SLinus Torvalds 
3614344736f2SVladimir Davydov 	if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
36151da177e4SLinus Torvalds 		return;
361688f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3617e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3618e716f2ebSMel Gorman 							   classzone_idx);
361938087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
36208d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
36211da177e4SLinus Torvalds 		return;
3622e1a55637SMel Gorman 
3623c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3624c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3625c73322d0SJohannes Weiner 		return;
3626c73322d0SJohannes Weiner 
3627e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx))
362888f5acf8SMel Gorman 		return;
362988f5acf8SMel Gorman 
3630e716f2ebSMel Gorman 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order);
36318d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
36321da177e4SLinus Torvalds }
36331da177e4SLinus Torvalds 
3634c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
36351da177e4SLinus Torvalds /*
36367b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3637d6277db4SRafael J. Wysocki  * freed pages.
3638d6277db4SRafael J. Wysocki  *
3639d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3640d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3641d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
36421da177e4SLinus Torvalds  */
36437b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
36441da177e4SLinus Torvalds {
3645d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3646d6277db4SRafael J. Wysocki 	struct scan_control sc = {
36477b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3648ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3649b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
36509e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3651ee814fe2SJohannes Weiner 		.may_writepage = 1,
3652ee814fe2SJohannes Weiner 		.may_unmap = 1,
3653ee814fe2SJohannes Weiner 		.may_swap = 1,
3654ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
36551da177e4SLinus Torvalds 	};
36567b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
36577b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
36587b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3659499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
36601da177e4SLinus Torvalds 
3661499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3662d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
3663d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
36647b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3665d6277db4SRafael J. Wysocki 
36663115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3667d6277db4SRafael J. Wysocki 
36687b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3669d92a8cfcSPeter Zijlstra 	fs_reclaim_release(sc.gfp_mask);
3670499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3671d6277db4SRafael J. Wysocki 
36727b51755cSKOSAKI Motohiro 	return nr_reclaimed;
36731da177e4SLinus Torvalds }
3674c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
36751da177e4SLinus Torvalds 
36761da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
36771da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
36781da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
36791da177e4SLinus Torvalds    restore their cpu bindings. */
3680517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
36811da177e4SLinus Torvalds {
368258c0a4a7SYasunori Goto 	int nid;
36831da177e4SLinus Torvalds 
368448fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3685c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3686a70f7302SRusty Russell 		const struct cpumask *mask;
3687a70f7302SRusty Russell 
3688a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3689c5f59f08SMike Travis 
36903e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
36911da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3692c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
36931da177e4SLinus Torvalds 	}
3694517bbed9SSebastian Andrzej Siewior 	return 0;
36951da177e4SLinus Torvalds }
36961da177e4SLinus Torvalds 
36973218ae14SYasunori Goto /*
36983218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
36993218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
37003218ae14SYasunori Goto  */
37013218ae14SYasunori Goto int kswapd_run(int nid)
37023218ae14SYasunori Goto {
37033218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
37043218ae14SYasunori Goto 	int ret = 0;
37053218ae14SYasunori Goto 
37063218ae14SYasunori Goto 	if (pgdat->kswapd)
37073218ae14SYasunori Goto 		return 0;
37083218ae14SYasunori Goto 
37093218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
37103218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
37113218ae14SYasunori Goto 		/* failure at boot is fatal */
3712c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3713d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3714d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3715d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
37163218ae14SYasunori Goto 	}
37173218ae14SYasunori Goto 	return ret;
37183218ae14SYasunori Goto }
37193218ae14SYasunori Goto 
37208fe23e05SDavid Rientjes /*
3721d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3722bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
37238fe23e05SDavid Rientjes  */
37248fe23e05SDavid Rientjes void kswapd_stop(int nid)
37258fe23e05SDavid Rientjes {
37268fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
37278fe23e05SDavid Rientjes 
3728d8adde17SJiang Liu 	if (kswapd) {
37298fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3730d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3731d8adde17SJiang Liu 	}
37328fe23e05SDavid Rientjes }
37338fe23e05SDavid Rientjes 
37341da177e4SLinus Torvalds static int __init kswapd_init(void)
37351da177e4SLinus Torvalds {
3736517bbed9SSebastian Andrzej Siewior 	int nid, ret;
373769e05944SAndrew Morton 
37381da177e4SLinus Torvalds 	swap_setup();
373948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
37403218ae14SYasunori Goto  		kswapd_run(nid);
3741517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3742517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3743517bbed9SSebastian Andrzej Siewior 					NULL);
3744517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
37451da177e4SLinus Torvalds 	return 0;
37461da177e4SLinus Torvalds }
37471da177e4SLinus Torvalds 
37481da177e4SLinus Torvalds module_init(kswapd_init)
37499eeff239SChristoph Lameter 
37509eeff239SChristoph Lameter #ifdef CONFIG_NUMA
37519eeff239SChristoph Lameter /*
3752a5f5f91dSMel Gorman  * Node reclaim mode
37539eeff239SChristoph Lameter  *
3754a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
37559eeff239SChristoph Lameter  * the watermarks.
37569eeff239SChristoph Lameter  */
3757a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
37589eeff239SChristoph Lameter 
37591b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
37607d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
37611b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
376295bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
37631b2ffb78SChristoph Lameter 
37649eeff239SChristoph Lameter /*
3765a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3766a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3767a92f7126SChristoph Lameter  * a zone.
3768a92f7126SChristoph Lameter  */
3769a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3770a92f7126SChristoph Lameter 
37719eeff239SChristoph Lameter /*
3772a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
37739614634fSChristoph Lameter  * occur.
37749614634fSChristoph Lameter  */
37759614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
37769614634fSChristoph Lameter 
37779614634fSChristoph Lameter /*
37780ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
37790ff38490SChristoph Lameter  * slab reclaim needs to occur.
37800ff38490SChristoph Lameter  */
37810ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
37820ff38490SChristoph Lameter 
378311fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
378490afa5deSMel Gorman {
378511fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
378611fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
378711fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
378890afa5deSMel Gorman 
378990afa5deSMel Gorman 	/*
379090afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
379190afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
379290afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
379390afa5deSMel Gorman 	 */
379490afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
379590afa5deSMel Gorman }
379690afa5deSMel Gorman 
379790afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3798a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
379990afa5deSMel Gorman {
3800d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3801d031a157SAlexandru Moise 	unsigned long delta = 0;
380290afa5deSMel Gorman 
380390afa5deSMel Gorman 	/*
380495bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
380590afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
380611fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
380790afa5deSMel Gorman 	 * a better estimate
380890afa5deSMel Gorman 	 */
3809a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3810a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
381190afa5deSMel Gorman 	else
3812a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
381390afa5deSMel Gorman 
381490afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3815a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3816a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
381790afa5deSMel Gorman 
381890afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
381990afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
382090afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
382190afa5deSMel Gorman 
382290afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
382390afa5deSMel Gorman }
382490afa5deSMel Gorman 
38250ff38490SChristoph Lameter /*
3826a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
38279eeff239SChristoph Lameter  */
3828a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
38299eeff239SChristoph Lameter {
38307fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
383169e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
38329eeff239SChristoph Lameter 	struct task_struct *p = current;
38339eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3834499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
3835179e9639SAndrew Morton 	struct scan_control sc = {
383662b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3837f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3838bd2f6199SJohannes Weiner 		.order = order,
3839a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3840a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3841a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3842ee814fe2SJohannes Weiner 		.may_swap = 1,
3843f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
3844179e9639SAndrew Morton 	};
38459eeff239SChristoph Lameter 
38469eeff239SChristoph Lameter 	cond_resched();
3847d4f7796eSChristoph Lameter 	/*
384895bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3849d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
385095bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3851d4f7796eSChristoph Lameter 	 */
3852499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3853499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
3854d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
38559eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
38569eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3857c84db23cSChristoph Lameter 
3858a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3859a92f7126SChristoph Lameter 		/*
38600ff38490SChristoph Lameter 		 * Free memory by calling shrink zone with increasing
38610ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3862a92f7126SChristoph Lameter 		 */
3863a92f7126SChristoph Lameter 		do {
3864970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
38659e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
38660ff38490SChristoph Lameter 	}
3867a92f7126SChristoph Lameter 
38689eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3869d92a8cfcSPeter Zijlstra 	fs_reclaim_release(gfp_mask);
3870499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
3871499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3872a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
38739eeff239SChristoph Lameter }
3874179e9639SAndrew Morton 
3875a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3876179e9639SAndrew Morton {
3877d773ed6bSDavid Rientjes 	int ret;
3878179e9639SAndrew Morton 
3879179e9639SAndrew Morton 	/*
3880a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
38810ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
388234aa1330SChristoph Lameter 	 *
38839614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
38849614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3885a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3886a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
38879614634fSChristoph Lameter 	 * unmapped file backed pages.
3888179e9639SAndrew Morton 	 */
3889a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3890385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3891a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3892179e9639SAndrew Morton 
3893179e9639SAndrew Morton 	/*
3894d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3895179e9639SAndrew Morton 	 */
3896d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3897a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3898179e9639SAndrew Morton 
3899179e9639SAndrew Morton 	/*
3900a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3901179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3902179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3903179e9639SAndrew Morton 	 * as wide as possible.
3904179e9639SAndrew Morton 	 */
3905a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3906a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3907d773ed6bSDavid Rientjes 
3908a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3909a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3910fa5e084eSMel Gorman 
3911a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3912a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3913d773ed6bSDavid Rientjes 
391424cf7251SMel Gorman 	if (!ret)
391524cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
391624cf7251SMel Gorman 
3917d773ed6bSDavid Rientjes 	return ret;
3918179e9639SAndrew Morton }
39199eeff239SChristoph Lameter #endif
3920894bc310SLee Schermerhorn 
3921894bc310SLee Schermerhorn /*
3922894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3923894bc310SLee Schermerhorn  * @page: the page to test
3924894bc310SLee Schermerhorn  *
3925894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
392639b5f29aSHugh Dickins  * lists vs unevictable list.
3927894bc310SLee Schermerhorn  *
3928894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3929ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3930b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3931ba9ddf49SLee Schermerhorn  *
3932894bc310SLee Schermerhorn  */
393339b5f29aSHugh Dickins int page_evictable(struct page *page)
3934894bc310SLee Schermerhorn {
393539b5f29aSHugh Dickins 	return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3936894bc310SLee Schermerhorn }
393789e004eaSLee Schermerhorn 
393885046579SHugh Dickins #ifdef CONFIG_SHMEM
393989e004eaSLee Schermerhorn /**
394024513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
394124513264SHugh Dickins  * @pages:	array of pages to check
394224513264SHugh Dickins  * @nr_pages:	number of pages to check
394389e004eaSLee Schermerhorn  *
394424513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
394585046579SHugh Dickins  *
394685046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
394789e004eaSLee Schermerhorn  */
394824513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
394989e004eaSLee Schermerhorn {
3950925b7673SJohannes Weiner 	struct lruvec *lruvec;
3951785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
395224513264SHugh Dickins 	int pgscanned = 0;
395324513264SHugh Dickins 	int pgrescued = 0;
395489e004eaSLee Schermerhorn 	int i;
395589e004eaSLee Schermerhorn 
395624513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
395724513264SHugh Dickins 		struct page *page = pages[i];
3958785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
395989e004eaSLee Schermerhorn 
396024513264SHugh Dickins 		pgscanned++;
3961785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3962785b99feSMel Gorman 			if (pgdat)
3963785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3964785b99feSMel Gorman 			pgdat = pagepgdat;
3965785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
396689e004eaSLee Schermerhorn 		}
3967785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
396889e004eaSLee Schermerhorn 
396924513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
397024513264SHugh Dickins 			continue;
397189e004eaSLee Schermerhorn 
397239b5f29aSHugh Dickins 		if (page_evictable(page)) {
397324513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
397424513264SHugh Dickins 
3975309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
397624513264SHugh Dickins 			ClearPageUnevictable(page);
3977fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3978fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
397924513264SHugh Dickins 			pgrescued++;
398089e004eaSLee Schermerhorn 		}
398189e004eaSLee Schermerhorn 	}
398224513264SHugh Dickins 
3983785b99feSMel Gorman 	if (pgdat) {
398424513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
398524513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3986785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
398724513264SHugh Dickins 	}
398885046579SHugh Dickins }
398985046579SHugh Dickins #endif /* CONFIG_SHMEM */
3990