xref: /openbmc/linux/mm/vmscan.c (revision 145e1a71e090575c74969e3daa8136d1e5b99fc8)
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;
119d108c772SAndrey Ryabinin 
120d108c772SAndrey Ryabinin 	struct {
121d108c772SAndrey Ryabinin 		unsigned int dirty;
122d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
123d108c772SAndrey Ryabinin 		unsigned int congested;
124d108c772SAndrey Ryabinin 		unsigned int writeback;
125d108c772SAndrey Ryabinin 		unsigned int immediate;
126d108c772SAndrey Ryabinin 		unsigned int file_taken;
127d108c772SAndrey Ryabinin 		unsigned int taken;
128d108c772SAndrey Ryabinin 	} nr;
1291da177e4SLinus Torvalds };
1301da177e4SLinus Torvalds 
1311da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1321da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1331da177e4SLinus Torvalds 	do {								\
1341da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1351da177e4SLinus Torvalds 			struct page *prev;				\
1361da177e4SLinus Torvalds 									\
1371da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1381da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1391da177e4SLinus Torvalds 		}							\
1401da177e4SLinus Torvalds 	} while (0)
1411da177e4SLinus Torvalds #else
1421da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1431da177e4SLinus Torvalds #endif
1441da177e4SLinus Torvalds 
1451da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1461da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1471da177e4SLinus Torvalds 	do {								\
1481da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1491da177e4SLinus Torvalds 			struct page *prev;				\
1501da177e4SLinus Torvalds 									\
1511da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1521da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1531da177e4SLinus Torvalds 		}							\
1541da177e4SLinus Torvalds 	} while (0)
1551da177e4SLinus Torvalds #else
1561da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1571da177e4SLinus Torvalds #endif
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds /*
1601da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1611da177e4SLinus Torvalds  */
1621da177e4SLinus Torvalds int vm_swappiness = 60;
163d0480be4SWang Sheng-Hui /*
164d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
165d0480be4SWang Sheng-Hui  * zones.
166d0480be4SWang Sheng-Hui  */
167d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1681da177e4SLinus Torvalds 
1691da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1701da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1711da177e4SLinus Torvalds 
172c255a458SAndrew Morton #ifdef CONFIG_MEMCG
17389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
17489b5fae5SJohannes Weiner {
175f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
17689b5fae5SJohannes Weiner }
17797c9341fSTejun Heo 
17897c9341fSTejun Heo /**
17997c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
18097c9341fSTejun Heo  * @sc: scan_control in question
18197c9341fSTejun Heo  *
18297c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
18397c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
18497c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
18597c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
18697c9341fSTejun Heo  * allocation and configurability.
18797c9341fSTejun Heo  *
18897c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
18997c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
19097c9341fSTejun Heo  */
19197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
19297c9341fSTejun Heo {
19397c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
19497c9341fSTejun Heo 
19597c9341fSTejun Heo 	if (!memcg)
19697c9341fSTejun Heo 		return true;
19797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
19869234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
19997c9341fSTejun Heo 		return true;
20097c9341fSTejun Heo #endif
20197c9341fSTejun Heo 	return false;
20297c9341fSTejun Heo }
203e3c1ac58SAndrey Ryabinin 
204e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
205e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
206e3c1ac58SAndrey Ryabinin 				bool congested)
207e3c1ac58SAndrey Ryabinin {
208e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
209e3c1ac58SAndrey Ryabinin 
210e3c1ac58SAndrey Ryabinin 	if (!memcg)
211e3c1ac58SAndrey Ryabinin 		return;
212e3c1ac58SAndrey Ryabinin 
213e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
214e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
215e3c1ac58SAndrey Ryabinin }
216e3c1ac58SAndrey Ryabinin 
217e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
218e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
219e3c1ac58SAndrey Ryabinin {
220e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
221e3c1ac58SAndrey Ryabinin 
222e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
223e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
224e3c1ac58SAndrey Ryabinin 
225e3c1ac58SAndrey Ryabinin }
22691a45470SKAMEZAWA Hiroyuki #else
22789b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
22889b5fae5SJohannes Weiner {
22989b5fae5SJohannes Weiner 	return true;
23089b5fae5SJohannes Weiner }
23197c9341fSTejun Heo 
23297c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
23397c9341fSTejun Heo {
23497c9341fSTejun Heo 	return true;
23597c9341fSTejun Heo }
236e3c1ac58SAndrey Ryabinin 
237e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
238e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
239e3c1ac58SAndrey Ryabinin {
240e3c1ac58SAndrey Ryabinin }
241e3c1ac58SAndrey Ryabinin 
242e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
243e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
244e3c1ac58SAndrey Ryabinin {
245e3c1ac58SAndrey Ryabinin 	return false;
246e3c1ac58SAndrey Ryabinin 
247e3c1ac58SAndrey Ryabinin }
24891a45470SKAMEZAWA Hiroyuki #endif
24991a45470SKAMEZAWA Hiroyuki 
2505a1c84b4SMel Gorman /*
2515a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
2525a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
2535a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
2545a1c84b4SMel Gorman  */
2555a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
2565a1c84b4SMel Gorman {
2575a1c84b4SMel Gorman 	unsigned long nr;
2585a1c84b4SMel Gorman 
2595a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
2605a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
2615a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
2625a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
2635a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
2645a1c84b4SMel Gorman 
2655a1c84b4SMel Gorman 	return nr;
2665a1c84b4SMel Gorman }
2675a1c84b4SMel Gorman 
268fd538803SMichal Hocko /**
269fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
270fd538803SMichal Hocko  * @lruvec: lru vector
271fd538803SMichal Hocko  * @lru: lru to use
272fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
273fd538803SMichal Hocko  */
274fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
275c9f299d9SKOSAKI Motohiro {
276fd538803SMichal Hocko 	unsigned long lru_size;
277fd538803SMichal Hocko 	int zid;
278a3d8e054SKOSAKI Motohiro 
279fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
280fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
281fd538803SMichal Hocko 	else
282fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
283fd538803SMichal Hocko 
284fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
285fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
286fd538803SMichal Hocko 		unsigned long size;
287fd538803SMichal Hocko 
288fd538803SMichal Hocko 		if (!managed_zone(zone))
289fd538803SMichal Hocko 			continue;
290fd538803SMichal Hocko 
291fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
292fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
293fd538803SMichal Hocko 		else
294fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
295fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
296fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
297c9f299d9SKOSAKI Motohiro 	}
298c9f299d9SKOSAKI Motohiro 
299fd538803SMichal Hocko 	return lru_size;
300b4536f0cSMichal Hocko 
301b4536f0cSMichal Hocko }
302b4536f0cSMichal Hocko 
3031da177e4SLinus Torvalds /*
3041d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3051da177e4SLinus Torvalds  */
3068e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3071da177e4SLinus Torvalds {
3081d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
3091d3d4437SGlauber Costa 
3101d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3111d3d4437SGlauber Costa 		size *= nr_node_ids;
3121d3d4437SGlauber Costa 
3131d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3141d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3151d3d4437SGlauber Costa 		return -ENOMEM;
3168e04944fSTetsuo Handa 	return 0;
3178e04944fSTetsuo Handa }
3181d3d4437SGlauber Costa 
3198e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3208e04944fSTetsuo Handa {
3218e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
3228e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
3238e04944fSTetsuo Handa }
3248e04944fSTetsuo Handa 
3258e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
3268e04944fSTetsuo Handa {
3271da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3281da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
3291da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
3308e04944fSTetsuo Handa }
3318e04944fSTetsuo Handa 
3328e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
3338e04944fSTetsuo Handa {
3348e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
3358e04944fSTetsuo Handa 
3368e04944fSTetsuo Handa 	if (err)
3378e04944fSTetsuo Handa 		return err;
3388e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
3391d3d4437SGlauber Costa 	return 0;
3401da177e4SLinus Torvalds }
3418e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
3421da177e4SLinus Torvalds 
3431da177e4SLinus Torvalds /*
3441da177e4SLinus Torvalds  * Remove one
3451da177e4SLinus Torvalds  */
3468e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
3471da177e4SLinus Torvalds {
348bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
349bb422a73STetsuo Handa 		return;
3501da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3511da177e4SLinus Torvalds 	list_del(&shrinker->list);
3521da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
353ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
354bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
3551da177e4SLinus Torvalds }
3568e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
3571da177e4SLinus Torvalds 
3581da177e4SLinus Torvalds #define SHRINK_BATCH 128
3591d3d4437SGlauber Costa 
360cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
3619092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
3621da177e4SLinus Torvalds {
36324f7c6b9SDave Chinner 	unsigned long freed = 0;
3641da177e4SLinus Torvalds 	unsigned long long delta;
365635697c6SKonstantin Khlebnikov 	long total_scan;
366d5bc5fd3SVladimir Davydov 	long freeable;
367acf92b48SDave Chinner 	long nr;
368acf92b48SDave Chinner 	long new_nr;
3691d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
370e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
371e9299f50SDave Chinner 					  : SHRINK_BATCH;
3725f33a080SShaohua Li 	long scanned = 0, next_deferred;
3731da177e4SLinus Torvalds 
374d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
375d5bc5fd3SVladimir Davydov 	if (freeable == 0)
3761d3d4437SGlauber Costa 		return 0;
377635697c6SKonstantin Khlebnikov 
378acf92b48SDave Chinner 	/*
379acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
380acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
381acf92b48SDave Chinner 	 * don't also do this scanning work.
382acf92b48SDave Chinner 	 */
3831d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
384acf92b48SDave Chinner 
385acf92b48SDave Chinner 	total_scan = nr;
3869092c71bSJosef Bacik 	delta = freeable >> priority;
3879092c71bSJosef Bacik 	delta *= 4;
3889092c71bSJosef Bacik 	do_div(delta, shrinker->seeks);
389acf92b48SDave Chinner 	total_scan += delta;
390acf92b48SDave Chinner 	if (total_scan < 0) {
3918612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
392a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
393d5bc5fd3SVladimir Davydov 		total_scan = freeable;
3945f33a080SShaohua Li 		next_deferred = nr;
3955f33a080SShaohua Li 	} else
3965f33a080SShaohua Li 		next_deferred = total_scan;
397ea164d73SAndrea Arcangeli 
398ea164d73SAndrea Arcangeli 	/*
3993567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
4003567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
4013567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
4023567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
4033567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
404d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
4053567b59aSDave Chinner 	 * memory.
4063567b59aSDave Chinner 	 *
4073567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
4083567b59aSDave Chinner 	 * a large delta change is calculated directly.
4093567b59aSDave Chinner 	 */
410d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
411d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
4123567b59aSDave Chinner 
4133567b59aSDave Chinner 	/*
414ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
415ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
416ea164d73SAndrea Arcangeli 	 * freeable entries.
417ea164d73SAndrea Arcangeli 	 */
418d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
419d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
4201da177e4SLinus Torvalds 
42124f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
4229092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
42309576073SDave Chinner 
4240b1fb40aSVladimir Davydov 	/*
4250b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
4260b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
4270b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
4280b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
4290b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
4300b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
4310b1fb40aSVladimir Davydov 	 * batch_size.
4320b1fb40aSVladimir Davydov 	 *
4330b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
4340b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
435d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
4360b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
4370b1fb40aSVladimir Davydov 	 * possible.
4380b1fb40aSVladimir Davydov 	 */
4390b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
440d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
44124f7c6b9SDave Chinner 		unsigned long ret;
4420b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
4431da177e4SLinus Torvalds 
4440b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
445d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
44624f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
44724f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
4481da177e4SLinus Torvalds 			break;
44924f7c6b9SDave Chinner 		freed += ret;
45024f7c6b9SDave Chinner 
451d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
452d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
453d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
4541da177e4SLinus Torvalds 
4551da177e4SLinus Torvalds 		cond_resched();
4561da177e4SLinus Torvalds 	}
4571da177e4SLinus Torvalds 
4585f33a080SShaohua Li 	if (next_deferred >= scanned)
4595f33a080SShaohua Li 		next_deferred -= scanned;
4605f33a080SShaohua Li 	else
4615f33a080SShaohua Li 		next_deferred = 0;
462acf92b48SDave Chinner 	/*
463acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
464acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
465acf92b48SDave Chinner 	 * scan, there is no need to do an update.
466acf92b48SDave Chinner 	 */
4675f33a080SShaohua Li 	if (next_deferred > 0)
4685f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
4691d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
47083aeeadaSKonstantin Khlebnikov 	else
4711d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
472acf92b48SDave Chinner 
473df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
4741d3d4437SGlauber Costa 	return freed;
4751d3d4437SGlauber Costa }
4761d3d4437SGlauber Costa 
4776b4f7799SJohannes Weiner /**
478cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
4796b4f7799SJohannes Weiner  * @gfp_mask: allocation context
4806b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
481cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
4829092c71bSJosef Bacik  * @priority: the reclaim priority
4831d3d4437SGlauber Costa  *
4846b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
4851d3d4437SGlauber Costa  *
4866b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
4876b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
4881d3d4437SGlauber Costa  *
489cb731d6cSVladimir Davydov  * @memcg specifies the memory cgroup to target. If it is not NULL,
490cb731d6cSVladimir Davydov  * only shrinkers with SHRINKER_MEMCG_AWARE set will be called to scan
4910fc9f58aSVladimir Davydov  * objects from the memory cgroup specified. Otherwise, only unaware
4920fc9f58aSVladimir Davydov  * shrinkers are called.
493cb731d6cSVladimir Davydov  *
4949092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
4959092c71bSJosef Bacik  * in order to get the scan target.
4961d3d4437SGlauber Costa  *
4976b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
4981d3d4437SGlauber Costa  */
499cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
500cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
5019092c71bSJosef Bacik 				 int priority)
5021d3d4437SGlauber Costa {
5031d3d4437SGlauber Costa 	struct shrinker *shrinker;
5041d3d4437SGlauber Costa 	unsigned long freed = 0;
5051d3d4437SGlauber Costa 
5060fc9f58aSVladimir Davydov 	if (memcg && (!memcg_kmem_enabled() || !mem_cgroup_online(memcg)))
507cb731d6cSVladimir Davydov 		return 0;
508cb731d6cSVladimir Davydov 
509e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
5101d3d4437SGlauber Costa 		goto out;
5111d3d4437SGlauber Costa 
5121d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
5136b4f7799SJohannes Weiner 		struct shrink_control sc = {
5146b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
5156b4f7799SJohannes Weiner 			.nid = nid,
516cb731d6cSVladimir Davydov 			.memcg = memcg,
5176b4f7799SJohannes Weiner 		};
5186b4f7799SJohannes Weiner 
5190fc9f58aSVladimir Davydov 		/*
5200fc9f58aSVladimir Davydov 		 * If kernel memory accounting is disabled, we ignore
5210fc9f58aSVladimir Davydov 		 * SHRINKER_MEMCG_AWARE flag and call all shrinkers
5220fc9f58aSVladimir Davydov 		 * passing NULL for memcg.
5230fc9f58aSVladimir Davydov 		 */
5240fc9f58aSVladimir Davydov 		if (memcg_kmem_enabled() &&
5250fc9f58aSVladimir Davydov 		    !!memcg != !!(shrinker->flags & SHRINKER_MEMCG_AWARE))
526cb731d6cSVladimir Davydov 			continue;
527cb731d6cSVladimir Davydov 
5286b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
5296b4f7799SJohannes Weiner 			sc.nid = 0;
5306b4f7799SJohannes Weiner 
5319092c71bSJosef Bacik 		freed += do_shrink_slab(&sc, shrinker, priority);
532e496612cSMinchan Kim 		/*
533e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
534e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
535e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
536e496612cSMinchan Kim 		 */
537e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
538e496612cSMinchan Kim 			freed = freed ? : 1;
539e496612cSMinchan Kim 			break;
540e496612cSMinchan Kim 		}
541ec97097bSVladimir Davydov 	}
5421d3d4437SGlauber Costa 
5431da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
544f06590bdSMinchan Kim out:
545f06590bdSMinchan Kim 	cond_resched();
54624f7c6b9SDave Chinner 	return freed;
5471da177e4SLinus Torvalds }
5481da177e4SLinus Torvalds 
549cb731d6cSVladimir Davydov void drop_slab_node(int nid)
550cb731d6cSVladimir Davydov {
551cb731d6cSVladimir Davydov 	unsigned long freed;
552cb731d6cSVladimir Davydov 
553cb731d6cSVladimir Davydov 	do {
554cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
555cb731d6cSVladimir Davydov 
556cb731d6cSVladimir Davydov 		freed = 0;
557cb731d6cSVladimir Davydov 		do {
5589092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
559cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
560cb731d6cSVladimir Davydov 	} while (freed > 10);
561cb731d6cSVladimir Davydov }
562cb731d6cSVladimir Davydov 
563cb731d6cSVladimir Davydov void drop_slab(void)
564cb731d6cSVladimir Davydov {
565cb731d6cSVladimir Davydov 	int nid;
566cb731d6cSVladimir Davydov 
567cb731d6cSVladimir Davydov 	for_each_online_node(nid)
568cb731d6cSVladimir Davydov 		drop_slab_node(nid);
569cb731d6cSVladimir Davydov }
570cb731d6cSVladimir Davydov 
5711da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
5721da177e4SLinus Torvalds {
573ceddc3a5SJohannes Weiner 	/*
574ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
575ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
576ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
577ceddc3a5SJohannes Weiner 	 */
578bd4c82c2SHuang Ying 	int radix_pins = PageTransHuge(page) && PageSwapCache(page) ?
579bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
580bd4c82c2SHuang Ying 	return page_count(page) - page_has_private(page) == 1 + radix_pins;
5811da177e4SLinus Torvalds }
5821da177e4SLinus Torvalds 
583703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
5841da177e4SLinus Torvalds {
585930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
5861da177e4SLinus Torvalds 		return 1;
587703c2708STejun Heo 	if (!inode_write_congested(inode))
5881da177e4SLinus Torvalds 		return 1;
589703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
5901da177e4SLinus Torvalds 		return 1;
5911da177e4SLinus Torvalds 	return 0;
5921da177e4SLinus Torvalds }
5931da177e4SLinus Torvalds 
5941da177e4SLinus Torvalds /*
5951da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
5961da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
5971da177e4SLinus Torvalds  * fsync(), msync() or close().
5981da177e4SLinus Torvalds  *
5991da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
6001da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
6011da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
6021da177e4SLinus Torvalds  *
6031da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
6041da177e4SLinus Torvalds  * __GFP_FS.
6051da177e4SLinus Torvalds  */
6061da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
6071da177e4SLinus Torvalds 				struct page *page, int error)
6081da177e4SLinus Torvalds {
6097eaceaccSJens Axboe 	lock_page(page);
6103e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
6113e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
6121da177e4SLinus Torvalds 	unlock_page(page);
6131da177e4SLinus Torvalds }
6141da177e4SLinus Torvalds 
61504e62a29SChristoph Lameter /* possible outcome of pageout() */
61604e62a29SChristoph Lameter typedef enum {
61704e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
61804e62a29SChristoph Lameter 	PAGE_KEEP,
61904e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
62004e62a29SChristoph Lameter 	PAGE_ACTIVATE,
62104e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
62204e62a29SChristoph Lameter 	PAGE_SUCCESS,
62304e62a29SChristoph Lameter 	/* page is clean and locked */
62404e62a29SChristoph Lameter 	PAGE_CLEAN,
62504e62a29SChristoph Lameter } pageout_t;
62604e62a29SChristoph Lameter 
6271da177e4SLinus Torvalds /*
6281742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
6291742f19fSAndrew Morton  * Calls ->writepage().
6301da177e4SLinus Torvalds  */
631c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
6327d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
6331da177e4SLinus Torvalds {
6341da177e4SLinus Torvalds 	/*
6351da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
6361da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
6371da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
6381da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
6391da177e4SLinus Torvalds 	 * PagePrivate for that.
6401da177e4SLinus Torvalds 	 *
6418174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
6421da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
6431da177e4SLinus Torvalds 	 * will block.
6441da177e4SLinus Torvalds 	 *
6451da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
6461da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
6471da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
6481da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
6491da177e4SLinus Torvalds 	 */
6501da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
6511da177e4SLinus Torvalds 		return PAGE_KEEP;
6521da177e4SLinus Torvalds 	if (!mapping) {
6531da177e4SLinus Torvalds 		/*
6541da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
6551da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
6561da177e4SLinus Torvalds 		 */
657266cf658SDavid Howells 		if (page_has_private(page)) {
6581da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
6591da177e4SLinus Torvalds 				ClearPageDirty(page);
660b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
6611da177e4SLinus Torvalds 				return PAGE_CLEAN;
6621da177e4SLinus Torvalds 			}
6631da177e4SLinus Torvalds 		}
6641da177e4SLinus Torvalds 		return PAGE_KEEP;
6651da177e4SLinus Torvalds 	}
6661da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
6671da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
668703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
6691da177e4SLinus Torvalds 		return PAGE_KEEP;
6701da177e4SLinus Torvalds 
6711da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
6721da177e4SLinus Torvalds 		int res;
6731da177e4SLinus Torvalds 		struct writeback_control wbc = {
6741da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
6751da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
676111ebb6eSOGAWA Hirofumi 			.range_start = 0,
677111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
6781da177e4SLinus Torvalds 			.for_reclaim = 1,
6791da177e4SLinus Torvalds 		};
6801da177e4SLinus Torvalds 
6811da177e4SLinus Torvalds 		SetPageReclaim(page);
6821da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
6831da177e4SLinus Torvalds 		if (res < 0)
6841da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
685994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
6861da177e4SLinus Torvalds 			ClearPageReclaim(page);
6871da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
6881da177e4SLinus Torvalds 		}
689c661b078SAndy Whitcroft 
6901da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
6911da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
6921da177e4SLinus Torvalds 			ClearPageReclaim(page);
6931da177e4SLinus Torvalds 		}
6943aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
695c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
6961da177e4SLinus Torvalds 		return PAGE_SUCCESS;
6971da177e4SLinus Torvalds 	}
6981da177e4SLinus Torvalds 
6991da177e4SLinus Torvalds 	return PAGE_CLEAN;
7001da177e4SLinus Torvalds }
7011da177e4SLinus Torvalds 
702a649fd92SAndrew Morton /*
703e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
704e286781dSNick Piggin  * gets returned with a refcount of 0.
705a649fd92SAndrew Morton  */
706a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
707a528910eSJohannes Weiner 			    bool reclaimed)
70849d2e9ccSChristoph Lameter {
709c4843a75SGreg Thelen 	unsigned long flags;
710bd4c82c2SHuang Ying 	int refcount;
711c4843a75SGreg Thelen 
71228e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
71328e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
71449d2e9ccSChristoph Lameter 
715b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
71649d2e9ccSChristoph Lameter 	/*
7170fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
7180fd0e6b0SNick Piggin 	 *
7190fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
7200fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
7210fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
7220fd0e6b0SNick Piggin 	 * here, then the following race may occur:
7230fd0e6b0SNick Piggin 	 *
7240fd0e6b0SNick Piggin 	 * get_user_pages(&page);
7250fd0e6b0SNick Piggin 	 * [user mapping goes away]
7260fd0e6b0SNick Piggin 	 * write_to(page);
7270fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
7280fd0e6b0SNick Piggin 	 * SetPageDirty(page);
7290fd0e6b0SNick Piggin 	 * put_page(page);
7300fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
7310fd0e6b0SNick Piggin 	 *
7320fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
7330fd0e6b0SNick Piggin 	 *
7340fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
7350fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
7360139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
7370fd0e6b0SNick Piggin 	 *
7380fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
739b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
74049d2e9ccSChristoph Lameter 	 */
741bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
742bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
743bd4c82c2SHuang Ying 	else
744bd4c82c2SHuang Ying 		refcount = 2;
745bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
74649d2e9ccSChristoph Lameter 		goto cannot_free;
747e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
748e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
749bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
75049d2e9ccSChristoph Lameter 		goto cannot_free;
751e286781dSNick Piggin 	}
75249d2e9ccSChristoph Lameter 
75349d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
75449d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
7550a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
75649d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
757b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
75875f6d6d2SMinchan Kim 		put_swap_page(page, swap);
759e286781dSNick Piggin 	} else {
7606072d13cSLinus Torvalds 		void (*freepage)(struct page *);
761a528910eSJohannes Weiner 		void *shadow = NULL;
7626072d13cSLinus Torvalds 
7636072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
764a528910eSJohannes Weiner 		/*
765a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
766a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
767a528910eSJohannes Weiner 		 *
768a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
769a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
770a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
771a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
772a528910eSJohannes Weiner 		 * back.
773f9fe48beSRoss Zwisler 		 *
774f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
775f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
776f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
777f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
778b93b0163SMatthew Wilcox 		 * same address_space.
779a528910eSJohannes Weiner 		 */
780a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
781f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
782a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
78362cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
784b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
7856072d13cSLinus Torvalds 
7866072d13cSLinus Torvalds 		if (freepage != NULL)
7876072d13cSLinus Torvalds 			freepage(page);
788e286781dSNick Piggin 	}
789e286781dSNick Piggin 
79049d2e9ccSChristoph Lameter 	return 1;
79149d2e9ccSChristoph Lameter 
79249d2e9ccSChristoph Lameter cannot_free:
793b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
79449d2e9ccSChristoph Lameter 	return 0;
79549d2e9ccSChristoph Lameter }
79649d2e9ccSChristoph Lameter 
7971da177e4SLinus Torvalds /*
798e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
799e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
800e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
801e286781dSNick Piggin  * this page.
802e286781dSNick Piggin  */
803e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
804e286781dSNick Piggin {
805a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
806e286781dSNick Piggin 		/*
807e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
808e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
809e286781dSNick Piggin 		 * atomic operation.
810e286781dSNick Piggin 		 */
811fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
812e286781dSNick Piggin 		return 1;
813e286781dSNick Piggin 	}
814e286781dSNick Piggin 	return 0;
815e286781dSNick Piggin }
816e286781dSNick Piggin 
817894bc310SLee Schermerhorn /**
818894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
819894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
820894bc310SLee Schermerhorn  *
821894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
822894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
823894bc310SLee Schermerhorn  *
824894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
825894bc310SLee Schermerhorn  */
826894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
827894bc310SLee Schermerhorn {
828c53954a0SMel Gorman 	lru_cache_add(page);
829894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
830894bc310SLee Schermerhorn }
831894bc310SLee Schermerhorn 
832dfc8d636SJohannes Weiner enum page_references {
833dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
834dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
83564574746SJohannes Weiner 	PAGEREF_KEEP,
836dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
837dfc8d636SJohannes Weiner };
838dfc8d636SJohannes Weiner 
839dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
840dfc8d636SJohannes Weiner 						  struct scan_control *sc)
841dfc8d636SJohannes Weiner {
84264574746SJohannes Weiner 	int referenced_ptes, referenced_page;
843dfc8d636SJohannes Weiner 	unsigned long vm_flags;
844dfc8d636SJohannes Weiner 
845c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
846c3ac9a8aSJohannes Weiner 					  &vm_flags);
84764574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
848dfc8d636SJohannes Weiner 
849dfc8d636SJohannes Weiner 	/*
850dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
851dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
852dfc8d636SJohannes Weiner 	 */
853dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
854dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
855dfc8d636SJohannes Weiner 
85664574746SJohannes Weiner 	if (referenced_ptes) {
857e4898273SMichal Hocko 		if (PageSwapBacked(page))
85864574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
85964574746SJohannes Weiner 		/*
86064574746SJohannes Weiner 		 * All mapped pages start out with page table
86164574746SJohannes Weiner 		 * references from the instantiating fault, so we need
86264574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
86364574746SJohannes Weiner 		 * than once.
86464574746SJohannes Weiner 		 *
86564574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
86664574746SJohannes Weiner 		 * inactive list.  Another page table reference will
86764574746SJohannes Weiner 		 * lead to its activation.
86864574746SJohannes Weiner 		 *
86964574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
87064574746SJohannes Weiner 		 * so that recently deactivated but used pages are
87164574746SJohannes Weiner 		 * quickly recovered.
87264574746SJohannes Weiner 		 */
87364574746SJohannes Weiner 		SetPageReferenced(page);
87464574746SJohannes Weiner 
87534dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
876dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
877dfc8d636SJohannes Weiner 
878c909e993SKonstantin Khlebnikov 		/*
879c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
880c909e993SKonstantin Khlebnikov 		 */
881c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
882c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
883c909e993SKonstantin Khlebnikov 
88464574746SJohannes Weiner 		return PAGEREF_KEEP;
88564574746SJohannes Weiner 	}
88664574746SJohannes Weiner 
887dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
8882e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
889dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
89064574746SJohannes Weiner 
89164574746SJohannes Weiner 	return PAGEREF_RECLAIM;
892dfc8d636SJohannes Weiner }
893dfc8d636SJohannes Weiner 
894e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
895e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
896e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
897e2be15f6SMel Gorman {
898b4597226SMel Gorman 	struct address_space *mapping;
899b4597226SMel Gorman 
900e2be15f6SMel Gorman 	/*
901e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
902e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
903e2be15f6SMel Gorman 	 */
904802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
905802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
906e2be15f6SMel Gorman 		*dirty = false;
907e2be15f6SMel Gorman 		*writeback = false;
908e2be15f6SMel Gorman 		return;
909e2be15f6SMel Gorman 	}
910e2be15f6SMel Gorman 
911e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
912e2be15f6SMel Gorman 	*dirty = PageDirty(page);
913e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
914b4597226SMel Gorman 
915b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
916b4597226SMel Gorman 	if (!page_has_private(page))
917b4597226SMel Gorman 		return;
918b4597226SMel Gorman 
919b4597226SMel Gorman 	mapping = page_mapping(page);
920b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
921b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
922e2be15f6SMel Gorman }
923e2be15f6SMel Gorman 
924e286781dSNick Piggin /*
9251742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
9261da177e4SLinus Torvalds  */
9271742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
928599d0c95SMel Gorman 				      struct pglist_data *pgdat,
929f84f6e2bSMel Gorman 				      struct scan_control *sc,
93002c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
9313c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
93202c6de8dSMinchan Kim 				      bool force_reclaim)
9331da177e4SLinus Torvalds {
9341da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
935abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
9361da177e4SLinus Torvalds 	int pgactivate = 0;
9373c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
9383c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
9393c710c1aSMichal Hocko 	unsigned nr_congested = 0;
9403c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
9413c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
9423c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
9435bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
9445bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
9451da177e4SLinus Torvalds 
9461da177e4SLinus Torvalds 	cond_resched();
9471da177e4SLinus Torvalds 
9481da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
9491da177e4SLinus Torvalds 		struct address_space *mapping;
9501da177e4SLinus Torvalds 		struct page *page;
9511da177e4SLinus Torvalds 		int may_enter_fs;
95202c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
953e2be15f6SMel Gorman 		bool dirty, writeback;
9541da177e4SLinus Torvalds 
9551da177e4SLinus Torvalds 		cond_resched();
9561da177e4SLinus Torvalds 
9571da177e4SLinus Torvalds 		page = lru_to_page(page_list);
9581da177e4SLinus Torvalds 		list_del(&page->lru);
9591da177e4SLinus Torvalds 
960529ae9aaSNick Piggin 		if (!trylock_page(page))
9611da177e4SLinus Torvalds 			goto keep;
9621da177e4SLinus Torvalds 
963309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
9641da177e4SLinus Torvalds 
9651da177e4SLinus Torvalds 		sc->nr_scanned++;
96680e43426SChristoph Lameter 
96739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
968ad6b6704SMinchan Kim 			goto activate_locked;
969894bc310SLee Schermerhorn 
970a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
97180e43426SChristoph Lameter 			goto keep_locked;
97280e43426SChristoph Lameter 
9731da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
974802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
975802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
9761da177e4SLinus Torvalds 			sc->nr_scanned++;
9771da177e4SLinus Torvalds 
978c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
979c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
980c661b078SAndy Whitcroft 
981e62e384eSMichal Hocko 		/*
982894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
983e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
984e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
985e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
986e2be15f6SMel Gorman 		 */
987e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
988e2be15f6SMel Gorman 		if (dirty || writeback)
989e2be15f6SMel Gorman 			nr_dirty++;
990e2be15f6SMel Gorman 
991e2be15f6SMel Gorman 		if (dirty && !writeback)
992e2be15f6SMel Gorman 			nr_unqueued_dirty++;
993e2be15f6SMel Gorman 
994d04e8acdSMel Gorman 		/*
995d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
996d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
997d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
998d04e8acdSMel Gorman 		 * end of the LRU a second time.
999d04e8acdSMel Gorman 		 */
1000e2be15f6SMel Gorman 		mapping = page_mapping(page);
10011da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1002703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1003d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1004e2be15f6SMel Gorman 			nr_congested++;
1005e2be15f6SMel Gorman 
1006e2be15f6SMel Gorman 		/*
1007283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1008283aba9fSMel Gorman 		 * are three cases to consider.
1009e62e384eSMichal Hocko 		 *
1010283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1011283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1012283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1013283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1014283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1015283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1016283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1017b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1018b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1019c3b94f44SHugh Dickins 		 *
102097c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1021ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1022ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1023ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
102497c9341fSTejun Heo 		 *    reclaim and continue scanning.
1025283aba9fSMel Gorman 		 *
1026ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1027ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1028283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1029283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1030283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1031283aba9fSMel Gorman 		 *    would probably show more reasons.
1032283aba9fSMel Gorman 		 *
10337fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1034283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1035283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1036283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1037283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1038c55e8d03SJohannes Weiner 		 *
1039c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1040c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1041c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1042c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1043c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1044c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1045c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1046c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1047e62e384eSMichal Hocko 		 */
1048283aba9fSMel Gorman 		if (PageWriteback(page)) {
1049283aba9fSMel Gorman 			/* Case 1 above */
1050283aba9fSMel Gorman 			if (current_is_kswapd() &&
1051283aba9fSMel Gorman 			    PageReclaim(page) &&
1052599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1053b1a6f21eSMel Gorman 				nr_immediate++;
1054c55e8d03SJohannes Weiner 				goto activate_locked;
1055283aba9fSMel Gorman 
1056283aba9fSMel Gorman 			/* Case 2 above */
105797c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1058ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1059c3b94f44SHugh Dickins 				/*
1060c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1061c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1062c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1063c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1064c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1065c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1066c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1067c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1068c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1069c3b94f44SHugh Dickins 				 */
1070c3b94f44SHugh Dickins 				SetPageReclaim(page);
107192df3a72SMel Gorman 				nr_writeback++;
1072c55e8d03SJohannes Weiner 				goto activate_locked;
1073283aba9fSMel Gorman 
1074283aba9fSMel Gorman 			/* Case 3 above */
1075283aba9fSMel Gorman 			} else {
10767fadc820SHugh Dickins 				unlock_page(page);
1077c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
10787fadc820SHugh Dickins 				/* then go back and try same page again */
10797fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
10807fadc820SHugh Dickins 				continue;
1081e62e384eSMichal Hocko 			}
1082283aba9fSMel Gorman 		}
10831da177e4SLinus Torvalds 
108402c6de8dSMinchan Kim 		if (!force_reclaim)
10856a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
108602c6de8dSMinchan Kim 
1087dfc8d636SJohannes Weiner 		switch (references) {
1088dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
10891da177e4SLinus Torvalds 			goto activate_locked;
109064574746SJohannes Weiner 		case PAGEREF_KEEP:
10915bccd166SMichal Hocko 			nr_ref_keep++;
109264574746SJohannes Weiner 			goto keep_locked;
1093dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1094dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1095dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1096dfc8d636SJohannes Weiner 		}
10971da177e4SLinus Torvalds 
10981da177e4SLinus Torvalds 		/*
10991da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
11001da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1101802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
11021da177e4SLinus Torvalds 		 */
1103bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1104bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
110563eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
110663eb6b93SHugh Dickins 					goto keep_locked;
1107747552b1SHuang Ying 				if (PageTransHuge(page)) {
1108b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1109747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1110b8f593cdSHuang Ying 						goto activate_locked;
1111747552b1SHuang Ying 					/*
1112747552b1SHuang Ying 					 * Split pages without a PMD map right
1113747552b1SHuang Ying 					 * away. Chances are some or all of the
1114747552b1SHuang Ying 					 * tail pages can be freed without IO.
1115747552b1SHuang Ying 					 */
1116747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1117bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1118bd4c82c2SHuang Ying 								    page_list))
1119747552b1SHuang Ying 						goto activate_locked;
1120747552b1SHuang Ying 				}
11210f074658SMinchan Kim 				if (!add_to_swap(page)) {
11220f074658SMinchan Kim 					if (!PageTransHuge(page))
11231da177e4SLinus Torvalds 						goto activate_locked;
1124bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1125bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1126bd4c82c2SHuang Ying 								    page_list))
11270f074658SMinchan Kim 						goto activate_locked;
1128fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1129fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1130fe490cc0SHuang Ying #endif
11310f074658SMinchan Kim 					if (!add_to_swap(page))
11320f074658SMinchan Kim 						goto activate_locked;
11330f074658SMinchan Kim 				}
11340f074658SMinchan Kim 
113563eb6b93SHugh Dickins 				may_enter_fs = 1;
11361da177e4SLinus Torvalds 
1137e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
11381da177e4SLinus Torvalds 				mapping = page_mapping(page);
1139bd4c82c2SHuang Ying 			}
11407751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
11417751b2daSKirill A. Shutemov 			/* Split file THP */
11427751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
11437751b2daSKirill A. Shutemov 				goto keep_locked;
1144e2be15f6SMel Gorman 		}
11451da177e4SLinus Torvalds 
11461da177e4SLinus Torvalds 		/*
11471da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
11481da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
11491da177e4SLinus Torvalds 		 */
1150802a3a92SShaohua Li 		if (page_mapped(page)) {
1151bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1152bd4c82c2SHuang Ying 
1153bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1154bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1155bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
11565bccd166SMichal Hocko 				nr_unmap_fail++;
11571da177e4SLinus Torvalds 				goto activate_locked;
11581da177e4SLinus Torvalds 			}
11591da177e4SLinus Torvalds 		}
11601da177e4SLinus Torvalds 
11611da177e4SLinus Torvalds 		if (PageDirty(page)) {
1162ee72886dSMel Gorman 			/*
11634eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
11644eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
11654eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
11664eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
11674eda4823SJohannes Weiner 			 * write pages when we've encountered many
11684eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
11694eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
11704eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1171ee72886dSMel Gorman 			 */
1172f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
11734eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1174599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
117549ea7eb6SMel Gorman 				/*
117649ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
117749ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
117849ea7eb6SMel Gorman 				 * except we already have the page isolated
117949ea7eb6SMel Gorman 				 * and know it's dirty
118049ea7eb6SMel Gorman 				 */
1181c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
118249ea7eb6SMel Gorman 				SetPageReclaim(page);
118349ea7eb6SMel Gorman 
1184c55e8d03SJohannes Weiner 				goto activate_locked;
1185ee72886dSMel Gorman 			}
1186ee72886dSMel Gorman 
1187dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
11881da177e4SLinus Torvalds 				goto keep_locked;
11894dd4b920SAndrew Morton 			if (!may_enter_fs)
11901da177e4SLinus Torvalds 				goto keep_locked;
119152a8363eSChristoph Lameter 			if (!sc->may_writepage)
11921da177e4SLinus Torvalds 				goto keep_locked;
11931da177e4SLinus Torvalds 
1194d950c947SMel Gorman 			/*
1195d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1196d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1197d950c947SMel Gorman 			 * starts and then write it out here.
1198d950c947SMel Gorman 			 */
1199d950c947SMel Gorman 			try_to_unmap_flush_dirty();
12007d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
12011da177e4SLinus Torvalds 			case PAGE_KEEP:
12021da177e4SLinus Torvalds 				goto keep_locked;
12031da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
12041da177e4SLinus Torvalds 				goto activate_locked;
12051da177e4SLinus Torvalds 			case PAGE_SUCCESS:
12067d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
120741ac1999SMel Gorman 					goto keep;
12087d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
12091da177e4SLinus Torvalds 					goto keep;
12107d3579e8SKOSAKI Motohiro 
12111da177e4SLinus Torvalds 				/*
12121da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
12131da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
12141da177e4SLinus Torvalds 				 */
1215529ae9aaSNick Piggin 				if (!trylock_page(page))
12161da177e4SLinus Torvalds 					goto keep;
12171da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
12181da177e4SLinus Torvalds 					goto keep_locked;
12191da177e4SLinus Torvalds 				mapping = page_mapping(page);
12201da177e4SLinus Torvalds 			case PAGE_CLEAN:
12211da177e4SLinus Torvalds 				; /* try to free the page below */
12221da177e4SLinus Torvalds 			}
12231da177e4SLinus Torvalds 		}
12241da177e4SLinus Torvalds 
12251da177e4SLinus Torvalds 		/*
12261da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
12271da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
12281da177e4SLinus Torvalds 		 * the page as well.
12291da177e4SLinus Torvalds 		 *
12301da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
12311da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
12321da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
12331da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
12341da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
12351da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
12361da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
12371da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
12381da177e4SLinus Torvalds 		 *
12391da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
12401da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
12411da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
12421da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
12431da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
12441da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
12451da177e4SLinus Torvalds 		 */
1246266cf658SDavid Howells 		if (page_has_private(page)) {
12471da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
12481da177e4SLinus Torvalds 				goto activate_locked;
1249e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1250e286781dSNick Piggin 				unlock_page(page);
1251e286781dSNick Piggin 				if (put_page_testzero(page))
12521da177e4SLinus Torvalds 					goto free_it;
1253e286781dSNick Piggin 				else {
1254e286781dSNick Piggin 					/*
1255e286781dSNick Piggin 					 * rare race with speculative reference.
1256e286781dSNick Piggin 					 * the speculative reference will free
1257e286781dSNick Piggin 					 * this page shortly, so we may
1258e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1259e286781dSNick Piggin 					 * leave it off the LRU).
1260e286781dSNick Piggin 					 */
1261e286781dSNick Piggin 					nr_reclaimed++;
1262e286781dSNick Piggin 					continue;
1263e286781dSNick Piggin 				}
1264e286781dSNick Piggin 			}
12651da177e4SLinus Torvalds 		}
12661da177e4SLinus Torvalds 
1267802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1268802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1269802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
127049d2e9ccSChristoph Lameter 				goto keep_locked;
1271802a3a92SShaohua Li 			if (PageDirty(page)) {
1272802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1273802a3a92SShaohua Li 				goto keep_locked;
1274802a3a92SShaohua Li 			}
12751da177e4SLinus Torvalds 
1276802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
12772262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1278802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1279802a3a92SShaohua Li 			goto keep_locked;
1280a978d6f5SNick Piggin 		/*
1281a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1282a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1283a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1284a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1285a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1286a978d6f5SNick Piggin 		 */
128748c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1288e286781dSNick Piggin free_it:
128905ff5137SAndrew Morton 		nr_reclaimed++;
1290abe4c3b5SMel Gorman 
1291abe4c3b5SMel Gorman 		/*
1292abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1293abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1294abe4c3b5SMel Gorman 		 */
1295bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1296bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1297bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1298bd4c82c2SHuang Ying 		} else
1299abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
13001da177e4SLinus Torvalds 		continue;
13011da177e4SLinus Torvalds 
13021da177e4SLinus Torvalds activate_locked:
130368a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1304ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1305ad6b6704SMinchan Kim 						PageMlocked(page)))
1306a2c43eedSHugh Dickins 			try_to_free_swap(page);
1307309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1308ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
13091da177e4SLinus Torvalds 			SetPageActive(page);
13101da177e4SLinus Torvalds 			pgactivate++;
13112262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1312ad6b6704SMinchan Kim 		}
13131da177e4SLinus Torvalds keep_locked:
13141da177e4SLinus Torvalds 		unlock_page(page);
13151da177e4SLinus Torvalds keep:
13161da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1317309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
13181da177e4SLinus Torvalds 	}
1319abe4c3b5SMel Gorman 
1320747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
132172b252aeSMel Gorman 	try_to_unmap_flush();
13222d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1323abe4c3b5SMel Gorman 
13241da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1325f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
13260a31bc97SJohannes Weiner 
13273c710c1aSMichal Hocko 	if (stat) {
13283c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
13293c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
13303c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
13313c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
13323c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
13335bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
13345bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
13355bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
13363c710c1aSMichal Hocko 	}
133705ff5137SAndrew Morton 	return nr_reclaimed;
13381da177e4SLinus Torvalds }
13391da177e4SLinus Torvalds 
134002c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
134102c6de8dSMinchan Kim 					    struct list_head *page_list)
134202c6de8dSMinchan Kim {
134302c6de8dSMinchan Kim 	struct scan_control sc = {
134402c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
134502c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
134602c6de8dSMinchan Kim 		.may_unmap = 1,
134702c6de8dSMinchan Kim 	};
13483c710c1aSMichal Hocko 	unsigned long ret;
134902c6de8dSMinchan Kim 	struct page *page, *next;
135002c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
135102c6de8dSMinchan Kim 
135202c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1353117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1354b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
135502c6de8dSMinchan Kim 			ClearPageActive(page);
135602c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
135702c6de8dSMinchan Kim 		}
135802c6de8dSMinchan Kim 	}
135902c6de8dSMinchan Kim 
1360599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1361a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
136202c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1363599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
136402c6de8dSMinchan Kim 	return ret;
136502c6de8dSMinchan Kim }
136602c6de8dSMinchan Kim 
13675ad333ebSAndy Whitcroft /*
13685ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
13695ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
13705ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
13715ad333ebSAndy Whitcroft  *
13725ad333ebSAndy Whitcroft  * page:	page to consider
13735ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
13745ad333ebSAndy Whitcroft  *
13755ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
13765ad333ebSAndy Whitcroft  */
1377f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
13785ad333ebSAndy Whitcroft {
13795ad333ebSAndy Whitcroft 	int ret = -EINVAL;
13805ad333ebSAndy Whitcroft 
13815ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
13825ad333ebSAndy Whitcroft 	if (!PageLRU(page))
13835ad333ebSAndy Whitcroft 		return ret;
13845ad333ebSAndy Whitcroft 
1385e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1386e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1387894bc310SLee Schermerhorn 		return ret;
1388894bc310SLee Schermerhorn 
13895ad333ebSAndy Whitcroft 	ret = -EBUSY;
139008e552c6SKAMEZAWA Hiroyuki 
1391c8244935SMel Gorman 	/*
1392c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1393c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1394c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1395c8244935SMel Gorman 	 *
1396c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1397c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1398c8244935SMel Gorman 	 */
13991276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1400c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1401c8244935SMel Gorman 		if (PageWriteback(page))
140239deaf85SMinchan Kim 			return ret;
140339deaf85SMinchan Kim 
1404c8244935SMel Gorman 		if (PageDirty(page)) {
1405c8244935SMel Gorman 			struct address_space *mapping;
140669d763fcSMel Gorman 			bool migrate_dirty;
1407c8244935SMel Gorman 
1408c8244935SMel Gorman 			/*
1409c8244935SMel Gorman 			 * Only pages without mappings or that have a
1410c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
141169d763fcSMel Gorman 			 * without blocking. However, we can be racing with
141269d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
141369d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
141469d763fcSMel Gorman 			 * the page lock until after the page is removed
141569d763fcSMel Gorman 			 * from the page cache.
1416c8244935SMel Gorman 			 */
141769d763fcSMel Gorman 			if (!trylock_page(page))
141869d763fcSMel Gorman 				return ret;
141969d763fcSMel Gorman 
1420c8244935SMel Gorman 			mapping = page_mapping(page);
1421*145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
142269d763fcSMel Gorman 			unlock_page(page);
142369d763fcSMel Gorman 			if (!migrate_dirty)
1424c8244935SMel Gorman 				return ret;
1425c8244935SMel Gorman 		}
1426c8244935SMel Gorman 	}
1427c8244935SMel Gorman 
1428f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1429f80c0673SMinchan Kim 		return ret;
1430f80c0673SMinchan Kim 
14315ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
14325ad333ebSAndy Whitcroft 		/*
14335ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
14345ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
14355ad333ebSAndy Whitcroft 		 * page release code relies on it.
14365ad333ebSAndy Whitcroft 		 */
14375ad333ebSAndy Whitcroft 		ClearPageLRU(page);
14385ad333ebSAndy Whitcroft 		ret = 0;
14395ad333ebSAndy Whitcroft 	}
14405ad333ebSAndy Whitcroft 
14415ad333ebSAndy Whitcroft 	return ret;
14425ad333ebSAndy Whitcroft }
14435ad333ebSAndy Whitcroft 
14447ee36a14SMel Gorman 
14457ee36a14SMel Gorman /*
14467ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
14477ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
14487ee36a14SMel Gorman  */
14497ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1450b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
14517ee36a14SMel Gorman {
14527ee36a14SMel Gorman 	int zid;
14537ee36a14SMel Gorman 
14547ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
14557ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
14567ee36a14SMel Gorman 			continue;
14577ee36a14SMel Gorman 
14587ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1459b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1460b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1461b4536f0cSMichal Hocko #endif
14627ee36a14SMel Gorman 	}
14637ee36a14SMel Gorman 
14647ee36a14SMel Gorman }
14657ee36a14SMel Gorman 
146649d2e9ccSChristoph Lameter /*
1467a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
14681da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
14691da177e4SLinus Torvalds  * and working on them outside the LRU lock.
14701da177e4SLinus Torvalds  *
14711da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
14721da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
14731da177e4SLinus Torvalds  *
14741da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
14751da177e4SLinus Torvalds  *
1476791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
14775dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
14781da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1479f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1480fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
14815ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
14823cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
14831da177e4SLinus Torvalds  *
14841da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
14851da177e4SLinus Torvalds  */
148669e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
14875dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1488fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
14893cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
14901da177e4SLinus Torvalds {
149175b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
149269e05944SAndrew Morton 	unsigned long nr_taken = 0;
1493599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
14947cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
14953db65812SJohannes Weiner 	unsigned long skipped = 0;
1496791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1497b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
14981da177e4SLinus Torvalds 
1499791b48b6SMinchan Kim 	scan = 0;
1500791b48b6SMinchan Kim 	for (total_scan = 0;
1501791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1502791b48b6SMinchan Kim 	     total_scan++) {
15035ad333ebSAndy Whitcroft 		struct page *page;
15045ad333ebSAndy Whitcroft 
15051da177e4SLinus Torvalds 		page = lru_to_page(src);
15061da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
15071da177e4SLinus Torvalds 
1508309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
15098d438f96SNick Piggin 
1510b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1511b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
15127cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1513b2e18757SMel Gorman 			continue;
1514b2e18757SMel Gorman 		}
1515b2e18757SMel Gorman 
1516791b48b6SMinchan Kim 		/*
1517791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1518791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1519791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1520791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1521791b48b6SMinchan Kim 		 */
1522791b48b6SMinchan Kim 		scan++;
1523f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
15245ad333ebSAndy Whitcroft 		case 0:
1525599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1526599d0c95SMel Gorman 			nr_taken += nr_pages;
1527599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
15285ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
15295ad333ebSAndy Whitcroft 			break;
15307c8ee9a8SNick Piggin 
15315ad333ebSAndy Whitcroft 		case -EBUSY:
15325ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
15335ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
15345ad333ebSAndy Whitcroft 			continue;
15355ad333ebSAndy Whitcroft 
15365ad333ebSAndy Whitcroft 		default:
15375ad333ebSAndy Whitcroft 			BUG();
15385ad333ebSAndy Whitcroft 		}
15395ad333ebSAndy Whitcroft 	}
15401da177e4SLinus Torvalds 
1541b2e18757SMel Gorman 	/*
1542b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1543b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1544b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1545b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1546b2e18757SMel Gorman 	 * system at risk of premature OOM.
1547b2e18757SMel Gorman 	 */
15487cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
15497cc30fcfSMel Gorman 		int zid;
15507cc30fcfSMel Gorman 
15513db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
15527cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15537cc30fcfSMel Gorman 			if (!nr_skipped[zid])
15547cc30fcfSMel Gorman 				continue;
15557cc30fcfSMel Gorman 
15567cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
15571265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
15587cc30fcfSMel Gorman 		}
15597cc30fcfSMel Gorman 	}
1560791b48b6SMinchan Kim 	*nr_scanned = total_scan;
15611265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1562791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1563b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
15641da177e4SLinus Torvalds 	return nr_taken;
15651da177e4SLinus Torvalds }
15661da177e4SLinus Torvalds 
156762695a84SNick Piggin /**
156862695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
156962695a84SNick Piggin  * @page: page to isolate from its LRU list
157062695a84SNick Piggin  *
157162695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
157262695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
157362695a84SNick Piggin  *
157462695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
157562695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
157662695a84SNick Piggin  *
157762695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1578894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1579894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1580894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
158162695a84SNick Piggin  *
158262695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
158362695a84SNick Piggin  * found will be decremented.
158462695a84SNick Piggin  *
158562695a84SNick Piggin  * Restrictions:
1586a5d09bedSMike Rapoport  *
158762695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
158862695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
158962695a84SNick Piggin  *     without a stable reference).
159062695a84SNick Piggin  * (2) the lru_lock must not be held.
159162695a84SNick Piggin  * (3) interrupts must be enabled.
159262695a84SNick Piggin  */
159362695a84SNick Piggin int isolate_lru_page(struct page *page)
159462695a84SNick Piggin {
159562695a84SNick Piggin 	int ret = -EBUSY;
159662695a84SNick Piggin 
1597309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1598cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
15990c917313SKonstantin Khlebnikov 
160062695a84SNick Piggin 	if (PageLRU(page)) {
160162695a84SNick Piggin 		struct zone *zone = page_zone(page);
1602fa9add64SHugh Dickins 		struct lruvec *lruvec;
160362695a84SNick Piggin 
1604a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1605599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
16060c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1607894bc310SLee Schermerhorn 			int lru = page_lru(page);
16080c917313SKonstantin Khlebnikov 			get_page(page);
160962695a84SNick Piggin 			ClearPageLRU(page);
1610fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1611fa9add64SHugh Dickins 			ret = 0;
161262695a84SNick Piggin 		}
1613a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
161462695a84SNick Piggin 	}
161562695a84SNick Piggin 	return ret;
161662695a84SNick Piggin }
161762695a84SNick Piggin 
16185ad333ebSAndy Whitcroft /*
1619d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1620d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1621d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1622d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1623d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
162435cd7815SRik van Riel  */
1625599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
162635cd7815SRik van Riel 		struct scan_control *sc)
162735cd7815SRik van Riel {
162835cd7815SRik van Riel 	unsigned long inactive, isolated;
162935cd7815SRik van Riel 
163035cd7815SRik van Riel 	if (current_is_kswapd())
163135cd7815SRik van Riel 		return 0;
163235cd7815SRik van Riel 
163397c9341fSTejun Heo 	if (!sane_reclaim(sc))
163435cd7815SRik van Riel 		return 0;
163535cd7815SRik van Riel 
163635cd7815SRik van Riel 	if (file) {
1637599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1638599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
163935cd7815SRik van Riel 	} else {
1640599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1641599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
164235cd7815SRik van Riel 	}
164335cd7815SRik van Riel 
16443cf23841SFengguang Wu 	/*
16453cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
16463cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
16473cf23841SFengguang Wu 	 * deadlock.
16483cf23841SFengguang Wu 	 */
1649d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
16503cf23841SFengguang Wu 		inactive >>= 3;
16513cf23841SFengguang Wu 
165235cd7815SRik van Riel 	return isolated > inactive;
165335cd7815SRik van Riel }
165435cd7815SRik van Riel 
165566635629SMel Gorman static noinline_for_stack void
165675b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
165766635629SMel Gorman {
165827ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1659599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
16603f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
166166635629SMel Gorman 
166266635629SMel Gorman 	/*
166366635629SMel Gorman 	 * Put back any unfreeable pages.
166466635629SMel Gorman 	 */
166566635629SMel Gorman 	while (!list_empty(page_list)) {
16663f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
166766635629SMel Gorman 		int lru;
16683f79768fSHugh Dickins 
1669309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
167066635629SMel Gorman 		list_del(&page->lru);
167139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1672599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
167366635629SMel Gorman 			putback_lru_page(page);
1674599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
167566635629SMel Gorman 			continue;
167666635629SMel Gorman 		}
1677fa9add64SHugh Dickins 
1678599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1679fa9add64SHugh Dickins 
16807a608572SLinus Torvalds 		SetPageLRU(page);
168166635629SMel Gorman 		lru = page_lru(page);
1682fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1683fa9add64SHugh Dickins 
168466635629SMel Gorman 		if (is_active_lru(lru)) {
168566635629SMel Gorman 			int file = is_file_lru(lru);
16869992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
16879992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
168866635629SMel Gorman 		}
16892bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
16902bcf8879SHugh Dickins 			__ClearPageLRU(page);
16912bcf8879SHugh Dickins 			__ClearPageActive(page);
1692fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
16932bcf8879SHugh Dickins 
16942bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1695599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1696747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
16972bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1698599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
16992bcf8879SHugh Dickins 			} else
17002bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
170166635629SMel Gorman 		}
170266635629SMel Gorman 	}
170366635629SMel Gorman 
17043f79768fSHugh Dickins 	/*
17053f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
17063f79768fSHugh Dickins 	 */
17073f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
170866635629SMel Gorman }
170966635629SMel Gorman 
171066635629SMel Gorman /*
1711399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1712399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1713399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1714399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1715399ba0b9SNeilBrown  */
1716399ba0b9SNeilBrown static int current_may_throttle(void)
1717399ba0b9SNeilBrown {
1718399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1719399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1720399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1721399ba0b9SNeilBrown }
1722399ba0b9SNeilBrown 
1723399ba0b9SNeilBrown /*
1724b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
17251742f19fSAndrew Morton  * of reclaimed pages
17261da177e4SLinus Torvalds  */
172766635629SMel Gorman static noinline_for_stack unsigned long
17281a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
17299e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
17301da177e4SLinus Torvalds {
17311da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1732e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
173305ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1734e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
17353c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1736f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
17373cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1738599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17391a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1740db73ee0dSMichal Hocko 	bool stalled = false;
174178dc583dSKOSAKI Motohiro 
1742599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1743db73ee0dSMichal Hocko 		if (stalled)
1744db73ee0dSMichal Hocko 			return 0;
1745db73ee0dSMichal Hocko 
1746db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1747db73ee0dSMichal Hocko 		msleep(100);
1748db73ee0dSMichal Hocko 		stalled = true;
174935cd7815SRik van Riel 
175035cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
175135cd7815SRik van Riel 		if (fatal_signal_pending(current))
175235cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
175335cd7815SRik van Riel 	}
175435cd7815SRik van Riel 
17551da177e4SLinus Torvalds 	lru_add_drain();
1756f80c0673SMinchan Kim 
1757f80c0673SMinchan Kim 	if (!sc->may_unmap)
175861317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1759f80c0673SMinchan Kim 
1760599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17611da177e4SLinus Torvalds 
17625dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
17635dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
176495d918fcSKonstantin Khlebnikov 
1765599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
17669d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
176795d918fcSKonstantin Khlebnikov 
17682262185cSRoman Gushchin 	if (current_is_kswapd()) {
17692262185cSRoman Gushchin 		if (global_reclaim(sc))
1770599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
17712262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
17722262185cSRoman Gushchin 				   nr_scanned);
17732262185cSRoman Gushchin 	} else {
17742262185cSRoman Gushchin 		if (global_reclaim(sc))
1775599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
17762262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
17772262185cSRoman Gushchin 				   nr_scanned);
1778b35ea17bSKOSAKI Motohiro 	}
1779599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1780d563c050SHillf Danton 
1781d563c050SHillf Danton 	if (nr_taken == 0)
178266635629SMel Gorman 		return 0;
1783b35ea17bSKOSAKI Motohiro 
1784a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
17853c710c1aSMichal Hocko 				&stat, false);
1786c661b078SAndy Whitcroft 
1787599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
17883f79768fSHugh Dickins 
17892262185cSRoman Gushchin 	if (current_is_kswapd()) {
17902262185cSRoman Gushchin 		if (global_reclaim(sc))
1791599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
17922262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
17932262185cSRoman Gushchin 				   nr_reclaimed);
17942262185cSRoman Gushchin 	} else {
17952262185cSRoman Gushchin 		if (global_reclaim(sc))
1796599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
17972262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
17982262185cSRoman Gushchin 				   nr_reclaimed);
1799904249aaSYing Han 	}
1800a74609faSNick Piggin 
180127ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
18023f79768fSHugh Dickins 
1803599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
18043f79768fSHugh Dickins 
1805599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
18063f79768fSHugh Dickins 
1807747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
18082d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1809e11da5b4SMel Gorman 
181092df3a72SMel Gorman 	/*
18111c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
18121c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
18131c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
18141c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
18151c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
18161c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
18171c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
18181c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
18191c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
18201c610d5fSAndrey Ryabinin 	 */
18211c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
18221c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
18231c610d5fSAndrey Ryabinin 
1824d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
1825d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
1826d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1827d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
1828d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
1829d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
1830d108c772SAndrey Ryabinin 	if (file)
1831d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
18328e950282SMel Gorman 
1833599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1834d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
183505ff5137SAndrew Morton 	return nr_reclaimed;
18361da177e4SLinus Torvalds }
18371da177e4SLinus Torvalds 
18383bb1a852SMartin Bligh /*
18391cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
18401cfb419bSKAMEZAWA Hiroyuki  *
18411cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
18421cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
18431cfb419bSKAMEZAWA Hiroyuki  *
18441cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1845a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
18461cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1847a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
18481cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
18491cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
18501cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
18511cfb419bSKAMEZAWA Hiroyuki  *
18520139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
18531cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
18549d998b4fSMichal Hocko  *
18559d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
18561cfb419bSKAMEZAWA Hiroyuki  */
18571cfb419bSKAMEZAWA Hiroyuki 
18589d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
18593eb4140fSWu Fengguang 				     struct list_head *list,
18602bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
18613eb4140fSWu Fengguang 				     enum lru_list lru)
18623eb4140fSWu Fengguang {
1863599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18643eb4140fSWu Fengguang 	struct page *page;
1865fa9add64SHugh Dickins 	int nr_pages;
18669d998b4fSMichal Hocko 	int nr_moved = 0;
18673eb4140fSWu Fengguang 
18683eb4140fSWu Fengguang 	while (!list_empty(list)) {
18693eb4140fSWu Fengguang 		page = lru_to_page(list);
1870599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18713eb4140fSWu Fengguang 
1872309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
18733eb4140fSWu Fengguang 		SetPageLRU(page);
18743eb4140fSWu Fengguang 
1875fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
1876599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1877925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
18783eb4140fSWu Fengguang 
18792bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18802bcf8879SHugh Dickins 			__ClearPageLRU(page);
18812bcf8879SHugh Dickins 			__ClearPageActive(page);
1882fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18832bcf8879SHugh Dickins 
18842bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1885599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1886747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18872bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1888599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18892bcf8879SHugh Dickins 			} else
18902bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
18919d998b4fSMichal Hocko 		} else {
18929d998b4fSMichal Hocko 			nr_moved += nr_pages;
18933eb4140fSWu Fengguang 		}
18943eb4140fSWu Fengguang 	}
18959d5e6a9fSHugh Dickins 
18962262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
1897f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
18982262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
18992262185cSRoman Gushchin 				   nr_moved);
19002262185cSRoman Gushchin 	}
19019d998b4fSMichal Hocko 
19029d998b4fSMichal Hocko 	return nr_moved;
19033eb4140fSWu Fengguang }
19041cfb419bSKAMEZAWA Hiroyuki 
1905f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
19061a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
1907f16015fbSJohannes Weiner 			       struct scan_control *sc,
19089e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
19091cfb419bSKAMEZAWA Hiroyuki {
191044c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
1911f626012dSHugh Dickins 	unsigned long nr_scanned;
19126fe6b7e3SWu Fengguang 	unsigned long vm_flags;
19131cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
19148cab4754SWu Fengguang 	LIST_HEAD(l_active);
1915b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
19161cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
19171a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
19189d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
19199d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
1920f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19213cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1922599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19231cfb419bSKAMEZAWA Hiroyuki 
19241da177e4SLinus Torvalds 	lru_add_drain();
1925f80c0673SMinchan Kim 
1926f80c0673SMinchan Kim 	if (!sc->may_unmap)
192761317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1928f80c0673SMinchan Kim 
1929599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
1930925b7673SJohannes Weiner 
19315dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
19325dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
193389b5fae5SJohannes Weiner 
1934599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1935b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
19361cfb419bSKAMEZAWA Hiroyuki 
1937599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
19382262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
19399d5e6a9fSHugh Dickins 
1940599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19411da177e4SLinus Torvalds 
19421da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
19431da177e4SLinus Torvalds 		cond_resched();
19441da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
19451da177e4SLinus Torvalds 		list_del(&page->lru);
19467e9cd484SRik van Riel 
194739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1948894bc310SLee Schermerhorn 			putback_lru_page(page);
1949894bc310SLee Schermerhorn 			continue;
1950894bc310SLee Schermerhorn 		}
1951894bc310SLee Schermerhorn 
1952cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
1953cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
1954cc715d99SMel Gorman 				if (page_has_private(page))
1955cc715d99SMel Gorman 					try_to_release_page(page, 0);
1956cc715d99SMel Gorman 				unlock_page(page);
1957cc715d99SMel Gorman 			}
1958cc715d99SMel Gorman 		}
1959cc715d99SMel Gorman 
1960c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
1961c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
19629992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
19638cab4754SWu Fengguang 			/*
19648cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
19658cab4754SWu Fengguang 			 * give them one more trip around the active list. So
19668cab4754SWu Fengguang 			 * that executable code get better chances to stay in
19678cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
19688cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
19698cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
19708cab4754SWu Fengguang 			 * so we ignore them here.
19718cab4754SWu Fengguang 			 */
197241e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
19738cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
19748cab4754SWu Fengguang 				continue;
19758cab4754SWu Fengguang 			}
19768cab4754SWu Fengguang 		}
19777e9cd484SRik van Riel 
19785205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
19791da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
19801da177e4SLinus Torvalds 	}
19811da177e4SLinus Torvalds 
1982b555749aSAndrew Morton 	/*
19838cab4754SWu Fengguang 	 * Move pages back to the lru list.
1984b555749aSAndrew Morton 	 */
1985599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19864f98a2feSRik van Riel 	/*
19878cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
19888cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
19898cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
19907c0db9e9SJerome Marchand 	 * get_scan_count.
1991556adecbSRik van Riel 	 */
1992b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
1993556adecbSRik van Riel 
19949d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
19959d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1996599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1997599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19982bcf8879SHugh Dickins 
1999747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
20002d4894b5SMel Gorman 	free_unref_page_list(&l_hold);
20019d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
20029d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
20031da177e4SLinus Torvalds }
20041da177e4SLinus Torvalds 
200559dc76b0SRik van Riel /*
200659dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
200759dc76b0SRik van Riel  * to do too much work.
200814797e23SKOSAKI Motohiro  *
200959dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
201059dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
201159dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
201259dc76b0SRik van Riel  *
201359dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
201459dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
201559dc76b0SRik van Riel  *
20162a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
20172a2e4885SJohannes Weiner  *
201859dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
20193a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
202059dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
202159dc76b0SRik van Riel  *
202259dc76b0SRik van Riel  * total     target    max
202359dc76b0SRik van Riel  * memory    ratio     inactive
202459dc76b0SRik van Riel  * -------------------------------------
202559dc76b0SRik van Riel  *   10MB       1         5MB
202659dc76b0SRik van Riel  *  100MB       1        50MB
202759dc76b0SRik van Riel  *    1GB       3       250MB
202859dc76b0SRik van Riel  *   10GB      10       0.9GB
202959dc76b0SRik van Riel  *  100GB      31         3GB
203059dc76b0SRik van Riel  *    1TB     101        10GB
203159dc76b0SRik van Riel  *   10TB     320        32GB
203214797e23SKOSAKI Motohiro  */
2033f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
20342a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
20352a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
203614797e23SKOSAKI Motohiro {
2037fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
20382a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20392a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
20402a2e4885SJohannes Weiner 	unsigned long inactive, active;
20412a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
20422a2e4885SJohannes Weiner 	unsigned long refaults;
204359dc76b0SRik van Riel 	unsigned long gb;
204459dc76b0SRik van Riel 
204574e3f3c3SMinchan Kim 	/*
204674e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
204774e3f3c3SMinchan Kim 	 * is pointless.
204874e3f3c3SMinchan Kim 	 */
204959dc76b0SRik van Riel 	if (!file && !total_swap_pages)
205042e2e457SYaowei Bai 		return false;
205174e3f3c3SMinchan Kim 
2052fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2053fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2054f8d1a311SMel Gorman 
20552a2e4885SJohannes Weiner 	if (memcg)
2056ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
20572a2e4885SJohannes Weiner 	else
20582a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
20592a2e4885SJohannes Weiner 
20602a2e4885SJohannes Weiner 	/*
20612a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
20622a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
20632a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
20642a2e4885SJohannes Weiner 	 */
20652a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
20662a2e4885SJohannes Weiner 		inactive_ratio = 0;
20672a2e4885SJohannes Weiner 	} else {
206859dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
206959dc76b0SRik van Riel 		if (gb)
207059dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2071b39415b2SRik van Riel 		else
207259dc76b0SRik van Riel 			inactive_ratio = 1;
20732a2e4885SJohannes Weiner 	}
207459dc76b0SRik van Riel 
20752a2e4885SJohannes Weiner 	if (actual_reclaim)
20762a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2077fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2078fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2079fd538803SMichal Hocko 			inactive_ratio, file);
2080fd538803SMichal Hocko 
208159dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2082b39415b2SRik van Riel }
2083b39415b2SRik van Riel 
20844f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
20852a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
20862a2e4885SJohannes Weiner 				 struct scan_control *sc)
2087b69408e8SChristoph Lameter {
2088b39415b2SRik van Riel 	if (is_active_lru(lru)) {
20892a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
20902a2e4885SJohannes Weiner 					 memcg, sc, true))
20911a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2092556adecbSRik van Riel 		return 0;
2093556adecbSRik van Riel 	}
2094556adecbSRik van Riel 
20951a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2096b69408e8SChristoph Lameter }
2097b69408e8SChristoph Lameter 
20989a265114SJohannes Weiner enum scan_balance {
20999a265114SJohannes Weiner 	SCAN_EQUAL,
21009a265114SJohannes Weiner 	SCAN_FRACT,
21019a265114SJohannes Weiner 	SCAN_ANON,
21029a265114SJohannes Weiner 	SCAN_FILE,
21039a265114SJohannes Weiner };
21049a265114SJohannes Weiner 
21051da177e4SLinus Torvalds /*
21064f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
21074f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
21084f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
21094f98a2feSRik van Riel  * onto the active list instead of evict.
21104f98a2feSRik van Riel  *
2111be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2112be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
21134f98a2feSRik van Riel  */
211433377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
21156b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
21166b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
21174f98a2feSRik van Riel {
211833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
211990126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
21209a265114SJohannes Weiner 	u64 fraction[2];
21219a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2122599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21239a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
21249a265114SJohannes Weiner 	enum scan_balance scan_balance;
21250bf1457fSJohannes Weiner 	unsigned long anon, file;
21269a265114SJohannes Weiner 	unsigned long ap, fp;
21279a265114SJohannes Weiner 	enum lru_list lru;
212876a33fc3SShaohua Li 
212976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2130d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
21319a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
213276a33fc3SShaohua Li 		goto out;
213376a33fc3SShaohua Li 	}
21344f98a2feSRik van Riel 
213510316b31SJohannes Weiner 	/*
213610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
213710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
213810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
213910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
214010316b31SJohannes Weiner 	 * too expensive.
214110316b31SJohannes Weiner 	 */
214202695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
21439a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
214410316b31SJohannes Weiner 		goto out;
214510316b31SJohannes Weiner 	}
214610316b31SJohannes Weiner 
214710316b31SJohannes Weiner 	/*
214810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
214910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
215010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
215110316b31SJohannes Weiner 	 */
215202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
21539a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
215410316b31SJohannes Weiner 		goto out;
215510316b31SJohannes Weiner 	}
215610316b31SJohannes Weiner 
215711d16c25SJohannes Weiner 	/*
215862376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
215962376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
216062376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
216162376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
216262376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
216362376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
216462376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
216562376251SJohannes Weiner 	 */
216662376251SJohannes Weiner 	if (global_reclaim(sc)) {
2167599d0c95SMel Gorman 		unsigned long pgdatfile;
2168599d0c95SMel Gorman 		unsigned long pgdatfree;
2169599d0c95SMel Gorman 		int z;
2170599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
217162376251SJohannes Weiner 
2172599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2173599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2174599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
21752ab051e1SJerome Marchand 
2176599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2177599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
21786aa303deSMel Gorman 			if (!managed_zone(zone))
2179599d0c95SMel Gorman 				continue;
2180599d0c95SMel Gorman 
2181599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2182599d0c95SMel Gorman 		}
2183599d0c95SMel Gorman 
2184599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
218506226226SDavid Rientjes 			/*
218606226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
218706226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
218806226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
218906226226SDavid Rientjes 			 */
219006226226SDavid Rientjes 			if (!inactive_list_is_low(lruvec, false, memcg, sc, false) &&
219106226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
219206226226SDavid Rientjes 					>> sc->priority) {
219362376251SJohannes Weiner 				scan_balance = SCAN_ANON;
219462376251SJohannes Weiner 				goto out;
219562376251SJohannes Weiner 			}
219662376251SJohannes Weiner 		}
219706226226SDavid Rientjes 	}
219862376251SJohannes Weiner 
219962376251SJohannes Weiner 	/*
2200316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2201316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2202316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2203316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2204316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2205316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2206316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2207e9868505SRik van Riel 	 */
22082a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
220971ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
22109a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2211e9868505SRik van Riel 		goto out;
22124f98a2feSRik van Riel 	}
22134f98a2feSRik van Riel 
22149a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
22159a265114SJohannes Weiner 
22164f98a2feSRik van Riel 	/*
221758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
221858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
221958c37f6eSKOSAKI Motohiro 	 */
222002695175SJohannes Weiner 	anon_prio = swappiness;
222175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
222258c37f6eSKOSAKI Motohiro 
222358c37f6eSKOSAKI Motohiro 	/*
22244f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
22254f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
22264f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
22274f98a2feSRik van Riel 	 *
22284f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
22294f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
22304f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
22314f98a2feSRik van Riel 	 *
22324f98a2feSRik van Riel 	 * anon in [0], file in [1]
22334f98a2feSRik van Riel 	 */
22342ab051e1SJerome Marchand 
2235fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2236fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2237fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2238fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
22392ab051e1SJerome Marchand 
2240599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
224158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
22426e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
22436e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
22444f98a2feSRik van Riel 	}
22454f98a2feSRik van Riel 
22466e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
22476e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
22486e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
22494f98a2feSRik van Riel 	}
22504f98a2feSRik van Riel 
22514f98a2feSRik van Riel 	/*
225200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
225300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
225400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
22554f98a2feSRik van Riel 	 */
2256fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
22576e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
22584f98a2feSRik van Riel 
2259fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
22606e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2261599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
22624f98a2feSRik van Riel 
226376a33fc3SShaohua Li 	fraction[0] = ap;
226476a33fc3SShaohua Li 	fraction[1] = fp;
226576a33fc3SShaohua Li 	denominator = ap + fp + 1;
226676a33fc3SShaohua Li out:
22676b4f7799SJohannes Weiner 	*lru_pages = 0;
22684111304dSHugh Dickins 	for_each_evictable_lru(lru) {
22694111304dSHugh Dickins 		int file = is_file_lru(lru);
2270d778df51SJohannes Weiner 		unsigned long size;
227176a33fc3SShaohua Li 		unsigned long scan;
227276a33fc3SShaohua Li 
227371ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2274d778df51SJohannes Weiner 		scan = size >> sc->priority;
2275688035f7SJohannes Weiner 		/*
2276688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2277688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2278688035f7SJohannes Weiner 		 */
2279688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2280d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
22819a265114SJohannes Weiner 
22829a265114SJohannes Weiner 		switch (scan_balance) {
22839a265114SJohannes Weiner 		case SCAN_EQUAL:
22849a265114SJohannes Weiner 			/* Scan lists relative to size */
22859a265114SJohannes Weiner 			break;
22869a265114SJohannes Weiner 		case SCAN_FRACT:
22879a265114SJohannes Weiner 			/*
22889a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
22899a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
22909a265114SJohannes Weiner 			 */
22916f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
22926f04f48dSSuleiman Souhlal 					 denominator);
22939a265114SJohannes Weiner 			break;
22949a265114SJohannes Weiner 		case SCAN_FILE:
22959a265114SJohannes Weiner 		case SCAN_ANON:
22969a265114SJohannes Weiner 			/* Scan one type exclusively */
22976b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
22986b4f7799SJohannes Weiner 				size = 0;
22999a265114SJohannes Weiner 				scan = 0;
23006b4f7799SJohannes Weiner 			}
23019a265114SJohannes Weiner 			break;
23029a265114SJohannes Weiner 		default:
23039a265114SJohannes Weiner 			/* Look ma, no brain */
23049a265114SJohannes Weiner 			BUG();
23059a265114SJohannes Weiner 		}
23066b4f7799SJohannes Weiner 
23076b4f7799SJohannes Weiner 		*lru_pages += size;
23084111304dSHugh Dickins 		nr[lru] = scan;
230976a33fc3SShaohua Li 	}
23106e08a369SWu Fengguang }
23114f98a2feSRik van Riel 
23129b4f98cdSJohannes Weiner /*
2313a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
23149b4f98cdSJohannes Weiner  */
2315a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
23166b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
23179b4f98cdSJohannes Weiner {
2318ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
23199b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2320e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
23219b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
23229b4f98cdSJohannes Weiner 	enum lru_list lru;
23239b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
23249b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
23259b4f98cdSJohannes Weiner 	struct blk_plug plug;
23261a501907SMel Gorman 	bool scan_adjusted;
23279b4f98cdSJohannes Weiner 
232833377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
23299b4f98cdSJohannes Weiner 
2330e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2331e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2332e82e0561SMel Gorman 
23331a501907SMel Gorman 	/*
23341a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
23351a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
23361a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
23371a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
23381a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
23391a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
23401a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
23411a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
23421a501907SMel Gorman 	 * dropped to zero at the first pass.
23431a501907SMel Gorman 	 */
23441a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
23451a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
23461a501907SMel Gorman 
23479b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
23489b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
23499b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2350e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2351e82e0561SMel Gorman 		unsigned long nr_scanned;
2352e82e0561SMel Gorman 
23539b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
23549b4f98cdSJohannes Weiner 			if (nr[lru]) {
23559b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
23569b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
23579b4f98cdSJohannes Weiner 
23589b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
23592a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
23609b4f98cdSJohannes Weiner 			}
23619b4f98cdSJohannes Weiner 		}
2362e82e0561SMel Gorman 
2363bd041733SMichal Hocko 		cond_resched();
2364bd041733SMichal Hocko 
2365e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2366e82e0561SMel Gorman 			continue;
2367e82e0561SMel Gorman 
23689b4f98cdSJohannes Weiner 		/*
2369e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
23701a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2371e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2372e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2373e82e0561SMel Gorman 		 * proportional to the original scan target.
2374e82e0561SMel Gorman 		 */
2375e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2376e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2377e82e0561SMel Gorman 
23781a501907SMel Gorman 		/*
23791a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
23801a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
23811a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
23821a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
23831a501907SMel Gorman 		 */
23841a501907SMel Gorman 		if (!nr_file || !nr_anon)
23851a501907SMel Gorman 			break;
23861a501907SMel Gorman 
2387e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2388e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2389e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2390e82e0561SMel Gorman 			lru = LRU_BASE;
2391e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2392e82e0561SMel Gorman 		} else {
2393e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2394e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2395e82e0561SMel Gorman 			lru = LRU_FILE;
2396e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2397e82e0561SMel Gorman 		}
2398e82e0561SMel Gorman 
2399e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2400e82e0561SMel Gorman 		nr[lru] = 0;
2401e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2402e82e0561SMel Gorman 
2403e82e0561SMel Gorman 		/*
2404e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2405e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2406e82e0561SMel Gorman 		 */
2407e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2408e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2409e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2410e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2411e82e0561SMel Gorman 
2412e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2413e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2414e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2415e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2416e82e0561SMel Gorman 
2417e82e0561SMel Gorman 		scan_adjusted = true;
24189b4f98cdSJohannes Weiner 	}
24199b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
24209b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
24219b4f98cdSJohannes Weiner 
24229b4f98cdSJohannes Weiner 	/*
24239b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
24249b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
24259b4f98cdSJohannes Weiner 	 */
24262a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
24279b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
24289b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
24299b4f98cdSJohannes Weiner }
24309b4f98cdSJohannes Weiner 
243123b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
24329e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
243323b9da55SMel Gorman {
2434d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
243523b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
24369e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
243723b9da55SMel Gorman 		return true;
243823b9da55SMel Gorman 
243923b9da55SMel Gorman 	return false;
244023b9da55SMel Gorman }
244123b9da55SMel Gorman 
24424f98a2feSRik van Riel /*
244323b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
244423b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
244523b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
244623b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
244723b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
24483e7d3449SMel Gorman  */
2449a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
24503e7d3449SMel Gorman 					unsigned long nr_reclaimed,
24513e7d3449SMel Gorman 					unsigned long nr_scanned,
24523e7d3449SMel Gorman 					struct scan_control *sc)
24533e7d3449SMel Gorman {
24543e7d3449SMel Gorman 	unsigned long pages_for_compaction;
24553e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2456a9dd0a83SMel Gorman 	int z;
24573e7d3449SMel Gorman 
24583e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
24599e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
24603e7d3449SMel Gorman 		return false;
24613e7d3449SMel Gorman 
24622876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2463dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
24643e7d3449SMel Gorman 		/*
2465dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
24662876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
24672876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2468dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
24693e7d3449SMel Gorman 		 */
24703e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
24713e7d3449SMel Gorman 			return false;
24722876592fSMel Gorman 	} else {
24732876592fSMel Gorman 		/*
2474dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
24752876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
24762876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
24772876592fSMel Gorman 		 * pages that were scanned. This will return to the
24782876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
24792876592fSMel Gorman 		 * the resulting allocation attempt fails
24802876592fSMel Gorman 		 */
24812876592fSMel Gorman 		if (!nr_reclaimed)
24822876592fSMel Gorman 			return false;
24832876592fSMel Gorman 	}
24843e7d3449SMel Gorman 
24853e7d3449SMel Gorman 	/*
24863e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
24873e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
24883e7d3449SMel Gorman 	 */
24899861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2490a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2491ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2492a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
24933e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
24943e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
24953e7d3449SMel Gorman 		return true;
24963e7d3449SMel Gorman 
24973e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2498a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2499a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
25006aa303deSMel Gorman 		if (!managed_zone(zone))
2501a9dd0a83SMel Gorman 			continue;
2502a9dd0a83SMel Gorman 
2503a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2504cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
25053e7d3449SMel Gorman 		case COMPACT_CONTINUE:
25063e7d3449SMel Gorman 			return false;
25073e7d3449SMel Gorman 		default:
2508a9dd0a83SMel Gorman 			/* check next zone */
2509a9dd0a83SMel Gorman 			;
25103e7d3449SMel Gorman 		}
25113e7d3449SMel Gorman 	}
2512a9dd0a83SMel Gorman 	return true;
2513a9dd0a83SMel Gorman }
25143e7d3449SMel Gorman 
2515e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2516e3c1ac58SAndrey Ryabinin {
2517e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2518e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2519e3c1ac58SAndrey Ryabinin }
2520e3c1ac58SAndrey Ryabinin 
2521970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2522f16015fbSJohannes Weiner {
2523cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
25249b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
25252344d7e4SJohannes Weiner 	bool reclaimable = false;
25269b4f98cdSJohannes Weiner 
25279b4f98cdSJohannes Weiner 	do {
25285660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
25295660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2530ef8f2327SMel Gorman 			.pgdat = pgdat,
25319e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
25325660048cSJohannes Weiner 		};
2533a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2534694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
25355660048cSJohannes Weiner 
2536d108c772SAndrey Ryabinin 		memset(&sc->nr, 0, sizeof(sc->nr));
2537d108c772SAndrey Ryabinin 
25389b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
25399b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
25409b4f98cdSJohannes Weiner 
2541694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2542694fbc0fSAndrew Morton 		do {
25436b4f7799SJohannes Weiner 			unsigned long lru_pages;
25448e8ae645SJohannes Weiner 			unsigned long reclaimed;
2545cb731d6cSVladimir Davydov 			unsigned long scanned;
25469b4f98cdSJohannes Weiner 
2547241994edSJohannes Weiner 			if (mem_cgroup_low(root, memcg)) {
2548d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2549d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2550241994edSJohannes Weiner 					continue;
2551d6622f63SYisheng Xie 				}
2552e27be240SJohannes Weiner 				memcg_memory_event(memcg, MEMCG_LOW);
2553241994edSJohannes Weiner 			}
2554241994edSJohannes Weiner 
25558e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2556cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2557a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2558a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2559f9be23d6SKonstantin Khlebnikov 
2560b5afba29SVladimir Davydov 			if (memcg)
2561a9dd0a83SMel Gorman 				shrink_slab(sc->gfp_mask, pgdat->node_id,
25629092c71bSJosef Bacik 					    memcg, sc->priority);
2563cb731d6cSVladimir Davydov 
25648e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
25658e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
25668e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
25678e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
25688e8ae645SJohannes Weiner 
25695660048cSJohannes Weiner 			/*
2570a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2571a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2572a9dd0a83SMel Gorman 			 * node.
2573a394cb8eSMichal Hocko 			 *
2574a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2575a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2576a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2577a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
25785660048cSJohannes Weiner 			 */
2579a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2580a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
25815660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
25825660048cSJohannes Weiner 				break;
25835660048cSJohannes Weiner 			}
2584241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
258570ddf637SAnton Vorontsov 
2586b2e18757SMel Gorman 		if (global_reclaim(sc))
2587a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, NULL,
25889092c71bSJosef Bacik 				    sc->priority);
25896b4f7799SJohannes Weiner 
25906b4f7799SJohannes Weiner 		if (reclaim_state) {
2591cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
25926b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
25936b4f7799SJohannes Weiner 		}
25946b4f7799SJohannes Weiner 
25958e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
25968e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
259770ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
259870ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
259970ddf637SAnton Vorontsov 
26002344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
26012344d7e4SJohannes Weiner 			reclaimable = true;
26022344d7e4SJohannes Weiner 
2603e3c1ac58SAndrey Ryabinin 		if (current_is_kswapd()) {
2604d108c772SAndrey Ryabinin 			/*
2605e3c1ac58SAndrey Ryabinin 			 * If reclaim is isolating dirty pages under writeback,
2606e3c1ac58SAndrey Ryabinin 			 * it implies that the long-lived page allocation rate
2607e3c1ac58SAndrey Ryabinin 			 * is exceeding the page laundering rate. Either the
2608e3c1ac58SAndrey Ryabinin 			 * global limits are not being effective at throttling
2609e3c1ac58SAndrey Ryabinin 			 * processes due to the page distribution throughout
2610e3c1ac58SAndrey Ryabinin 			 * zones or there is heavy usage of a slow backing
2611e3c1ac58SAndrey Ryabinin 			 * device. The only option is to throttle from reclaim
2612e3c1ac58SAndrey Ryabinin 			 * context which is not ideal as there is no guarantee
2613d108c772SAndrey Ryabinin 			 * the dirtying process is throttled in the same way
2614d108c772SAndrey Ryabinin 			 * balance_dirty_pages() manages.
2615d108c772SAndrey Ryabinin 			 *
2616e3c1ac58SAndrey Ryabinin 			 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2617e3c1ac58SAndrey Ryabinin 			 * count the number of pages under pages flagged for
2618e3c1ac58SAndrey Ryabinin 			 * immediate reclaim and stall if any are encountered
2619e3c1ac58SAndrey Ryabinin 			 * in the nr_immediate check below.
2620d108c772SAndrey Ryabinin 			 */
2621d108c772SAndrey Ryabinin 			if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2622d108c772SAndrey Ryabinin 				set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2623d108c772SAndrey Ryabinin 
2624d108c772SAndrey Ryabinin 			/*
2625d108c772SAndrey Ryabinin 			 * Tag a node as congested if all the dirty pages
2626d108c772SAndrey Ryabinin 			 * scanned were backed by a congested BDI and
2627d108c772SAndrey Ryabinin 			 * wait_iff_congested will stall.
2628d108c772SAndrey Ryabinin 			 */
2629d108c772SAndrey Ryabinin 			if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2630d108c772SAndrey Ryabinin 				set_bit(PGDAT_CONGESTED, &pgdat->flags);
2631d108c772SAndrey Ryabinin 
2632d108c772SAndrey Ryabinin 			/* Allow kswapd to start writing pages during reclaim.*/
2633d108c772SAndrey Ryabinin 			if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2634d108c772SAndrey Ryabinin 				set_bit(PGDAT_DIRTY, &pgdat->flags);
2635d108c772SAndrey Ryabinin 
2636d108c772SAndrey Ryabinin 			/*
2637d108c772SAndrey Ryabinin 			 * If kswapd scans pages marked marked for immediate
2638d108c772SAndrey Ryabinin 			 * reclaim and under writeback (nr_immediate), it
2639d108c772SAndrey Ryabinin 			 * implies that pages are cycling through the LRU
2640d108c772SAndrey Ryabinin 			 * faster than they are written so also forcibly stall.
2641d108c772SAndrey Ryabinin 			 */
2642d108c772SAndrey Ryabinin 			if (sc->nr.immediate)
2643d108c772SAndrey Ryabinin 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2644d108c772SAndrey Ryabinin 		}
2645d108c772SAndrey Ryabinin 
2646d108c772SAndrey Ryabinin 		/*
2647e3c1ac58SAndrey Ryabinin 		 * Legacy memcg will stall in page writeback so avoid forcibly
2648e3c1ac58SAndrey Ryabinin 		 * stalling in wait_iff_congested().
2649e3c1ac58SAndrey Ryabinin 		 */
2650e3c1ac58SAndrey Ryabinin 		if (!global_reclaim(sc) && sane_reclaim(sc) &&
2651e3c1ac58SAndrey Ryabinin 		    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2652e3c1ac58SAndrey Ryabinin 			set_memcg_congestion(pgdat, root, true);
2653e3c1ac58SAndrey Ryabinin 
2654e3c1ac58SAndrey Ryabinin 		/*
2655d108c772SAndrey Ryabinin 		 * Stall direct reclaim for IO completions if underlying BDIs
2656d108c772SAndrey Ryabinin 		 * and node is congested. Allow kswapd to continue until it
2657d108c772SAndrey Ryabinin 		 * starts encountering unqueued dirty pages or cycling through
2658d108c772SAndrey Ryabinin 		 * the LRU too quickly.
2659d108c772SAndrey Ryabinin 		 */
2660d108c772SAndrey Ryabinin 		if (!sc->hibernation_mode && !current_is_kswapd() &&
2661e3c1ac58SAndrey Ryabinin 		   current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2662e3c1ac58SAndrey Ryabinin 			wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2663d108c772SAndrey Ryabinin 
2664a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
26659b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
26662344d7e4SJohannes Weiner 
2667c73322d0SJohannes Weiner 	/*
2668c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2669c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2670c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2671c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2672c73322d0SJohannes Weiner 	 */
2673c73322d0SJohannes Weiner 	if (reclaimable)
2674c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2675c73322d0SJohannes Weiner 
26762344d7e4SJohannes Weiner 	return reclaimable;
2677f16015fbSJohannes Weiner }
2678f16015fbSJohannes Weiner 
267953853e2dSVlastimil Babka /*
2680fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2681fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2682fdd4c614SVlastimil Babka  * should reclaim first.
268353853e2dSVlastimil Babka  */
26844f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2685fe4b1b24SMel Gorman {
268631483b6aSMel Gorman 	unsigned long watermark;
2687fdd4c614SVlastimil Babka 	enum compact_result suitable;
2688fe4b1b24SMel Gorman 
2689fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2690fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2691fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2692fdd4c614SVlastimil Babka 		return true;
2693fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2694fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2695fe4b1b24SMel Gorman 		return false;
2696fe4b1b24SMel Gorman 
2697fdd4c614SVlastimil Babka 	/*
2698fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2699fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2700fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2701fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2702fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2703fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2704fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2705fdd4c614SVlastimil Babka 	 */
2706fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2707fdd4c614SVlastimil Babka 
2708fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2709fe4b1b24SMel Gorman }
2710fe4b1b24SMel Gorman 
27111da177e4SLinus Torvalds /*
27121da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
27131da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
27141da177e4SLinus Torvalds  * request.
27151da177e4SLinus Torvalds  *
27161da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
27171da177e4SLinus Torvalds  * scan then give up on it.
27181da177e4SLinus Torvalds  */
27190a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
27201da177e4SLinus Torvalds {
2721dd1a239fSMel Gorman 	struct zoneref *z;
272254a6eb5cSMel Gorman 	struct zone *zone;
27230608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
27240608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2725619d0d76SWeijie Yang 	gfp_t orig_mask;
272679dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
27271cfb419bSKAMEZAWA Hiroyuki 
2728cc715d99SMel Gorman 	/*
2729cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2730cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2731cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2732cc715d99SMel Gorman 	 */
2733619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2734b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2735cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
27364f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2737b2e18757SMel Gorman 	}
2738cc715d99SMel Gorman 
2739d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2740b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2741b2e18757SMel Gorman 		/*
27421cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
27431cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
27441cfb419bSKAMEZAWA Hiroyuki 		 */
274589b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2746344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2747344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
27481da177e4SLinus Torvalds 				continue;
274965ec02cbSVladimir Davydov 
2750e0887c19SRik van Riel 			/*
2751e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2752e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2753e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2754e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2755e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2756c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2757c7cfa37bSCopot Alexandru 			 * page allocations.
2758e0887c19SRik van Riel 			 */
27590b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
27600b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
27614f588331SMel Gorman 			    compaction_ready(zone, sc)) {
27620b06496aSJohannes Weiner 				sc->compaction_ready = true;
2763e0887c19SRik van Riel 				continue;
2764e0887c19SRik van Riel 			}
27650b06496aSJohannes Weiner 
27660608f43dSAndrew Morton 			/*
276779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
276879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
276979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
277079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
277179dafcdcSMel Gorman 			 */
277279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
277379dafcdcSMel Gorman 				continue;
277479dafcdcSMel Gorman 
277579dafcdcSMel Gorman 			/*
27760608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
27770608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
27780608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
27790608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
27800608f43dSAndrew Morton 			 */
27810608f43dSAndrew Morton 			nr_soft_scanned = 0;
2782ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
27830608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
27840608f43dSAndrew Morton 						&nr_soft_scanned);
27850608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
27860608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2787ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2788ac34a1a3SKAMEZAWA Hiroyuki 		}
2789d149e3b2SYing Han 
279079dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
279179dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
279279dafcdcSMel Gorman 			continue;
279379dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2794970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
27951da177e4SLinus Torvalds 	}
2796e0c23279SMel Gorman 
279765ec02cbSVladimir Davydov 	/*
2798619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2799619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2800619d0d76SWeijie Yang 	 */
2801619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
28021da177e4SLinus Torvalds }
28031da177e4SLinus Torvalds 
28042a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
28052a2e4885SJohannes Weiner {
28062a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
28072a2e4885SJohannes Weiner 
28082a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
28092a2e4885SJohannes Weiner 	do {
28102a2e4885SJohannes Weiner 		unsigned long refaults;
28112a2e4885SJohannes Weiner 		struct lruvec *lruvec;
28122a2e4885SJohannes Weiner 
28132a2e4885SJohannes Weiner 		if (memcg)
2814ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
28152a2e4885SJohannes Weiner 		else
28162a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
28172a2e4885SJohannes Weiner 
28182a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
28192a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
28202a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
28212a2e4885SJohannes Weiner }
28222a2e4885SJohannes Weiner 
28231da177e4SLinus Torvalds /*
28241da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
28251da177e4SLinus Torvalds  *
28261da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
28271da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
28281da177e4SLinus Torvalds  *
28291da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
28301da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
28315b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
28325b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
28335b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
28345b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2835a41f24eaSNishanth Aravamudan  *
2836a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2837a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
28381da177e4SLinus Torvalds  */
2839dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
28403115cd91SVladimir Davydov 					  struct scan_control *sc)
28411da177e4SLinus Torvalds {
2842241994edSJohannes Weiner 	int initial_priority = sc->priority;
28432a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
28442a2e4885SJohannes Weiner 	struct zoneref *z;
28452a2e4885SJohannes Weiner 	struct zone *zone;
2846241994edSJohannes Weiner retry:
2847873b4771SKeika Kobayashi 	delayacct_freepages_start();
2848873b4771SKeika Kobayashi 
284989b5fae5SJohannes Weiner 	if (global_reclaim(sc))
28507cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
28511da177e4SLinus Torvalds 
28529e3b2f8cSKonstantin Khlebnikov 	do {
285370ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
285470ddf637SAnton Vorontsov 				sc->priority);
285566e1707bSBalbir Singh 		sc->nr_scanned = 0;
28560a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2857e0c23279SMel Gorman 
2858bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
28590b06496aSJohannes Weiner 			break;
28600b06496aSJohannes Weiner 
28610b06496aSJohannes Weiner 		if (sc->compaction_ready)
28620b06496aSJohannes Weiner 			break;
28631da177e4SLinus Torvalds 
28641da177e4SLinus Torvalds 		/*
28650e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
28660e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
28670e50ce3bSMinchan Kim 		 */
28680e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
28690e50ce3bSMinchan Kim 			sc->may_writepage = 1;
28700b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
2871bb21c7ceSKOSAKI Motohiro 
28722a2e4885SJohannes Weiner 	last_pgdat = NULL;
28732a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
28742a2e4885SJohannes Weiner 					sc->nodemask) {
28752a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
28762a2e4885SJohannes Weiner 			continue;
28772a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
28782a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
2879e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
28802a2e4885SJohannes Weiner 	}
28812a2e4885SJohannes Weiner 
2882873b4771SKeika Kobayashi 	delayacct_freepages_end();
2883873b4771SKeika Kobayashi 
2884bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
2885bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
2886bb21c7ceSKOSAKI Motohiro 
28870cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
28880b06496aSJohannes Weiner 	if (sc->compaction_ready)
28897335084dSMel Gorman 		return 1;
28907335084dSMel Gorman 
2891241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
2892d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
2893241994edSJohannes Weiner 		sc->priority = initial_priority;
2894d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
2895d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
2896241994edSJohannes Weiner 		goto retry;
2897241994edSJohannes Weiner 	}
2898241994edSJohannes Weiner 
2899bb21c7ceSKOSAKI Motohiro 	return 0;
29001da177e4SLinus Torvalds }
29011da177e4SLinus Torvalds 
2902c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
29035515061dSMel Gorman {
29045515061dSMel Gorman 	struct zone *zone;
29055515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
29065515061dSMel Gorman 	unsigned long free_pages = 0;
29075515061dSMel Gorman 	int i;
29085515061dSMel Gorman 	bool wmark_ok;
29095515061dSMel Gorman 
2910c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
2911c73322d0SJohannes Weiner 		return true;
2912c73322d0SJohannes Weiner 
29135515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
29145515061dSMel Gorman 		zone = &pgdat->node_zones[i];
2915d450abd8SJohannes Weiner 		if (!managed_zone(zone))
2916d450abd8SJohannes Weiner 			continue;
2917d450abd8SJohannes Weiner 
2918d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
2919675becceSMel Gorman 			continue;
2920675becceSMel Gorman 
29215515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
29225515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
29235515061dSMel Gorman 	}
29245515061dSMel Gorman 
2925675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
2926675becceSMel Gorman 	if (!pfmemalloc_reserve)
2927675becceSMel Gorman 		return true;
2928675becceSMel Gorman 
29295515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
29305515061dSMel Gorman 
29315515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
29325515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
293338087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
29345515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
29355515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
29365515061dSMel Gorman 	}
29375515061dSMel Gorman 
29385515061dSMel Gorman 	return wmark_ok;
29395515061dSMel Gorman }
29405515061dSMel Gorman 
29415515061dSMel Gorman /*
29425515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
29435515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
29445515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
294550694c28SMel Gorman  * when the low watermark is reached.
294650694c28SMel Gorman  *
294750694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
294850694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
29495515061dSMel Gorman  */
295050694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
29515515061dSMel Gorman 					nodemask_t *nodemask)
29525515061dSMel Gorman {
2953675becceSMel Gorman 	struct zoneref *z;
29545515061dSMel Gorman 	struct zone *zone;
2955675becceSMel Gorman 	pg_data_t *pgdat = NULL;
29565515061dSMel Gorman 
29575515061dSMel Gorman 	/*
29585515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
29595515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
29605515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
29615515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
29625515061dSMel Gorman 	 * processes to block on log_wait_commit().
29635515061dSMel Gorman 	 */
29645515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
296550694c28SMel Gorman 		goto out;
296650694c28SMel Gorman 
296750694c28SMel Gorman 	/*
296850694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
296950694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
297050694c28SMel Gorman 	 */
297150694c28SMel Gorman 	if (fatal_signal_pending(current))
297250694c28SMel Gorman 		goto out;
29735515061dSMel Gorman 
2974675becceSMel Gorman 	/*
2975675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
2976675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
2977675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
2978675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
2979675becceSMel Gorman 	 *
2980675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
2981675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
2982675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
2983675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
2984675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
2985675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
2986675becceSMel Gorman 	 * should make reasonable progress.
2987675becceSMel Gorman 	 */
2988675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
298917636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
2990675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
2991675becceSMel Gorman 			continue;
2992675becceSMel Gorman 
2993675becceSMel Gorman 		/* Throttle based on the first usable node */
29945515061dSMel Gorman 		pgdat = zone->zone_pgdat;
2995c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
299650694c28SMel Gorman 			goto out;
2997675becceSMel Gorman 		break;
2998675becceSMel Gorman 	}
2999675becceSMel Gorman 
3000675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3001675becceSMel Gorman 	if (!pgdat)
3002675becceSMel Gorman 		goto out;
30035515061dSMel Gorman 
300468243e76SMel Gorman 	/* Account for the throttling */
300568243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
300668243e76SMel Gorman 
30075515061dSMel Gorman 	/*
30085515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
30095515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
30105515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
30115515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
30125515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
30135515061dSMel Gorman 	 * second before continuing.
30145515061dSMel Gorman 	 */
30155515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
30165515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3017c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
301850694c28SMel Gorman 
301950694c28SMel Gorman 		goto check_pending;
30205515061dSMel Gorman 	}
30215515061dSMel Gorman 
30225515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
30235515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3024c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
302550694c28SMel Gorman 
302650694c28SMel Gorman check_pending:
302750694c28SMel Gorman 	if (fatal_signal_pending(current))
302850694c28SMel Gorman 		return true;
302950694c28SMel Gorman 
303050694c28SMel Gorman out:
303150694c28SMel Gorman 	return false;
30325515061dSMel Gorman }
30335515061dSMel Gorman 
3034dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3035327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
303666e1707bSBalbir Singh {
303733906bc5SMel Gorman 	unsigned long nr_reclaimed;
303866e1707bSBalbir Singh 	struct scan_control sc = {
303922fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3040f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3041b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3042ee814fe2SJohannes Weiner 		.order = order,
3043ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3044ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3045ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3046a6dc60f8SJohannes Weiner 		.may_unmap = 1,
30472e2e4259SKOSAKI Motohiro 		.may_swap = 1,
304866e1707bSBalbir Singh 	};
304966e1707bSBalbir Singh 
30505515061dSMel Gorman 	/*
305150694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
305250694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
305350694c28SMel Gorman 	 * point.
30545515061dSMel Gorman 	 */
3055f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
30565515061dSMel Gorman 		return 1;
30575515061dSMel Gorman 
305833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
305933906bc5SMel Gorman 				sc.may_writepage,
3060f2f43e56SNick Desaulniers 				sc.gfp_mask,
3061e5146b12SMel Gorman 				sc.reclaim_idx);
306233906bc5SMel Gorman 
30633115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
306433906bc5SMel Gorman 
306533906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
306633906bc5SMel Gorman 
306733906bc5SMel Gorman 	return nr_reclaimed;
306866e1707bSBalbir Singh }
306966e1707bSBalbir Singh 
3070c255a458SAndrew Morton #ifdef CONFIG_MEMCG
307166e1707bSBalbir Singh 
3072a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
30734e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3074ef8f2327SMel Gorman 						pg_data_t *pgdat,
30750ae5e89cSYing Han 						unsigned long *nr_scanned)
30764e416953SBalbir Singh {
30774e416953SBalbir Singh 	struct scan_control sc = {
3078b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3079ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
30804e416953SBalbir Singh 		.may_writepage = !laptop_mode,
30814e416953SBalbir Singh 		.may_unmap = 1,
3082b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
30834e416953SBalbir Singh 		.may_swap = !noswap,
30844e416953SBalbir Singh 	};
30856b4f7799SJohannes Weiner 	unsigned long lru_pages;
30860ae5e89cSYing Han 
30874e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
30884e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3089bdce6d9eSKOSAKI Motohiro 
30909e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3091bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3092e5146b12SMel Gorman 						      sc.gfp_mask,
3093e5146b12SMel Gorman 						      sc.reclaim_idx);
3094bdce6d9eSKOSAKI Motohiro 
30954e416953SBalbir Singh 	/*
30964e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
30974e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3098a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
30994e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
31004e416953SBalbir Singh 	 * the priority and make it zero.
31014e416953SBalbir Singh 	 */
3102ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3103bdce6d9eSKOSAKI Motohiro 
3104bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3105bdce6d9eSKOSAKI Motohiro 
31060ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
31074e416953SBalbir Singh 	return sc.nr_reclaimed;
31084e416953SBalbir Singh }
31094e416953SBalbir Singh 
311072835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3111b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
31128c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3113b70a2a21SJohannes Weiner 					   bool may_swap)
311466e1707bSBalbir Singh {
31154e416953SBalbir Singh 	struct zonelist *zonelist;
3116bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3117889976dbSYing Han 	int nid;
3118499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
311966e1707bSBalbir Singh 	struct scan_control sc = {
3120b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
31217dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3122ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3123b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3124ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3125ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
312666e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3127a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3128b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3129a09ed5e0SYing Han 	};
313066e1707bSBalbir Singh 
3131889976dbSYing Han 	/*
3132889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3133889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3134889976dbSYing Han 	 * scan does not need to be the current node.
3135889976dbSYing Han 	 */
313672835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3137889976dbSYing Han 
3138c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3139bdce6d9eSKOSAKI Motohiro 
3140bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3141bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3142e5146b12SMel Gorman 					    sc.gfp_mask,
3143e5146b12SMel Gorman 					    sc.reclaim_idx);
3144bdce6d9eSKOSAKI Motohiro 
3145499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
31463115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3147499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3148bdce6d9eSKOSAKI Motohiro 
3149bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3150bdce6d9eSKOSAKI Motohiro 
3151bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
315266e1707bSBalbir Singh }
315366e1707bSBalbir Singh #endif
315466e1707bSBalbir Singh 
31551d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3156ef8f2327SMel Gorman 				struct scan_control *sc)
3157f16015fbSJohannes Weiner {
3158b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3159b95a2f2dSJohannes Weiner 
3160b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3161b95a2f2dSJohannes Weiner 		return;
3162b95a2f2dSJohannes Weiner 
3163b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3164b95a2f2dSJohannes Weiner 	do {
3165ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3166f16015fbSJohannes Weiner 
31672a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
31681a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
31699e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3170b95a2f2dSJohannes Weiner 
3171b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3172b95a2f2dSJohannes Weiner 	} while (memcg);
3173f16015fbSJohannes Weiner }
3174f16015fbSJohannes Weiner 
3175e716f2ebSMel Gorman /*
3176e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3177e716f2ebSMel Gorman  * and classzone_idx
3178e716f2ebSMel Gorman  */
3179e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
318060cefed4SJohannes Weiner {
3181e716f2ebSMel Gorman 	int i;
3182e716f2ebSMel Gorman 	unsigned long mark = -1;
3183e716f2ebSMel Gorman 	struct zone *zone;
318460cefed4SJohannes Weiner 
3185e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3186e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
31876256c6b4SMel Gorman 
3188e716f2ebSMel Gorman 		if (!managed_zone(zone))
3189e716f2ebSMel Gorman 			continue;
3190e716f2ebSMel Gorman 
3191e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3192e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
31936256c6b4SMel Gorman 			return true;
319460cefed4SJohannes Weiner 	}
319560cefed4SJohannes Weiner 
3196e716f2ebSMel Gorman 	/*
3197e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3198e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3199e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3200e716f2ebSMel Gorman 	 */
3201e716f2ebSMel Gorman 	if (mark == -1)
3202e716f2ebSMel Gorman 		return true;
3203e716f2ebSMel Gorman 
3204e716f2ebSMel Gorman 	return false;
3205e716f2ebSMel Gorman }
3206e716f2ebSMel Gorman 
3207631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3208631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3209631b6e08SMel Gorman {
3210631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3211631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3212631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3213631b6e08SMel Gorman }
3214631b6e08SMel Gorman 
32151741c877SMel Gorman /*
32165515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
32175515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
32185515061dSMel Gorman  *
32195515061dSMel Gorman  * Returns true if kswapd is ready to sleep
32205515061dSMel Gorman  */
3221d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3222f50de2d3SMel Gorman {
32235515061dSMel Gorman 	/*
32249e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3225c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
32269e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
32279e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
32289e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
32299e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
32309e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
32319e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
32329e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
32339e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
32349e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
32355515061dSMel Gorman 	 */
32369e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
32379e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3238f50de2d3SMel Gorman 
3239c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3240c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3241c73322d0SJohannes Weiner 		return true;
3242c73322d0SJohannes Weiner 
3243e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3244631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3245333b0a45SShantanu Goel 		return true;
32461d82de61SMel Gorman 	}
32471d82de61SMel Gorman 
3248333b0a45SShantanu Goel 	return false;
3249f50de2d3SMel Gorman }
3250f50de2d3SMel Gorman 
32511da177e4SLinus Torvalds /*
32521d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
32531d82de61SMel Gorman  * zone that is currently unbalanced.
3254b8e83b94SMel Gorman  *
3255b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3256283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3257283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
325875485363SMel Gorman  */
32591d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3260accf6242SVlastimil Babka 			       struct scan_control *sc)
326175485363SMel Gorman {
32621d82de61SMel Gorman 	struct zone *zone;
32631d82de61SMel Gorman 	int z;
326475485363SMel Gorman 
32651d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
32661d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3267970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
32681d82de61SMel Gorman 		zone = pgdat->node_zones + z;
32696aa303deSMel Gorman 		if (!managed_zone(zone))
32701d82de61SMel Gorman 			continue;
32717c954f6dSMel Gorman 
32721d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
32737c954f6dSMel Gorman 	}
32747c954f6dSMel Gorman 
32751d82de61SMel Gorman 	/*
32761d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
32771d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
32781d82de61SMel Gorman 	 */
3279970a39a3SMel Gorman 	shrink_node(pgdat, sc);
32801d82de61SMel Gorman 
32811d82de61SMel Gorman 	/*
32821d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
32831d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
32841d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
32851d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
32861d82de61SMel Gorman 	 * can direct reclaim/compact.
32871d82de61SMel Gorman 	 */
32889861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
32891d82de61SMel Gorman 		sc->order = 0;
32901d82de61SMel Gorman 
3291b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
329275485363SMel Gorman }
329375485363SMel Gorman 
329475485363SMel Gorman /*
32951d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
32961d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
32971d82de61SMel Gorman  * balanced.
32981da177e4SLinus Torvalds  *
32991d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
33001da177e4SLinus Torvalds  *
33011da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
330241858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
33031d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
33041d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
33051d82de61SMel Gorman  * balanced.
33061da177e4SLinus Torvalds  */
3307accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
33081da177e4SLinus Torvalds {
33091da177e4SLinus Torvalds 	int i;
33100608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
33110608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
33121d82de61SMel Gorman 	struct zone *zone;
3313179e9639SAndrew Morton 	struct scan_control sc = {
3314179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3315ee814fe2SJohannes Weiner 		.order = order,
3316b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3317ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3318a6dc60f8SJohannes Weiner 		.may_unmap = 1,
33192e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3320179e9639SAndrew Morton 	};
3321f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
33221da177e4SLinus Torvalds 
33239e3b2f8cSKonstantin Khlebnikov 	do {
3324c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3325b8e83b94SMel Gorman 		bool raise_priority = true;
3326b8e83b94SMel Gorman 
332784c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
33281da177e4SLinus Torvalds 
332986c79f6bSMel Gorman 		/*
333084c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
333184c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
333284c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
333384c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
333484c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
333584c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
333684c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
333784c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
333886c79f6bSMel Gorman 		 */
333986c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
334086c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
334186c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
33426aa303deSMel Gorman 				if (!managed_zone(zone))
334386c79f6bSMel Gorman 					continue;
334486c79f6bSMel Gorman 
3345970a39a3SMel Gorman 				sc.reclaim_idx = i;
334686c79f6bSMel Gorman 				break;
334786c79f6bSMel Gorman 			}
334886c79f6bSMel Gorman 		}
334986c79f6bSMel Gorman 
335086c79f6bSMel Gorman 		/*
3351e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3352e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3353e716f2ebSMel Gorman 		 * have adjusted it.
335486c79f6bSMel Gorman 		 */
3355e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
33561da177e4SLinus Torvalds 			goto out;
3357e1dbeda6SAndrew Morton 
33581da177e4SLinus Torvalds 		/*
33591d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
33601d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
33611d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
33621d82de61SMel Gorman 		 * about consistent aging.
33631d82de61SMel Gorman 		 */
3364ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
33651d82de61SMel Gorman 
33661d82de61SMel Gorman 		/*
3367b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3368b7ea3c41SMel Gorman 		 * even in laptop mode.
3369b7ea3c41SMel Gorman 		 */
3370047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3371b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3372b7ea3c41SMel Gorman 
33731d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
33741da177e4SLinus Torvalds 		sc.nr_scanned = 0;
33750608f43dSAndrew Morton 		nr_soft_scanned = 0;
3376ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
33771d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
33780608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
33790608f43dSAndrew Morton 
338032a4330dSRik van Riel 		/*
33811d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
33821d82de61SMel Gorman 		 * enough pages are already being scanned that that high
33831d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
338432a4330dSRik van Riel 		 */
3385970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3386b8e83b94SMel Gorman 			raise_priority = false;
3387d7868daeSMel Gorman 
33885515061dSMel Gorman 		/*
33895515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
33905515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
33915515061dSMel Gorman 		 * able to safely make forward progress. Wake them
33925515061dSMel Gorman 		 */
33935515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3394c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3395cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
33965515061dSMel Gorman 
3397b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
3398b8e83b94SMel Gorman 		if (try_to_freeze() || kthread_should_stop())
3399b8e83b94SMel Gorman 			break;
3400b8e83b94SMel Gorman 
3401b8e83b94SMel Gorman 		/*
3402b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3403b8e83b94SMel Gorman 		 * progress in reclaiming pages
3404b8e83b94SMel Gorman 		 */
3405c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3406c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3407b8e83b94SMel Gorman 			sc.priority--;
34081d82de61SMel Gorman 	} while (sc.priority >= 1);
34091da177e4SLinus Torvalds 
3410c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3411c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3412c73322d0SJohannes Weiner 
3413b8e83b94SMel Gorman out:
34142a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
34150abdee2bSMel Gorman 	/*
34161d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
34171d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
34181d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
34191d82de61SMel Gorman 	 * remain at the higher level.
34200abdee2bSMel Gorman 	 */
34211d82de61SMel Gorman 	return sc.order;
34221da177e4SLinus Torvalds }
34231da177e4SLinus Torvalds 
3424e716f2ebSMel Gorman /*
3425e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3426e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3427e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3428e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3429e716f2ebSMel Gorman  * was recently woke for.
3430e716f2ebSMel Gorman  */
3431e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3432e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3433e716f2ebSMel Gorman {
3434e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3435e716f2ebSMel Gorman 		return classzone_idx;
3436e716f2ebSMel Gorman 
3437e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3438e716f2ebSMel Gorman }
3439e716f2ebSMel Gorman 
344038087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
344138087d9bSMel Gorman 				unsigned int classzone_idx)
3442f0bc0a60SKOSAKI Motohiro {
3443f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3444f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3445f0bc0a60SKOSAKI Motohiro 
3446f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3447f0bc0a60SKOSAKI Motohiro 		return;
3448f0bc0a60SKOSAKI Motohiro 
3449f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3450f0bc0a60SKOSAKI Motohiro 
3451333b0a45SShantanu Goel 	/*
3452333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3453333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3454333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3455333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3456333b0a45SShantanu Goel 	 * succeed.
3457333b0a45SShantanu Goel 	 */
3458d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3459fd901c95SVlastimil Babka 		/*
3460fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3461fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3462fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3463fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3464fd901c95SVlastimil Babka 		 */
3465fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3466fd901c95SVlastimil Babka 
3467fd901c95SVlastimil Babka 		/*
3468fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3469fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3470fd901c95SVlastimil Babka 		 */
347138087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3472fd901c95SVlastimil Babka 
3473f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
347438087d9bSMel Gorman 
347538087d9bSMel Gorman 		/*
347638087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
347738087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
347838087d9bSMel Gorman 		 * the previous request that slept prematurely.
347938087d9bSMel Gorman 		 */
348038087d9bSMel Gorman 		if (remaining) {
3481e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
348238087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
348338087d9bSMel Gorman 		}
348438087d9bSMel Gorman 
3485f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3486f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3487f0bc0a60SKOSAKI Motohiro 	}
3488f0bc0a60SKOSAKI Motohiro 
3489f0bc0a60SKOSAKI Motohiro 	/*
3490f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3491f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3492f0bc0a60SKOSAKI Motohiro 	 */
3493d9f21d42SMel Gorman 	if (!remaining &&
3494d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3495f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3496f0bc0a60SKOSAKI Motohiro 
3497f0bc0a60SKOSAKI Motohiro 		/*
3498f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3499f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3500f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3501f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3502f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3503f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3504f0bc0a60SKOSAKI Motohiro 		 */
3505f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
35061c7e7f6cSAaditya Kumar 
35071c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3508f0bc0a60SKOSAKI Motohiro 			schedule();
35091c7e7f6cSAaditya Kumar 
3510f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3511f0bc0a60SKOSAKI Motohiro 	} else {
3512f0bc0a60SKOSAKI Motohiro 		if (remaining)
3513f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3514f0bc0a60SKOSAKI Motohiro 		else
3515f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3516f0bc0a60SKOSAKI Motohiro 	}
3517f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3518f0bc0a60SKOSAKI Motohiro }
3519f0bc0a60SKOSAKI Motohiro 
35201da177e4SLinus Torvalds /*
35211da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
35221da177e4SLinus Torvalds  * from the init process.
35231da177e4SLinus Torvalds  *
35241da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
35251da177e4SLinus Torvalds  * free memory available even if there is no other activity
35261da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
35271da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
35281da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
35291da177e4SLinus Torvalds  *
35301da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
35311da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
35321da177e4SLinus Torvalds  */
35331da177e4SLinus Torvalds static int kswapd(void *p)
35341da177e4SLinus Torvalds {
3535e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3536e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
35371da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
35381da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3539f0bc0a60SKOSAKI Motohiro 
35401da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
35411da177e4SLinus Torvalds 		.reclaimed_slab = 0,
35421da177e4SLinus Torvalds 	};
3543a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
35441da177e4SLinus Torvalds 
3545174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3546c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
35471da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
35481da177e4SLinus Torvalds 
35491da177e4SLinus Torvalds 	/*
35501da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
35511da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
35521da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
35531da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
35541da177e4SLinus Torvalds 	 *
35551da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
35561da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
35571da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
35581da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
35591da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
35601da177e4SLinus Torvalds 	 */
3561930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
356283144186SRafael J. Wysocki 	set_freezable();
35631da177e4SLinus Torvalds 
3564e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3565e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35661da177e4SLinus Torvalds 	for ( ; ; ) {
35676f6313d4SJeff Liu 		bool ret;
35683e1d1d28SChristoph Lameter 
3569e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3570e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3571e716f2ebSMel Gorman 
357238087d9bSMel Gorman kswapd_try_sleep:
357338087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
357438087d9bSMel Gorman 					classzone_idx);
3575215ddd66SMel Gorman 
357638087d9bSMel Gorman 		/* Read the new order and classzone_idx */
357738087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3578e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
357938087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3580e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
35811da177e4SLinus Torvalds 
35828fe23e05SDavid Rientjes 		ret = try_to_freeze();
35838fe23e05SDavid Rientjes 		if (kthread_should_stop())
35848fe23e05SDavid Rientjes 			break;
35858fe23e05SDavid Rientjes 
35868fe23e05SDavid Rientjes 		/*
35878fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
35888fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3589b1296cc4SRafael J. Wysocki 		 */
359038087d9bSMel Gorman 		if (ret)
359138087d9bSMel Gorman 			continue;
35921d82de61SMel Gorman 
359338087d9bSMel Gorman 		/*
359438087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
359538087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
359638087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
359738087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
359838087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
359938087d9bSMel Gorman 		 * request (alloc_order).
360038087d9bSMel Gorman 		 */
3601e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3602e5146b12SMel Gorman 						alloc_order);
3603d92a8cfcSPeter Zijlstra 		fs_reclaim_acquire(GFP_KERNEL);
360438087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
3605d92a8cfcSPeter Zijlstra 		fs_reclaim_release(GFP_KERNEL);
360638087d9bSMel Gorman 		if (reclaim_order < alloc_order)
360738087d9bSMel Gorman 			goto kswapd_try_sleep;
360833906bc5SMel Gorman 	}
3609b0a8cc58STakamori Yamaguchi 
361071abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3611b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
361271abdc15SJohannes Weiner 
36131da177e4SLinus Torvalds 	return 0;
36141da177e4SLinus Torvalds }
36151da177e4SLinus Torvalds 
36161da177e4SLinus Torvalds /*
36175ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
36185ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
36195ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
36205ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
36215ecd9d40SDavid Rientjes  * needed.
36221da177e4SLinus Torvalds  */
36235ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
36245ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
36251da177e4SLinus Torvalds {
36261da177e4SLinus Torvalds 	pg_data_t *pgdat;
36271da177e4SLinus Torvalds 
36286aa303deSMel Gorman 	if (!managed_zone(zone))
36291da177e4SLinus Torvalds 		return;
36301da177e4SLinus Torvalds 
36315ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
36321da177e4SLinus Torvalds 		return;
363388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3634e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3635e716f2ebSMel Gorman 							   classzone_idx);
363638087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
36378d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
36381da177e4SLinus Torvalds 		return;
3639e1a55637SMel Gorman 
36405ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
36415ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
36425ecd9d40SDavid Rientjes 	    pgdat_balanced(pgdat, order, classzone_idx)) {
36435ecd9d40SDavid Rientjes 		/*
36445ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
36455ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
36465ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
36475ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
36485ecd9d40SDavid Rientjes 		 * ratelimit its work.
36495ecd9d40SDavid Rientjes 		 */
36505ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
36515ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3652c73322d0SJohannes Weiner 		return;
36535ecd9d40SDavid Rientjes 	}
3654c73322d0SJohannes Weiner 
36555ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
36565ecd9d40SDavid Rientjes 				      gfp_flags);
36578d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
36581da177e4SLinus Torvalds }
36591da177e4SLinus Torvalds 
3660c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
36611da177e4SLinus Torvalds /*
36627b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3663d6277db4SRafael J. Wysocki  * freed pages.
3664d6277db4SRafael J. Wysocki  *
3665d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3666d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3667d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
36681da177e4SLinus Torvalds  */
36697b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
36701da177e4SLinus Torvalds {
3671d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3672d6277db4SRafael J. Wysocki 	struct scan_control sc = {
36737b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3674ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3675b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
36769e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3677ee814fe2SJohannes Weiner 		.may_writepage = 1,
3678ee814fe2SJohannes Weiner 		.may_unmap = 1,
3679ee814fe2SJohannes Weiner 		.may_swap = 1,
3680ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
36811da177e4SLinus Torvalds 	};
36827b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
36837b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
36847b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3685499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
36861da177e4SLinus Torvalds 
3687499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3688d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
3689d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
36907b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3691d6277db4SRafael J. Wysocki 
36923115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3693d6277db4SRafael J. Wysocki 
36947b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3695d92a8cfcSPeter Zijlstra 	fs_reclaim_release(sc.gfp_mask);
3696499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3697d6277db4SRafael J. Wysocki 
36987b51755cSKOSAKI Motohiro 	return nr_reclaimed;
36991da177e4SLinus Torvalds }
3700c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
37011da177e4SLinus Torvalds 
37021da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
37031da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
37041da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
37051da177e4SLinus Torvalds    restore their cpu bindings. */
3706517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
37071da177e4SLinus Torvalds {
370858c0a4a7SYasunori Goto 	int nid;
37091da177e4SLinus Torvalds 
371048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3711c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3712a70f7302SRusty Russell 		const struct cpumask *mask;
3713a70f7302SRusty Russell 
3714a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3715c5f59f08SMike Travis 
37163e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
37171da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3718c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
37191da177e4SLinus Torvalds 	}
3720517bbed9SSebastian Andrzej Siewior 	return 0;
37211da177e4SLinus Torvalds }
37221da177e4SLinus Torvalds 
37233218ae14SYasunori Goto /*
37243218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
37253218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
37263218ae14SYasunori Goto  */
37273218ae14SYasunori Goto int kswapd_run(int nid)
37283218ae14SYasunori Goto {
37293218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
37303218ae14SYasunori Goto 	int ret = 0;
37313218ae14SYasunori Goto 
37323218ae14SYasunori Goto 	if (pgdat->kswapd)
37333218ae14SYasunori Goto 		return 0;
37343218ae14SYasunori Goto 
37353218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
37363218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
37373218ae14SYasunori Goto 		/* failure at boot is fatal */
3738c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3739d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3740d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3741d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
37423218ae14SYasunori Goto 	}
37433218ae14SYasunori Goto 	return ret;
37443218ae14SYasunori Goto }
37453218ae14SYasunori Goto 
37468fe23e05SDavid Rientjes /*
3747d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3748bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
37498fe23e05SDavid Rientjes  */
37508fe23e05SDavid Rientjes void kswapd_stop(int nid)
37518fe23e05SDavid Rientjes {
37528fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
37538fe23e05SDavid Rientjes 
3754d8adde17SJiang Liu 	if (kswapd) {
37558fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3756d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3757d8adde17SJiang Liu 	}
37588fe23e05SDavid Rientjes }
37598fe23e05SDavid Rientjes 
37601da177e4SLinus Torvalds static int __init kswapd_init(void)
37611da177e4SLinus Torvalds {
3762517bbed9SSebastian Andrzej Siewior 	int nid, ret;
376369e05944SAndrew Morton 
37641da177e4SLinus Torvalds 	swap_setup();
376548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
37663218ae14SYasunori Goto  		kswapd_run(nid);
3767517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3768517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3769517bbed9SSebastian Andrzej Siewior 					NULL);
3770517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
37711da177e4SLinus Torvalds 	return 0;
37721da177e4SLinus Torvalds }
37731da177e4SLinus Torvalds 
37741da177e4SLinus Torvalds module_init(kswapd_init)
37759eeff239SChristoph Lameter 
37769eeff239SChristoph Lameter #ifdef CONFIG_NUMA
37779eeff239SChristoph Lameter /*
3778a5f5f91dSMel Gorman  * Node reclaim mode
37799eeff239SChristoph Lameter  *
3780a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
37819eeff239SChristoph Lameter  * the watermarks.
37829eeff239SChristoph Lameter  */
3783a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
37849eeff239SChristoph Lameter 
37851b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
37867d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
37871b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
378895bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
37891b2ffb78SChristoph Lameter 
37909eeff239SChristoph Lameter /*
3791a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3792a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3793a92f7126SChristoph Lameter  * a zone.
3794a92f7126SChristoph Lameter  */
3795a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3796a92f7126SChristoph Lameter 
37979eeff239SChristoph Lameter /*
3798a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
37999614634fSChristoph Lameter  * occur.
38009614634fSChristoph Lameter  */
38019614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
38029614634fSChristoph Lameter 
38039614634fSChristoph Lameter /*
38040ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
38050ff38490SChristoph Lameter  * slab reclaim needs to occur.
38060ff38490SChristoph Lameter  */
38070ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
38080ff38490SChristoph Lameter 
380911fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
381090afa5deSMel Gorman {
381111fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
381211fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
381311fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
381490afa5deSMel Gorman 
381590afa5deSMel Gorman 	/*
381690afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
381790afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
381890afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
381990afa5deSMel Gorman 	 */
382090afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
382190afa5deSMel Gorman }
382290afa5deSMel Gorman 
382390afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3824a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
382590afa5deSMel Gorman {
3826d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3827d031a157SAlexandru Moise 	unsigned long delta = 0;
382890afa5deSMel Gorman 
382990afa5deSMel Gorman 	/*
383095bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
383190afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
383211fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
383390afa5deSMel Gorman 	 * a better estimate
383490afa5deSMel Gorman 	 */
3835a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3836a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
383790afa5deSMel Gorman 	else
3838a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
383990afa5deSMel Gorman 
384090afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3841a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3842a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
384390afa5deSMel Gorman 
384490afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
384590afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
384690afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
384790afa5deSMel Gorman 
384890afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
384990afa5deSMel Gorman }
385090afa5deSMel Gorman 
38510ff38490SChristoph Lameter /*
3852a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
38539eeff239SChristoph Lameter  */
3854a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
38559eeff239SChristoph Lameter {
38567fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
385769e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
38589eeff239SChristoph Lameter 	struct task_struct *p = current;
38599eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
3860499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
3861179e9639SAndrew Morton 	struct scan_control sc = {
386262b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3863f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3864bd2f6199SJohannes Weiner 		.order = order,
3865a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
3866a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
3867a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
3868ee814fe2SJohannes Weiner 		.may_swap = 1,
3869f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
3870179e9639SAndrew Morton 	};
38719eeff239SChristoph Lameter 
38729eeff239SChristoph Lameter 	cond_resched();
3873d4f7796eSChristoph Lameter 	/*
387495bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
3875d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
387695bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
3877d4f7796eSChristoph Lameter 	 */
3878499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3879499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
3880d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
38819eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
38829eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
3883c84db23cSChristoph Lameter 
3884a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
3885a92f7126SChristoph Lameter 		/*
3886894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
38870ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
3888a92f7126SChristoph Lameter 		 */
3889a92f7126SChristoph Lameter 		do {
3890970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
38919e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
38920ff38490SChristoph Lameter 	}
3893a92f7126SChristoph Lameter 
38949eeff239SChristoph Lameter 	p->reclaim_state = NULL;
3895d92a8cfcSPeter Zijlstra 	fs_reclaim_release(gfp_mask);
3896499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
3897499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3898a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
38999eeff239SChristoph Lameter }
3900179e9639SAndrew Morton 
3901a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
3902179e9639SAndrew Morton {
3903d773ed6bSDavid Rientjes 	int ret;
3904179e9639SAndrew Morton 
3905179e9639SAndrew Morton 	/*
3906a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
39070ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
390834aa1330SChristoph Lameter 	 *
39099614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
39109614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
3911a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
3912a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
39139614634fSChristoph Lameter 	 * unmapped file backed pages.
3914179e9639SAndrew Morton 	 */
3915a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
3916385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
3917a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
3918179e9639SAndrew Morton 
3919179e9639SAndrew Morton 	/*
3920d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
3921179e9639SAndrew Morton 	 */
3922d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
3923a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3924179e9639SAndrew Morton 
3925179e9639SAndrew Morton 	/*
3926a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
3927179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
3928179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
3929179e9639SAndrew Morton 	 * as wide as possible.
3930179e9639SAndrew Morton 	 */
3931a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
3932a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3933d773ed6bSDavid Rientjes 
3934a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
3935a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
3936fa5e084eSMel Gorman 
3937a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
3938a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
3939d773ed6bSDavid Rientjes 
394024cf7251SMel Gorman 	if (!ret)
394124cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
394224cf7251SMel Gorman 
3943d773ed6bSDavid Rientjes 	return ret;
3944179e9639SAndrew Morton }
39459eeff239SChristoph Lameter #endif
3946894bc310SLee Schermerhorn 
3947894bc310SLee Schermerhorn /*
3948894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
3949894bc310SLee Schermerhorn  * @page: the page to test
3950894bc310SLee Schermerhorn  *
3951894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
395239b5f29aSHugh Dickins  * lists vs unevictable list.
3953894bc310SLee Schermerhorn  *
3954894bc310SLee Schermerhorn  * Reasons page might not be evictable:
3955ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
3956b291f000SNick Piggin  * (2) page is part of an mlocked VMA
3957ba9ddf49SLee Schermerhorn  *
3958894bc310SLee Schermerhorn  */
395939b5f29aSHugh Dickins int page_evictable(struct page *page)
3960894bc310SLee Schermerhorn {
3961e92bb4ddSHuang Ying 	int ret;
3962e92bb4ddSHuang Ying 
3963e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
3964e92bb4ddSHuang Ying 	rcu_read_lock();
3965e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3966e92bb4ddSHuang Ying 	rcu_read_unlock();
3967e92bb4ddSHuang Ying 	return ret;
3968894bc310SLee Schermerhorn }
396989e004eaSLee Schermerhorn 
397085046579SHugh Dickins #ifdef CONFIG_SHMEM
397189e004eaSLee Schermerhorn /**
397224513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
397324513264SHugh Dickins  * @pages:	array of pages to check
397424513264SHugh Dickins  * @nr_pages:	number of pages to check
397589e004eaSLee Schermerhorn  *
397624513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
397785046579SHugh Dickins  *
397885046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
397989e004eaSLee Schermerhorn  */
398024513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
398189e004eaSLee Schermerhorn {
3982925b7673SJohannes Weiner 	struct lruvec *lruvec;
3983785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
398424513264SHugh Dickins 	int pgscanned = 0;
398524513264SHugh Dickins 	int pgrescued = 0;
398689e004eaSLee Schermerhorn 	int i;
398789e004eaSLee Schermerhorn 
398824513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
398924513264SHugh Dickins 		struct page *page = pages[i];
3990785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
399189e004eaSLee Schermerhorn 
399224513264SHugh Dickins 		pgscanned++;
3993785b99feSMel Gorman 		if (pagepgdat != pgdat) {
3994785b99feSMel Gorman 			if (pgdat)
3995785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
3996785b99feSMel Gorman 			pgdat = pagepgdat;
3997785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
399889e004eaSLee Schermerhorn 		}
3999785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
400089e004eaSLee Schermerhorn 
400124513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
400224513264SHugh Dickins 			continue;
400389e004eaSLee Schermerhorn 
400439b5f29aSHugh Dickins 		if (page_evictable(page)) {
400524513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
400624513264SHugh Dickins 
4007309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
400824513264SHugh Dickins 			ClearPageUnevictable(page);
4009fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4010fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
401124513264SHugh Dickins 			pgrescued++;
401289e004eaSLee Schermerhorn 		}
401389e004eaSLee Schermerhorn 	}
401424513264SHugh Dickins 
4015785b99feSMel Gorman 	if (pgdat) {
401624513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
401724513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4018785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
401924513264SHugh Dickins 	}
402085046579SHugh Dickins }
402185046579SHugh Dickins #endif /* CONFIG_SHMEM */
4022