xref: /openbmc/linux/mm/vmscan.c (revision fa40d1ee9f156624658ca409a04a78882ca5b3c5)
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>
4964e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
50268bb0ceSLinus Torvalds #include <linux/prefetch.h>
51b1de0d13SMitchel Humpherys #include <linux/printk.h>
52f9fe48beSRoss Zwisler #include <linux/dax.h>
53eb414681SJohannes Weiner #include <linux/psi.h>
541da177e4SLinus Torvalds 
551da177e4SLinus Torvalds #include <asm/tlbflush.h>
561da177e4SLinus Torvalds #include <asm/div64.h>
571da177e4SLinus Torvalds 
581da177e4SLinus Torvalds #include <linux/swapops.h>
59117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
601da177e4SLinus Torvalds 
610f8053a5SNick Piggin #include "internal.h"
620f8053a5SNick Piggin 
6333906bc5SMel Gorman #define CREATE_TRACE_POINTS
6433906bc5SMel Gorman #include <trace/events/vmscan.h>
6533906bc5SMel Gorman 
661da177e4SLinus Torvalds struct scan_control {
6722fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6822fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6922fba335SKOSAKI Motohiro 
70ee814fe2SJohannes Weiner 	/*
71ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
72ee814fe2SJohannes Weiner 	 * are scanned.
73ee814fe2SJohannes Weiner 	 */
74ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
759e3b2f8cSKonstantin Khlebnikov 
765f53e762SKOSAKI Motohiro 	/*
77f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
78f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
79f16015fbSJohannes Weiner 	 */
80f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8166e1707bSBalbir Singh 
821276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
83ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
84ee814fe2SJohannes Weiner 
85ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
86ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
87ee814fe2SJohannes Weiner 
88ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
89ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
90ee814fe2SJohannes Weiner 
91d6622f63SYisheng Xie 	/*
92d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
93d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
94d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
95d6622f63SYisheng Xie 	 */
96d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
97d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
98241994edSJohannes Weiner 
99ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
100ee814fe2SJohannes Weiner 
101ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
102ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
103ee814fe2SJohannes Weiner 
104bb451fdfSGreg Thelen 	/* Allocation order */
105bb451fdfSGreg Thelen 	s8 order;
106bb451fdfSGreg Thelen 
107bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
108bb451fdfSGreg Thelen 	s8 priority;
109bb451fdfSGreg Thelen 
110bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
111bb451fdfSGreg Thelen 	s8 reclaim_idx;
112bb451fdfSGreg Thelen 
113bb451fdfSGreg Thelen 	/* This context's GFP mask */
114bb451fdfSGreg Thelen 	gfp_t gfp_mask;
115bb451fdfSGreg Thelen 
116ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
117ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
118ee814fe2SJohannes Weiner 
119ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
120ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
121d108c772SAndrey Ryabinin 
122d108c772SAndrey Ryabinin 	struct {
123d108c772SAndrey Ryabinin 		unsigned int dirty;
124d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
125d108c772SAndrey Ryabinin 		unsigned int congested;
126d108c772SAndrey Ryabinin 		unsigned int writeback;
127d108c772SAndrey Ryabinin 		unsigned int immediate;
128d108c772SAndrey Ryabinin 		unsigned int file_taken;
129d108c772SAndrey Ryabinin 		unsigned int taken;
130d108c772SAndrey Ryabinin 	} nr;
131e5ca8071SYafang Shao 
132e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
133e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1341da177e4SLinus Torvalds };
1351da177e4SLinus Torvalds 
1361da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1371da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1381da177e4SLinus Torvalds 	do {								\
1391da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1401da177e4SLinus Torvalds 			struct page *prev;				\
1411da177e4SLinus Torvalds 									\
1421da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1431da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1441da177e4SLinus Torvalds 		}							\
1451da177e4SLinus Torvalds 	} while (0)
1461da177e4SLinus Torvalds #else
1471da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1481da177e4SLinus Torvalds #endif
1491da177e4SLinus Torvalds 
1501da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1511da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1521da177e4SLinus Torvalds 	do {								\
1531da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1541da177e4SLinus Torvalds 			struct page *prev;				\
1551da177e4SLinus Torvalds 									\
1561da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1571da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1581da177e4SLinus Torvalds 		}							\
1591da177e4SLinus Torvalds 	} while (0)
1601da177e4SLinus Torvalds #else
1611da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1621da177e4SLinus Torvalds #endif
1631da177e4SLinus Torvalds 
1641da177e4SLinus Torvalds /*
1651da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1661da177e4SLinus Torvalds  */
1671da177e4SLinus Torvalds int vm_swappiness = 60;
168d0480be4SWang Sheng-Hui /*
169d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
170d0480be4SWang Sheng-Hui  * zones.
171d0480be4SWang Sheng-Hui  */
172d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1731da177e4SLinus Torvalds 
1740a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1750a432dcbSYang Shi 				   struct reclaim_state *rs)
1760a432dcbSYang Shi {
1770a432dcbSYang Shi 	/* Check for an overwrite */
1780a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1790a432dcbSYang Shi 
1800a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1810a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1820a432dcbSYang Shi 
1830a432dcbSYang Shi 	task->reclaim_state = rs;
1840a432dcbSYang Shi }
1850a432dcbSYang Shi 
1861da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1871da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1881da177e4SLinus Torvalds 
1890a432dcbSYang Shi #ifdef CONFIG_MEMCG
1907e010df5SKirill Tkhai /*
1917e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
1927e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
1937e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
1947e010df5SKirill Tkhai  * restrictions on their internal registration order.
1957e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
1967e010df5SKirill Tkhai  * bit is set in the shrinkers map.
1977e010df5SKirill Tkhai  *
1987e010df5SKirill Tkhai  * This value is used by the function to detect registering
1997e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
2007e010df5SKirill Tkhai  */
2017e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
2027e010df5SKirill Tkhai 
203b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
204b4c2b231SKirill Tkhai static int shrinker_nr_max;
205b4c2b231SKirill Tkhai 
206b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
207b4c2b231SKirill Tkhai {
208b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
209b4c2b231SKirill Tkhai 
210b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
211b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
2127e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
213b4c2b231SKirill Tkhai 	if (id < 0)
214b4c2b231SKirill Tkhai 		goto unlock;
215b4c2b231SKirill Tkhai 
2160a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2170a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2180a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2190a4465d3SKirill Tkhai 			goto unlock;
2200a4465d3SKirill Tkhai 		}
2210a4465d3SKirill Tkhai 
222b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2230a4465d3SKirill Tkhai 	}
224b4c2b231SKirill Tkhai 	shrinker->id = id;
225b4c2b231SKirill Tkhai 	ret = 0;
226b4c2b231SKirill Tkhai unlock:
227b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
228b4c2b231SKirill Tkhai 	return ret;
229b4c2b231SKirill Tkhai }
230b4c2b231SKirill Tkhai 
231b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
232b4c2b231SKirill Tkhai {
233b4c2b231SKirill Tkhai 	int id = shrinker->id;
234b4c2b231SKirill Tkhai 
235b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
236b4c2b231SKirill Tkhai 
237b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
238b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
239b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
240b4c2b231SKirill Tkhai }
241b4c2b231SKirill Tkhai 
24289b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
24389b5fae5SJohannes Weiner {
244f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
24589b5fae5SJohannes Weiner }
24697c9341fSTejun Heo 
24797c9341fSTejun Heo /**
24897c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
24997c9341fSTejun Heo  * @sc: scan_control in question
25097c9341fSTejun Heo  *
25197c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
25297c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
25397c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
25497c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
25597c9341fSTejun Heo  * allocation and configurability.
25697c9341fSTejun Heo  *
25797c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
25897c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
25997c9341fSTejun Heo  */
26097c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
26197c9341fSTejun Heo {
26297c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
26397c9341fSTejun Heo 
26497c9341fSTejun Heo 	if (!memcg)
26597c9341fSTejun Heo 		return true;
26697c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26769234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26897c9341fSTejun Heo 		return true;
26997c9341fSTejun Heo #endif
27097c9341fSTejun Heo 	return false;
27197c9341fSTejun Heo }
272e3c1ac58SAndrey Ryabinin 
273e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
274e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
275e3c1ac58SAndrey Ryabinin 				bool congested)
276e3c1ac58SAndrey Ryabinin {
277e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
278e3c1ac58SAndrey Ryabinin 
279e3c1ac58SAndrey Ryabinin 	if (!memcg)
280e3c1ac58SAndrey Ryabinin 		return;
281e3c1ac58SAndrey Ryabinin 
282e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
283e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
284e3c1ac58SAndrey Ryabinin }
285e3c1ac58SAndrey Ryabinin 
286e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
287e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
288e3c1ac58SAndrey Ryabinin {
289e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
290e3c1ac58SAndrey Ryabinin 
291e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
292e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
293e3c1ac58SAndrey Ryabinin 
294e3c1ac58SAndrey Ryabinin }
29591a45470SKAMEZAWA Hiroyuki #else
2960a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
2970a432dcbSYang Shi {
2980a432dcbSYang Shi 	return 0;
2990a432dcbSYang Shi }
3000a432dcbSYang Shi 
3010a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
3020a432dcbSYang Shi {
3030a432dcbSYang Shi }
3040a432dcbSYang Shi 
30589b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
30689b5fae5SJohannes Weiner {
30789b5fae5SJohannes Weiner 	return true;
30889b5fae5SJohannes Weiner }
30997c9341fSTejun Heo 
31097c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
31197c9341fSTejun Heo {
31297c9341fSTejun Heo 	return true;
31397c9341fSTejun Heo }
314e3c1ac58SAndrey Ryabinin 
315e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
316e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
317e3c1ac58SAndrey Ryabinin {
318e3c1ac58SAndrey Ryabinin }
319e3c1ac58SAndrey Ryabinin 
320e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
321e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
322e3c1ac58SAndrey Ryabinin {
323e3c1ac58SAndrey Ryabinin 	return false;
324e3c1ac58SAndrey Ryabinin 
325e3c1ac58SAndrey Ryabinin }
32691a45470SKAMEZAWA Hiroyuki #endif
32791a45470SKAMEZAWA Hiroyuki 
3285a1c84b4SMel Gorman /*
3295a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3305a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3315a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3325a1c84b4SMel Gorman  */
3335a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3345a1c84b4SMel Gorman {
3355a1c84b4SMel Gorman 	unsigned long nr;
3365a1c84b4SMel Gorman 
3375a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3385a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3395a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3405a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3415a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3425a1c84b4SMel Gorman 
3435a1c84b4SMel Gorman 	return nr;
3445a1c84b4SMel Gorman }
3455a1c84b4SMel Gorman 
346fd538803SMichal Hocko /**
347fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
348fd538803SMichal Hocko  * @lruvec: lru vector
349fd538803SMichal Hocko  * @lru: lru to use
350fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
351fd538803SMichal Hocko  */
352fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
353c9f299d9SKOSAKI Motohiro {
354b11edebbSHonglei Wang 	unsigned long lru_size = 0;
355fd538803SMichal Hocko 	int zid;
356a3d8e054SKOSAKI Motohiro 
357b11edebbSHonglei Wang 	if (!mem_cgroup_disabled()) {
358b11edebbSHonglei Wang 		for (zid = 0; zid < MAX_NR_ZONES; zid++)
359b11edebbSHonglei Wang 			lru_size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
360b11edebbSHonglei Wang 	} else
361fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
362fd538803SMichal Hocko 
363fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
364fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
365fd538803SMichal Hocko 		unsigned long size;
366fd538803SMichal Hocko 
367fd538803SMichal Hocko 		if (!managed_zone(zone))
368fd538803SMichal Hocko 			continue;
369fd538803SMichal Hocko 
370fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
371fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
372fd538803SMichal Hocko 		else
373fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
374fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
375fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
376c9f299d9SKOSAKI Motohiro 	}
377c9f299d9SKOSAKI Motohiro 
378fd538803SMichal Hocko 	return lru_size;
379b4536f0cSMichal Hocko 
380b4536f0cSMichal Hocko }
381b4536f0cSMichal Hocko 
3821da177e4SLinus Torvalds /*
3831d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3841da177e4SLinus Torvalds  */
3858e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3861da177e4SLinus Torvalds {
387b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3881d3d4437SGlauber Costa 
3891d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3901d3d4437SGlauber Costa 		size *= nr_node_ids;
3911d3d4437SGlauber Costa 
3921d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3931d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3941d3d4437SGlauber Costa 		return -ENOMEM;
395b4c2b231SKirill Tkhai 
396b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
397b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
398b4c2b231SKirill Tkhai 			goto free_deferred;
399b4c2b231SKirill Tkhai 	}
400b4c2b231SKirill Tkhai 
4018e04944fSTetsuo Handa 	return 0;
402b4c2b231SKirill Tkhai 
403b4c2b231SKirill Tkhai free_deferred:
404b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
405b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
406b4c2b231SKirill Tkhai 	return -ENOMEM;
4078e04944fSTetsuo Handa }
4081d3d4437SGlauber Costa 
4098e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
4108e04944fSTetsuo Handa {
411b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
412b4c2b231SKirill Tkhai 		return;
413b4c2b231SKirill Tkhai 
414b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
415b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
416b4c2b231SKirill Tkhai 
4178e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4188e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4198e04944fSTetsuo Handa }
4208e04944fSTetsuo Handa 
4218e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4228e04944fSTetsuo Handa {
4231da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4241da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
4257e010df5SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
4268df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
4277e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
4287e010df5SKirill Tkhai #endif
4291da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
4308e04944fSTetsuo Handa }
4318e04944fSTetsuo Handa 
4328e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
4338e04944fSTetsuo Handa {
4348e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4358e04944fSTetsuo Handa 
4368e04944fSTetsuo Handa 	if (err)
4378e04944fSTetsuo Handa 		return err;
4388e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4391d3d4437SGlauber Costa 	return 0;
4401da177e4SLinus Torvalds }
4418e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4421da177e4SLinus Torvalds 
4431da177e4SLinus Torvalds /*
4441da177e4SLinus Torvalds  * Remove one
4451da177e4SLinus Torvalds  */
4468e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4471da177e4SLinus Torvalds {
448bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
449bb422a73STetsuo Handa 		return;
450b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
451b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4521da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4531da177e4SLinus Torvalds 	list_del(&shrinker->list);
4541da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
455ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
456bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4571da177e4SLinus Torvalds }
4588e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4591da177e4SLinus Torvalds 
4601da177e4SLinus Torvalds #define SHRINK_BATCH 128
4611d3d4437SGlauber Costa 
462cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4639092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4641da177e4SLinus Torvalds {
46524f7c6b9SDave Chinner 	unsigned long freed = 0;
4661da177e4SLinus Torvalds 	unsigned long long delta;
467635697c6SKonstantin Khlebnikov 	long total_scan;
468d5bc5fd3SVladimir Davydov 	long freeable;
469acf92b48SDave Chinner 	long nr;
470acf92b48SDave Chinner 	long new_nr;
4711d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
472e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
473e9299f50SDave Chinner 					  : SHRINK_BATCH;
4745f33a080SShaohua Li 	long scanned = 0, next_deferred;
4751da177e4SLinus Torvalds 
476ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
477ac7fb3adSKirill Tkhai 		nid = 0;
478ac7fb3adSKirill Tkhai 
479d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4809b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4819b996468SKirill Tkhai 		return freeable;
482635697c6SKonstantin Khlebnikov 
483acf92b48SDave Chinner 	/*
484acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
485acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
486acf92b48SDave Chinner 	 * don't also do this scanning work.
487acf92b48SDave Chinner 	 */
4881d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
489acf92b48SDave Chinner 
490acf92b48SDave Chinner 	total_scan = nr;
4914b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4929092c71bSJosef Bacik 		delta = freeable >> priority;
4939092c71bSJosef Bacik 		delta *= 4;
4949092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4954b85afbdSJohannes Weiner 	} else {
4964b85afbdSJohannes Weiner 		/*
4974b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4984b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4994b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
5004b85afbdSJohannes Weiner 		 */
5014b85afbdSJohannes Weiner 		delta = freeable / 2;
5024b85afbdSJohannes Weiner 	}
503172b06c3SRoman Gushchin 
504acf92b48SDave Chinner 	total_scan += delta;
505acf92b48SDave Chinner 	if (total_scan < 0) {
506d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
507a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
508d5bc5fd3SVladimir Davydov 		total_scan = freeable;
5095f33a080SShaohua Li 		next_deferred = nr;
5105f33a080SShaohua Li 	} else
5115f33a080SShaohua Li 		next_deferred = total_scan;
512ea164d73SAndrea Arcangeli 
513ea164d73SAndrea Arcangeli 	/*
5143567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5153567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5163567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5173567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5183567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
519d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5203567b59aSDave Chinner 	 * memory.
5213567b59aSDave Chinner 	 *
5223567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
5233567b59aSDave Chinner 	 * a large delta change is calculated directly.
5243567b59aSDave Chinner 	 */
525d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
526d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
5273567b59aSDave Chinner 
5283567b59aSDave Chinner 	/*
529ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
530ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
531ea164d73SAndrea Arcangeli 	 * freeable entries.
532ea164d73SAndrea Arcangeli 	 */
533d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
534d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5351da177e4SLinus Torvalds 
53624f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5379092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
53809576073SDave Chinner 
5390b1fb40aSVladimir Davydov 	/*
5400b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5410b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5420b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5430b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5440b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5450b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5460b1fb40aSVladimir Davydov 	 * batch_size.
5470b1fb40aSVladimir Davydov 	 *
5480b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5490b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
550d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5510b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5520b1fb40aSVladimir Davydov 	 * possible.
5530b1fb40aSVladimir Davydov 	 */
5540b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
555d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
55624f7c6b9SDave Chinner 		unsigned long ret;
5570b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5581da177e4SLinus Torvalds 
5590b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
560d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
56124f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
56224f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5631da177e4SLinus Torvalds 			break;
56424f7c6b9SDave Chinner 		freed += ret;
56524f7c6b9SDave Chinner 
566d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
567d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
568d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5691da177e4SLinus Torvalds 
5701da177e4SLinus Torvalds 		cond_resched();
5711da177e4SLinus Torvalds 	}
5721da177e4SLinus Torvalds 
5735f33a080SShaohua Li 	if (next_deferred >= scanned)
5745f33a080SShaohua Li 		next_deferred -= scanned;
5755f33a080SShaohua Li 	else
5765f33a080SShaohua Li 		next_deferred = 0;
577acf92b48SDave Chinner 	/*
578acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
579acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
580acf92b48SDave Chinner 	 * scan, there is no need to do an update.
581acf92b48SDave Chinner 	 */
5825f33a080SShaohua Li 	if (next_deferred > 0)
5835f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5841d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
58583aeeadaSKonstantin Khlebnikov 	else
5861d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
587acf92b48SDave Chinner 
588df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5891d3d4437SGlauber Costa 	return freed;
5901d3d4437SGlauber Costa }
5911d3d4437SGlauber Costa 
5920a432dcbSYang Shi #ifdef CONFIG_MEMCG
593b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
594b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
595b0dedc49SKirill Tkhai {
596b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
597b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
598b8e57efaSKirill Tkhai 	int i;
599b0dedc49SKirill Tkhai 
6000a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
601b0dedc49SKirill Tkhai 		return 0;
602b0dedc49SKirill Tkhai 
603b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
604b0dedc49SKirill Tkhai 		return 0;
605b0dedc49SKirill Tkhai 
606b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
607b0dedc49SKirill Tkhai 					true);
608b0dedc49SKirill Tkhai 	if (unlikely(!map))
609b0dedc49SKirill Tkhai 		goto unlock;
610b0dedc49SKirill Tkhai 
611b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
612b0dedc49SKirill Tkhai 		struct shrink_control sc = {
613b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
614b0dedc49SKirill Tkhai 			.nid = nid,
615b0dedc49SKirill Tkhai 			.memcg = memcg,
616b0dedc49SKirill Tkhai 		};
617b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
618b0dedc49SKirill Tkhai 
619b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6207e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6217e010df5SKirill Tkhai 			if (!shrinker)
622b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
623b0dedc49SKirill Tkhai 			continue;
624b0dedc49SKirill Tkhai 		}
625b0dedc49SKirill Tkhai 
6260a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
6270a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
6280a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
6290a432dcbSYang Shi 			continue;
6300a432dcbSYang Shi 
631b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
632f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
633f90280d6SKirill Tkhai 			clear_bit(i, map->map);
634f90280d6SKirill Tkhai 			/*
635f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
636f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
637f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
638f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
639f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
640f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
641f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
642f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
643f90280d6SKirill Tkhai 			 *
644f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
645f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
646f90280d6SKirill Tkhai 			 *   <MB>               <MB>
647f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
648f90280d6SKirill Tkhai 			 */
649f90280d6SKirill Tkhai 			smp_mb__after_atomic();
650f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6519b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6529b996468SKirill Tkhai 				ret = 0;
653f90280d6SKirill Tkhai 			else
654f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
655f90280d6SKirill Tkhai 		}
656b0dedc49SKirill Tkhai 		freed += ret;
657b0dedc49SKirill Tkhai 
658b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
659b0dedc49SKirill Tkhai 			freed = freed ? : 1;
660b0dedc49SKirill Tkhai 			break;
661b0dedc49SKirill Tkhai 		}
662b0dedc49SKirill Tkhai 	}
663b0dedc49SKirill Tkhai unlock:
664b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
665b0dedc49SKirill Tkhai 	return freed;
666b0dedc49SKirill Tkhai }
6670a432dcbSYang Shi #else /* CONFIG_MEMCG */
668b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
669b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
670b0dedc49SKirill Tkhai {
671b0dedc49SKirill Tkhai 	return 0;
672b0dedc49SKirill Tkhai }
6730a432dcbSYang Shi #endif /* CONFIG_MEMCG */
674b0dedc49SKirill Tkhai 
6756b4f7799SJohannes Weiner /**
676cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6776b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6786b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
679cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6809092c71bSJosef Bacik  * @priority: the reclaim priority
6811d3d4437SGlauber Costa  *
6826b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6831d3d4437SGlauber Costa  *
6846b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6856b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6861d3d4437SGlauber Costa  *
687aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
688aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
689cb731d6cSVladimir Davydov  *
6909092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6919092c71bSJosef Bacik  * in order to get the scan target.
6921d3d4437SGlauber Costa  *
6936b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6941d3d4437SGlauber Costa  */
695cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
696cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6979092c71bSJosef Bacik 				 int priority)
6981d3d4437SGlauber Costa {
699b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
7001d3d4437SGlauber Costa 	struct shrinker *shrinker;
7011d3d4437SGlauber Costa 
702fa1e512fSYang Shi 	/*
703fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
704fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
705fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
706fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
707fa1e512fSYang Shi 	 * oom.
708fa1e512fSYang Shi 	 */
709fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
710b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
711cb731d6cSVladimir Davydov 
712e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
7131d3d4437SGlauber Costa 		goto out;
7141d3d4437SGlauber Costa 
7151d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
7166b4f7799SJohannes Weiner 		struct shrink_control sc = {
7176b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
7186b4f7799SJohannes Weiner 			.nid = nid,
719cb731d6cSVladimir Davydov 			.memcg = memcg,
7206b4f7799SJohannes Weiner 		};
7216b4f7799SJohannes Weiner 
7229b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
7239b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
7249b996468SKirill Tkhai 			ret = 0;
7259b996468SKirill Tkhai 		freed += ret;
726e496612cSMinchan Kim 		/*
727e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
728e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
729e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
730e496612cSMinchan Kim 		 */
731e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
732e496612cSMinchan Kim 			freed = freed ? : 1;
733e496612cSMinchan Kim 			break;
734e496612cSMinchan Kim 		}
735ec97097bSVladimir Davydov 	}
7361d3d4437SGlauber Costa 
7371da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
738f06590bdSMinchan Kim out:
739f06590bdSMinchan Kim 	cond_resched();
74024f7c6b9SDave Chinner 	return freed;
7411da177e4SLinus Torvalds }
7421da177e4SLinus Torvalds 
743cb731d6cSVladimir Davydov void drop_slab_node(int nid)
744cb731d6cSVladimir Davydov {
745cb731d6cSVladimir Davydov 	unsigned long freed;
746cb731d6cSVladimir Davydov 
747cb731d6cSVladimir Davydov 	do {
748cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
749cb731d6cSVladimir Davydov 
750cb731d6cSVladimir Davydov 		freed = 0;
751aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
752cb731d6cSVladimir Davydov 		do {
7539092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
754cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
755cb731d6cSVladimir Davydov 	} while (freed > 10);
756cb731d6cSVladimir Davydov }
757cb731d6cSVladimir Davydov 
758cb731d6cSVladimir Davydov void drop_slab(void)
759cb731d6cSVladimir Davydov {
760cb731d6cSVladimir Davydov 	int nid;
761cb731d6cSVladimir Davydov 
762cb731d6cSVladimir Davydov 	for_each_online_node(nid)
763cb731d6cSVladimir Davydov 		drop_slab_node(nid);
764cb731d6cSVladimir Davydov }
765cb731d6cSVladimir Davydov 
7661da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7671da177e4SLinus Torvalds {
768ceddc3a5SJohannes Weiner 	/*
769ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
77067891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
77167891fffSMatthew Wilcox 	 * heads at page->private.
772ceddc3a5SJohannes Weiner 	 */
77367891fffSMatthew Wilcox 	int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
774bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
77567891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7761da177e4SLinus Torvalds }
7771da177e4SLinus Torvalds 
778703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
7791da177e4SLinus Torvalds {
780930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7811da177e4SLinus Torvalds 		return 1;
782703c2708STejun Heo 	if (!inode_write_congested(inode))
7831da177e4SLinus Torvalds 		return 1;
784703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7851da177e4SLinus Torvalds 		return 1;
7861da177e4SLinus Torvalds 	return 0;
7871da177e4SLinus Torvalds }
7881da177e4SLinus Torvalds 
7891da177e4SLinus Torvalds /*
7901da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7911da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7921da177e4SLinus Torvalds  * fsync(), msync() or close().
7931da177e4SLinus Torvalds  *
7941da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7951da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7961da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7971da177e4SLinus Torvalds  *
7981da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7991da177e4SLinus Torvalds  * __GFP_FS.
8001da177e4SLinus Torvalds  */
8011da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
8021da177e4SLinus Torvalds 				struct page *page, int error)
8031da177e4SLinus Torvalds {
8047eaceaccSJens Axboe 	lock_page(page);
8053e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
8063e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
8071da177e4SLinus Torvalds 	unlock_page(page);
8081da177e4SLinus Torvalds }
8091da177e4SLinus Torvalds 
81004e62a29SChristoph Lameter /* possible outcome of pageout() */
81104e62a29SChristoph Lameter typedef enum {
81204e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
81304e62a29SChristoph Lameter 	PAGE_KEEP,
81404e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
81504e62a29SChristoph Lameter 	PAGE_ACTIVATE,
81604e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
81704e62a29SChristoph Lameter 	PAGE_SUCCESS,
81804e62a29SChristoph Lameter 	/* page is clean and locked */
81904e62a29SChristoph Lameter 	PAGE_CLEAN,
82004e62a29SChristoph Lameter } pageout_t;
82104e62a29SChristoph Lameter 
8221da177e4SLinus Torvalds /*
8231742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
8241742f19fSAndrew Morton  * Calls ->writepage().
8251da177e4SLinus Torvalds  */
826c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
8277d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
8281da177e4SLinus Torvalds {
8291da177e4SLinus Torvalds 	/*
8301da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
8311da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
8321da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
8331da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
8341da177e4SLinus Torvalds 	 * PagePrivate for that.
8351da177e4SLinus Torvalds 	 *
8368174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
8371da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
8381da177e4SLinus Torvalds 	 * will block.
8391da177e4SLinus Torvalds 	 *
8401da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
8411da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
8421da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
8431da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
8441da177e4SLinus Torvalds 	 */
8451da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
8461da177e4SLinus Torvalds 		return PAGE_KEEP;
8471da177e4SLinus Torvalds 	if (!mapping) {
8481da177e4SLinus Torvalds 		/*
8491da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8501da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8511da177e4SLinus Torvalds 		 */
852266cf658SDavid Howells 		if (page_has_private(page)) {
8531da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8541da177e4SLinus Torvalds 				ClearPageDirty(page);
855b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8561da177e4SLinus Torvalds 				return PAGE_CLEAN;
8571da177e4SLinus Torvalds 			}
8581da177e4SLinus Torvalds 		}
8591da177e4SLinus Torvalds 		return PAGE_KEEP;
8601da177e4SLinus Torvalds 	}
8611da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8621da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
863703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
8641da177e4SLinus Torvalds 		return PAGE_KEEP;
8651da177e4SLinus Torvalds 
8661da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8671da177e4SLinus Torvalds 		int res;
8681da177e4SLinus Torvalds 		struct writeback_control wbc = {
8691da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8701da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
871111ebb6eSOGAWA Hirofumi 			.range_start = 0,
872111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8731da177e4SLinus Torvalds 			.for_reclaim = 1,
8741da177e4SLinus Torvalds 		};
8751da177e4SLinus Torvalds 
8761da177e4SLinus Torvalds 		SetPageReclaim(page);
8771da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8781da177e4SLinus Torvalds 		if (res < 0)
8791da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
880994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8811da177e4SLinus Torvalds 			ClearPageReclaim(page);
8821da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8831da177e4SLinus Torvalds 		}
884c661b078SAndy Whitcroft 
8851da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8861da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8871da177e4SLinus Torvalds 			ClearPageReclaim(page);
8881da177e4SLinus Torvalds 		}
8893aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
890c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8911da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8921da177e4SLinus Torvalds 	}
8931da177e4SLinus Torvalds 
8941da177e4SLinus Torvalds 	return PAGE_CLEAN;
8951da177e4SLinus Torvalds }
8961da177e4SLinus Torvalds 
897a649fd92SAndrew Morton /*
898e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
899e286781dSNick Piggin  * gets returned with a refcount of 0.
900a649fd92SAndrew Morton  */
901a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
902a528910eSJohannes Weiner 			    bool reclaimed)
90349d2e9ccSChristoph Lameter {
904c4843a75SGreg Thelen 	unsigned long flags;
905bd4c82c2SHuang Ying 	int refcount;
906c4843a75SGreg Thelen 
90728e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
90828e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
90949d2e9ccSChristoph Lameter 
910b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
91149d2e9ccSChristoph Lameter 	/*
9120fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
9130fd0e6b0SNick Piggin 	 *
9140fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
9150fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
9160fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
9170fd0e6b0SNick Piggin 	 * here, then the following race may occur:
9180fd0e6b0SNick Piggin 	 *
9190fd0e6b0SNick Piggin 	 * get_user_pages(&page);
9200fd0e6b0SNick Piggin 	 * [user mapping goes away]
9210fd0e6b0SNick Piggin 	 * write_to(page);
9220fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
9230fd0e6b0SNick Piggin 	 * SetPageDirty(page);
9240fd0e6b0SNick Piggin 	 * put_page(page);
9250fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
9260fd0e6b0SNick Piggin 	 *
9270fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
9280fd0e6b0SNick Piggin 	 *
9290fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
9300fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
9310139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
9320fd0e6b0SNick Piggin 	 *
9330fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
934b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
93549d2e9ccSChristoph Lameter 	 */
936906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
937bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
93849d2e9ccSChristoph Lameter 		goto cannot_free;
9391c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
940e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
941bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
94249d2e9ccSChristoph Lameter 		goto cannot_free;
943e286781dSNick Piggin 	}
94449d2e9ccSChristoph Lameter 
94549d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
94649d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
9470a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
9484e17ec25SMatthew Wilcox 		__delete_from_swap_cache(page, swap);
949b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
95075f6d6d2SMinchan Kim 		put_swap_page(page, swap);
951e286781dSNick Piggin 	} else {
9526072d13cSLinus Torvalds 		void (*freepage)(struct page *);
953a528910eSJohannes Weiner 		void *shadow = NULL;
9546072d13cSLinus Torvalds 
9556072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
956a528910eSJohannes Weiner 		/*
957a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
958a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
959a528910eSJohannes Weiner 		 *
960a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
961a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
962a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
963a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
964a528910eSJohannes Weiner 		 * back.
965f9fe48beSRoss Zwisler 		 *
966f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
967f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
968f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
969f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
970b93b0163SMatthew Wilcox 		 * same address_space.
971a528910eSJohannes Weiner 		 */
972a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
973f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
974a7ca12f9SAndrey Ryabinin 			shadow = workingset_eviction(page);
97562cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
976b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9776072d13cSLinus Torvalds 
9786072d13cSLinus Torvalds 		if (freepage != NULL)
9796072d13cSLinus Torvalds 			freepage(page);
980e286781dSNick Piggin 	}
981e286781dSNick Piggin 
98249d2e9ccSChristoph Lameter 	return 1;
98349d2e9ccSChristoph Lameter 
98449d2e9ccSChristoph Lameter cannot_free:
985b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
98649d2e9ccSChristoph Lameter 	return 0;
98749d2e9ccSChristoph Lameter }
98849d2e9ccSChristoph Lameter 
9891da177e4SLinus Torvalds /*
990e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
991e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
992e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
993e286781dSNick Piggin  * this page.
994e286781dSNick Piggin  */
995e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
996e286781dSNick Piggin {
997a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
998e286781dSNick Piggin 		/*
999e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
1000e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
1001e286781dSNick Piggin 		 * atomic operation.
1002e286781dSNick Piggin 		 */
1003fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
1004e286781dSNick Piggin 		return 1;
1005e286781dSNick Piggin 	}
1006e286781dSNick Piggin 	return 0;
1007e286781dSNick Piggin }
1008e286781dSNick Piggin 
1009894bc310SLee Schermerhorn /**
1010894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
1011894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
1012894bc310SLee Schermerhorn  *
1013894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1014894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1015894bc310SLee Schermerhorn  *
1016894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1017894bc310SLee Schermerhorn  */
1018894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1019894bc310SLee Schermerhorn {
1020c53954a0SMel Gorman 	lru_cache_add(page);
1021894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1022894bc310SLee Schermerhorn }
1023894bc310SLee Schermerhorn 
1024dfc8d636SJohannes Weiner enum page_references {
1025dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1026dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
102764574746SJohannes Weiner 	PAGEREF_KEEP,
1028dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1029dfc8d636SJohannes Weiner };
1030dfc8d636SJohannes Weiner 
1031dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1032dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1033dfc8d636SJohannes Weiner {
103464574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1035dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1036dfc8d636SJohannes Weiner 
1037c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1038c3ac9a8aSJohannes Weiner 					  &vm_flags);
103964574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1040dfc8d636SJohannes Weiner 
1041dfc8d636SJohannes Weiner 	/*
1042dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1043dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1044dfc8d636SJohannes Weiner 	 */
1045dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1046dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1047dfc8d636SJohannes Weiner 
104864574746SJohannes Weiner 	if (referenced_ptes) {
1049e4898273SMichal Hocko 		if (PageSwapBacked(page))
105064574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
105164574746SJohannes Weiner 		/*
105264574746SJohannes Weiner 		 * All mapped pages start out with page table
105364574746SJohannes Weiner 		 * references from the instantiating fault, so we need
105464574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
105564574746SJohannes Weiner 		 * than once.
105664574746SJohannes Weiner 		 *
105764574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
105864574746SJohannes Weiner 		 * inactive list.  Another page table reference will
105964574746SJohannes Weiner 		 * lead to its activation.
106064574746SJohannes Weiner 		 *
106164574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
106264574746SJohannes Weiner 		 * so that recently deactivated but used pages are
106364574746SJohannes Weiner 		 * quickly recovered.
106464574746SJohannes Weiner 		 */
106564574746SJohannes Weiner 		SetPageReferenced(page);
106664574746SJohannes Weiner 
106734dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1068dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1069dfc8d636SJohannes Weiner 
1070c909e993SKonstantin Khlebnikov 		/*
1071c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1072c909e993SKonstantin Khlebnikov 		 */
1073c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1074c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1075c909e993SKonstantin Khlebnikov 
107664574746SJohannes Weiner 		return PAGEREF_KEEP;
107764574746SJohannes Weiner 	}
107864574746SJohannes Weiner 
1079dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10802e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1081dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
108264574746SJohannes Weiner 
108364574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1084dfc8d636SJohannes Weiner }
1085dfc8d636SJohannes Weiner 
1086e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1087e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1088e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1089e2be15f6SMel Gorman {
1090b4597226SMel Gorman 	struct address_space *mapping;
1091b4597226SMel Gorman 
1092e2be15f6SMel Gorman 	/*
1093e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1094e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1095e2be15f6SMel Gorman 	 */
1096802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1097802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1098e2be15f6SMel Gorman 		*dirty = false;
1099e2be15f6SMel Gorman 		*writeback = false;
1100e2be15f6SMel Gorman 		return;
1101e2be15f6SMel Gorman 	}
1102e2be15f6SMel Gorman 
1103e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1104e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1105e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1106b4597226SMel Gorman 
1107b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1108b4597226SMel Gorman 	if (!page_has_private(page))
1109b4597226SMel Gorman 		return;
1110b4597226SMel Gorman 
1111b4597226SMel Gorman 	mapping = page_mapping(page);
1112b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1113b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1114e2be15f6SMel Gorman }
1115e2be15f6SMel Gorman 
1116e286781dSNick Piggin /*
11171742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
11181da177e4SLinus Torvalds  */
11191742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1120599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1121f84f6e2bSMel Gorman 				      struct scan_control *sc,
112202c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
11233c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
11248940b34aSMinchan Kim 				      bool ignore_references)
11251da177e4SLinus Torvalds {
11261da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1127abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
11283c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
1129886cf190SKirill Tkhai 	unsigned pgactivate = 0;
11301da177e4SLinus Torvalds 
1131060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
11321da177e4SLinus Torvalds 	cond_resched();
11331da177e4SLinus Torvalds 
11341da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
11351da177e4SLinus Torvalds 		struct address_space *mapping;
11361da177e4SLinus Torvalds 		struct page *page;
11371da177e4SLinus Torvalds 		int may_enter_fs;
11388940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1139e2be15f6SMel Gorman 		bool dirty, writeback;
114098879b3bSYang Shi 		unsigned int nr_pages;
11411da177e4SLinus Torvalds 
11421da177e4SLinus Torvalds 		cond_resched();
11431da177e4SLinus Torvalds 
11441da177e4SLinus Torvalds 		page = lru_to_page(page_list);
11451da177e4SLinus Torvalds 		list_del(&page->lru);
11461da177e4SLinus Torvalds 
1147529ae9aaSNick Piggin 		if (!trylock_page(page))
11481da177e4SLinus Torvalds 			goto keep;
11491da177e4SLinus Torvalds 
1150309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11511da177e4SLinus Torvalds 
1152d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
115398879b3bSYang Shi 
115498879b3bSYang Shi 		/* Account the number of base pages even though THP */
115598879b3bSYang Shi 		sc->nr_scanned += nr_pages;
115680e43426SChristoph Lameter 
115739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1158ad6b6704SMinchan Kim 			goto activate_locked;
1159894bc310SLee Schermerhorn 
1160a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
116180e43426SChristoph Lameter 			goto keep_locked;
116280e43426SChristoph Lameter 
1163c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1164c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1165c661b078SAndy Whitcroft 
1166e62e384eSMichal Hocko 		/*
1167894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1168e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1169e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1170e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1171e2be15f6SMel Gorman 		 */
1172e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1173e2be15f6SMel Gorman 		if (dirty || writeback)
1174060f005fSKirill Tkhai 			stat->nr_dirty++;
1175e2be15f6SMel Gorman 
1176e2be15f6SMel Gorman 		if (dirty && !writeback)
1177060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1178e2be15f6SMel Gorman 
1179d04e8acdSMel Gorman 		/*
1180d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1181d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1182d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1183d04e8acdSMel Gorman 		 * end of the LRU a second time.
1184d04e8acdSMel Gorman 		 */
1185e2be15f6SMel Gorman 		mapping = page_mapping(page);
11861da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1187703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1188d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1189060f005fSKirill Tkhai 			stat->nr_congested++;
1190e2be15f6SMel Gorman 
1191e2be15f6SMel Gorman 		/*
1192283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1193283aba9fSMel Gorman 		 * are three cases to consider.
1194e62e384eSMichal Hocko 		 *
1195283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1196283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1197283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1198283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1199283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1200283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1201283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1202b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1203b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1204c3b94f44SHugh Dickins 		 *
120597c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1206ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1207ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1208ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
120997c9341fSTejun Heo 		 *    reclaim and continue scanning.
1210283aba9fSMel Gorman 		 *
1211ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1212ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1213283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1214283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1215283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1216283aba9fSMel Gorman 		 *    would probably show more reasons.
1217283aba9fSMel Gorman 		 *
12187fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1219283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1220283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1221283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1222283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1223c55e8d03SJohannes Weiner 		 *
1224c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1225c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1226c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1227c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1228c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1229c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1230c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1231c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1232e62e384eSMichal Hocko 		 */
1233283aba9fSMel Gorman 		if (PageWriteback(page)) {
1234283aba9fSMel Gorman 			/* Case 1 above */
1235283aba9fSMel Gorman 			if (current_is_kswapd() &&
1236283aba9fSMel Gorman 			    PageReclaim(page) &&
1237599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1238060f005fSKirill Tkhai 				stat->nr_immediate++;
1239c55e8d03SJohannes Weiner 				goto activate_locked;
1240283aba9fSMel Gorman 
1241283aba9fSMel Gorman 			/* Case 2 above */
124297c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1243ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1244c3b94f44SHugh Dickins 				/*
1245c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1246c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1247c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1248c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1249c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1250c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1251c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1252c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1253c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1254c3b94f44SHugh Dickins 				 */
1255c3b94f44SHugh Dickins 				SetPageReclaim(page);
1256060f005fSKirill Tkhai 				stat->nr_writeback++;
1257c55e8d03SJohannes Weiner 				goto activate_locked;
1258283aba9fSMel Gorman 
1259283aba9fSMel Gorman 			/* Case 3 above */
1260283aba9fSMel Gorman 			} else {
12617fadc820SHugh Dickins 				unlock_page(page);
1262c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12637fadc820SHugh Dickins 				/* then go back and try same page again */
12647fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12657fadc820SHugh Dickins 				continue;
1266e62e384eSMichal Hocko 			}
1267283aba9fSMel Gorman 		}
12681da177e4SLinus Torvalds 
12698940b34aSMinchan Kim 		if (!ignore_references)
12706a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
127102c6de8dSMinchan Kim 
1272dfc8d636SJohannes Weiner 		switch (references) {
1273dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12741da177e4SLinus Torvalds 			goto activate_locked;
127564574746SJohannes Weiner 		case PAGEREF_KEEP:
127698879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
127764574746SJohannes Weiner 			goto keep_locked;
1278dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1279dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1280dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1281dfc8d636SJohannes Weiner 		}
12821da177e4SLinus Torvalds 
12831da177e4SLinus Torvalds 		/*
12841da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12851da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1286802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12871da177e4SLinus Torvalds 		 */
1288bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1289bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
129063eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
129163eb6b93SHugh Dickins 					goto keep_locked;
1292747552b1SHuang Ying 				if (PageTransHuge(page)) {
1293b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1294747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1295b8f593cdSHuang Ying 						goto activate_locked;
1296747552b1SHuang Ying 					/*
1297747552b1SHuang Ying 					 * Split pages without a PMD map right
1298747552b1SHuang Ying 					 * away. Chances are some or all of the
1299747552b1SHuang Ying 					 * tail pages can be freed without IO.
1300747552b1SHuang Ying 					 */
1301747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1302bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1303bd4c82c2SHuang Ying 								    page_list))
1304747552b1SHuang Ying 						goto activate_locked;
1305747552b1SHuang Ying 				}
13060f074658SMinchan Kim 				if (!add_to_swap(page)) {
13070f074658SMinchan Kim 					if (!PageTransHuge(page))
130898879b3bSYang Shi 						goto activate_locked_split;
1309bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1310bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1311bd4c82c2SHuang Ying 								    page_list))
13120f074658SMinchan Kim 						goto activate_locked;
1313fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1314fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1315fe490cc0SHuang Ying #endif
13160f074658SMinchan Kim 					if (!add_to_swap(page))
131798879b3bSYang Shi 						goto activate_locked_split;
13180f074658SMinchan Kim 				}
13190f074658SMinchan Kim 
132063eb6b93SHugh Dickins 				may_enter_fs = 1;
13211da177e4SLinus Torvalds 
1322e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
13231da177e4SLinus Torvalds 				mapping = page_mapping(page);
1324bd4c82c2SHuang Ying 			}
13257751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
13267751b2daSKirill A. Shutemov 			/* Split file THP */
13277751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
13287751b2daSKirill A. Shutemov 				goto keep_locked;
1329e2be15f6SMel Gorman 		}
13301da177e4SLinus Torvalds 
13311da177e4SLinus Torvalds 		/*
133298879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
133398879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
133498879b3bSYang Shi 		 *
133598879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
133698879b3bSYang Shi 		 * reach here.
133798879b3bSYang Shi 		 */
133898879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
133998879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
134098879b3bSYang Shi 			nr_pages = 1;
134198879b3bSYang Shi 		}
134298879b3bSYang Shi 
134398879b3bSYang Shi 		/*
13441da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
13451da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
13461da177e4SLinus Torvalds 		 */
1347802a3a92SShaohua Li 		if (page_mapped(page)) {
1348bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1349bd4c82c2SHuang Ying 
1350bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1351bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1352bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
135398879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
13541da177e4SLinus Torvalds 				goto activate_locked;
13551da177e4SLinus Torvalds 			}
13561da177e4SLinus Torvalds 		}
13571da177e4SLinus Torvalds 
13581da177e4SLinus Torvalds 		if (PageDirty(page)) {
1359ee72886dSMel Gorman 			/*
13604eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13614eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13624eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13634eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13644eda4823SJohannes Weiner 			 * write pages when we've encountered many
13654eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13664eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13674eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1368ee72886dSMel Gorman 			 */
1369f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13704eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1371599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
137249ea7eb6SMel Gorman 				/*
137349ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
137449ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
137549ea7eb6SMel Gorman 				 * except we already have the page isolated
137649ea7eb6SMel Gorman 				 * and know it's dirty
137749ea7eb6SMel Gorman 				 */
1378c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
137949ea7eb6SMel Gorman 				SetPageReclaim(page);
138049ea7eb6SMel Gorman 
1381c55e8d03SJohannes Weiner 				goto activate_locked;
1382ee72886dSMel Gorman 			}
1383ee72886dSMel Gorman 
1384dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13851da177e4SLinus Torvalds 				goto keep_locked;
13864dd4b920SAndrew Morton 			if (!may_enter_fs)
13871da177e4SLinus Torvalds 				goto keep_locked;
138852a8363eSChristoph Lameter 			if (!sc->may_writepage)
13891da177e4SLinus Torvalds 				goto keep_locked;
13901da177e4SLinus Torvalds 
1391d950c947SMel Gorman 			/*
1392d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1393d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1394d950c947SMel Gorman 			 * starts and then write it out here.
1395d950c947SMel Gorman 			 */
1396d950c947SMel Gorman 			try_to_unmap_flush_dirty();
13977d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
13981da177e4SLinus Torvalds 			case PAGE_KEEP:
13991da177e4SLinus Torvalds 				goto keep_locked;
14001da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
14011da177e4SLinus Torvalds 				goto activate_locked;
14021da177e4SLinus Torvalds 			case PAGE_SUCCESS:
14037d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
140441ac1999SMel Gorman 					goto keep;
14057d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
14061da177e4SLinus Torvalds 					goto keep;
14077d3579e8SKOSAKI Motohiro 
14081da177e4SLinus Torvalds 				/*
14091da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
14101da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
14111da177e4SLinus Torvalds 				 */
1412529ae9aaSNick Piggin 				if (!trylock_page(page))
14131da177e4SLinus Torvalds 					goto keep;
14141da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
14151da177e4SLinus Torvalds 					goto keep_locked;
14161da177e4SLinus Torvalds 				mapping = page_mapping(page);
14171da177e4SLinus Torvalds 			case PAGE_CLEAN:
14181da177e4SLinus Torvalds 				; /* try to free the page below */
14191da177e4SLinus Torvalds 			}
14201da177e4SLinus Torvalds 		}
14211da177e4SLinus Torvalds 
14221da177e4SLinus Torvalds 		/*
14231da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
14241da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
14251da177e4SLinus Torvalds 		 * the page as well.
14261da177e4SLinus Torvalds 		 *
14271da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
14281da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
14291da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
14301da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
14311da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
14321da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
14331da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
14341da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
14351da177e4SLinus Torvalds 		 *
14361da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
14371da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
14381da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
14391da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
14401da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
14411da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
14421da177e4SLinus Torvalds 		 */
1443266cf658SDavid Howells 		if (page_has_private(page)) {
14441da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14451da177e4SLinus Torvalds 				goto activate_locked;
1446e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1447e286781dSNick Piggin 				unlock_page(page);
1448e286781dSNick Piggin 				if (put_page_testzero(page))
14491da177e4SLinus Torvalds 					goto free_it;
1450e286781dSNick Piggin 				else {
1451e286781dSNick Piggin 					/*
1452e286781dSNick Piggin 					 * rare race with speculative reference.
1453e286781dSNick Piggin 					 * the speculative reference will free
1454e286781dSNick Piggin 					 * this page shortly, so we may
1455e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1456e286781dSNick Piggin 					 * leave it off the LRU).
1457e286781dSNick Piggin 					 */
1458e286781dSNick Piggin 					nr_reclaimed++;
1459e286781dSNick Piggin 					continue;
1460e286781dSNick Piggin 				}
1461e286781dSNick Piggin 			}
14621da177e4SLinus Torvalds 		}
14631da177e4SLinus Torvalds 
1464802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1465802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1466802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
146749d2e9ccSChristoph Lameter 				goto keep_locked;
1468802a3a92SShaohua Li 			if (PageDirty(page)) {
1469802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1470802a3a92SShaohua Li 				goto keep_locked;
1471802a3a92SShaohua Li 			}
14721da177e4SLinus Torvalds 
1473802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14742262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1475802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1476802a3a92SShaohua Li 			goto keep_locked;
14779a1ea439SHugh Dickins 
14789a1ea439SHugh Dickins 		unlock_page(page);
1479e286781dSNick Piggin free_it:
148098879b3bSYang Shi 		/*
148198879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
148298879b3bSYang Shi 		 * all base pages.
148398879b3bSYang Shi 		 */
148498879b3bSYang Shi 		nr_reclaimed += nr_pages;
1485abe4c3b5SMel Gorman 
1486abe4c3b5SMel Gorman 		/*
1487abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1488abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1489abe4c3b5SMel Gorman 		 */
14907ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1491bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
14927ae88534SYang Shi 		else
1493abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14941da177e4SLinus Torvalds 		continue;
14951da177e4SLinus Torvalds 
149698879b3bSYang Shi activate_locked_split:
149798879b3bSYang Shi 		/*
149898879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
149998879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
150098879b3bSYang Shi 		 */
150198879b3bSYang Shi 		if (nr_pages > 1) {
150298879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
150398879b3bSYang Shi 			nr_pages = 1;
150498879b3bSYang Shi 		}
15051da177e4SLinus Torvalds activate_locked:
150668a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1507ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1508ad6b6704SMinchan Kim 						PageMlocked(page)))
1509a2c43eedSHugh Dickins 			try_to_free_swap(page);
1510309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1511ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
1512886cf190SKirill Tkhai 			int type = page_is_file_cache(page);
15131da177e4SLinus Torvalds 			SetPageActive(page);
151498879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
15152262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1516ad6b6704SMinchan Kim 		}
15171da177e4SLinus Torvalds keep_locked:
15181da177e4SLinus Torvalds 		unlock_page(page);
15191da177e4SLinus Torvalds keep:
15201da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1521309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
15221da177e4SLinus Torvalds 	}
1523abe4c3b5SMel Gorman 
152498879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
152598879b3bSYang Shi 
1526747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
152772b252aeSMel Gorman 	try_to_unmap_flush();
15282d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1529abe4c3b5SMel Gorman 
15301da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1531886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
15320a31bc97SJohannes Weiner 
153305ff5137SAndrew Morton 	return nr_reclaimed;
15341da177e4SLinus Torvalds }
15351da177e4SLinus Torvalds 
153602c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
153702c6de8dSMinchan Kim 					    struct list_head *page_list)
153802c6de8dSMinchan Kim {
153902c6de8dSMinchan Kim 	struct scan_control sc = {
154002c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
154102c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
154202c6de8dSMinchan Kim 		.may_unmap = 1,
154302c6de8dSMinchan Kim 	};
1544060f005fSKirill Tkhai 	struct reclaim_stat dummy_stat;
15453c710c1aSMichal Hocko 	unsigned long ret;
154602c6de8dSMinchan Kim 	struct page *page, *next;
154702c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
154802c6de8dSMinchan Kim 
154902c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1550117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1551a58f2cefSMinchan Kim 		    !__PageMovable(page) && !PageUnevictable(page)) {
155202c6de8dSMinchan Kim 			ClearPageActive(page);
155302c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
155402c6de8dSMinchan Kim 		}
155502c6de8dSMinchan Kim 	}
155602c6de8dSMinchan Kim 
1557599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1558060f005fSKirill Tkhai 			TTU_IGNORE_ACCESS, &dummy_stat, true);
155902c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1560599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
156102c6de8dSMinchan Kim 	return ret;
156202c6de8dSMinchan Kim }
156302c6de8dSMinchan Kim 
15645ad333ebSAndy Whitcroft /*
15655ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15665ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15675ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15685ad333ebSAndy Whitcroft  *
15695ad333ebSAndy Whitcroft  * page:	page to consider
15705ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15715ad333ebSAndy Whitcroft  *
15725ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15735ad333ebSAndy Whitcroft  */
1574f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15755ad333ebSAndy Whitcroft {
15765ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15775ad333ebSAndy Whitcroft 
15785ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15795ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15805ad333ebSAndy Whitcroft 		return ret;
15815ad333ebSAndy Whitcroft 
1582e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1583e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1584894bc310SLee Schermerhorn 		return ret;
1585894bc310SLee Schermerhorn 
15865ad333ebSAndy Whitcroft 	ret = -EBUSY;
158708e552c6SKAMEZAWA Hiroyuki 
1588c8244935SMel Gorman 	/*
1589c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1590c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1591c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1592c8244935SMel Gorman 	 *
1593c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1594c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1595c8244935SMel Gorman 	 */
15961276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1597c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1598c8244935SMel Gorman 		if (PageWriteback(page))
159939deaf85SMinchan Kim 			return ret;
160039deaf85SMinchan Kim 
1601c8244935SMel Gorman 		if (PageDirty(page)) {
1602c8244935SMel Gorman 			struct address_space *mapping;
160369d763fcSMel Gorman 			bool migrate_dirty;
1604c8244935SMel Gorman 
1605c8244935SMel Gorman 			/*
1606c8244935SMel Gorman 			 * Only pages without mappings or that have a
1607c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
160869d763fcSMel Gorman 			 * without blocking. However, we can be racing with
160969d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
161069d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
161169d763fcSMel Gorman 			 * the page lock until after the page is removed
161269d763fcSMel Gorman 			 * from the page cache.
1613c8244935SMel Gorman 			 */
161469d763fcSMel Gorman 			if (!trylock_page(page))
161569d763fcSMel Gorman 				return ret;
161669d763fcSMel Gorman 
1617c8244935SMel Gorman 			mapping = page_mapping(page);
1618145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
161969d763fcSMel Gorman 			unlock_page(page);
162069d763fcSMel Gorman 			if (!migrate_dirty)
1621c8244935SMel Gorman 				return ret;
1622c8244935SMel Gorman 		}
1623c8244935SMel Gorman 	}
1624c8244935SMel Gorman 
1625f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1626f80c0673SMinchan Kim 		return ret;
1627f80c0673SMinchan Kim 
16285ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
16295ad333ebSAndy Whitcroft 		/*
16305ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
16315ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
16325ad333ebSAndy Whitcroft 		 * page release code relies on it.
16335ad333ebSAndy Whitcroft 		 */
16345ad333ebSAndy Whitcroft 		ClearPageLRU(page);
16355ad333ebSAndy Whitcroft 		ret = 0;
16365ad333ebSAndy Whitcroft 	}
16375ad333ebSAndy Whitcroft 
16385ad333ebSAndy Whitcroft 	return ret;
16395ad333ebSAndy Whitcroft }
16405ad333ebSAndy Whitcroft 
16417ee36a14SMel Gorman 
16427ee36a14SMel Gorman /*
16437ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
16447ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
16457ee36a14SMel Gorman  */
16467ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1647b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16487ee36a14SMel Gorman {
16497ee36a14SMel Gorman 	int zid;
16507ee36a14SMel Gorman 
16517ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16527ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16537ee36a14SMel Gorman 			continue;
16547ee36a14SMel Gorman 
16557ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1656b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1657b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1658b4536f0cSMichal Hocko #endif
16597ee36a14SMel Gorman 	}
16607ee36a14SMel Gorman 
16617ee36a14SMel Gorman }
16627ee36a14SMel Gorman 
1663f4b7e272SAndrey Ryabinin /**
1664f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16651da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16661da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16671da177e4SLinus Torvalds  *
16681da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16691da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16701da177e4SLinus Torvalds  *
16711da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16721da177e4SLinus Torvalds  *
1673791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16745dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16751da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1676f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1677fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16785ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16793cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16801da177e4SLinus Torvalds  *
16811da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16821da177e4SLinus Torvalds  */
168369e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16845dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1685fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1686a9e7c39fSKirill Tkhai 		enum lru_list lru)
16871da177e4SLinus Torvalds {
168875b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
168969e05944SAndrew Morton 	unsigned long nr_taken = 0;
1690599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16917cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16923db65812SJohannes Weiner 	unsigned long skipped = 0;
1693791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1694b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1695a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16961da177e4SLinus Torvalds 
169798879b3bSYang Shi 	total_scan = 0;
1698791b48b6SMinchan Kim 	scan = 0;
169998879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
17005ad333ebSAndy Whitcroft 		struct page *page;
17015ad333ebSAndy Whitcroft 
17021da177e4SLinus Torvalds 		page = lru_to_page(src);
17031da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
17041da177e4SLinus Torvalds 
1705309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
17068d438f96SNick Piggin 
1707d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
170898879b3bSYang Shi 		total_scan += nr_pages;
170998879b3bSYang Shi 
1710b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1711b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
171298879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1713b2e18757SMel Gorman 			continue;
1714b2e18757SMel Gorman 		}
1715b2e18757SMel Gorman 
1716791b48b6SMinchan Kim 		/*
1717791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1718791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1719791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1720791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
172198879b3bSYang Shi 		 *
172298879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
172398879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
172498879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1725791b48b6SMinchan Kim 		 */
172698879b3bSYang Shi 		scan += nr_pages;
1727f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
17285ad333ebSAndy Whitcroft 		case 0:
1729599d0c95SMel Gorman 			nr_taken += nr_pages;
1730599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
17315ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
17325ad333ebSAndy Whitcroft 			break;
17337c8ee9a8SNick Piggin 
17345ad333ebSAndy Whitcroft 		case -EBUSY:
17355ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
17365ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
17375ad333ebSAndy Whitcroft 			continue;
17385ad333ebSAndy Whitcroft 
17395ad333ebSAndy Whitcroft 		default:
17405ad333ebSAndy Whitcroft 			BUG();
17415ad333ebSAndy Whitcroft 		}
17425ad333ebSAndy Whitcroft 	}
17431da177e4SLinus Torvalds 
1744b2e18757SMel Gorman 	/*
1745b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1746b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1747b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1748b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1749b2e18757SMel Gorman 	 * system at risk of premature OOM.
1750b2e18757SMel Gorman 	 */
17517cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17527cc30fcfSMel Gorman 		int zid;
17537cc30fcfSMel Gorman 
17543db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17557cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17567cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17577cc30fcfSMel Gorman 				continue;
17587cc30fcfSMel Gorman 
17597cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17601265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17617cc30fcfSMel Gorman 		}
17627cc30fcfSMel Gorman 	}
1763791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17641265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1765791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1766b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17671da177e4SLinus Torvalds 	return nr_taken;
17681da177e4SLinus Torvalds }
17691da177e4SLinus Torvalds 
177062695a84SNick Piggin /**
177162695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
177262695a84SNick Piggin  * @page: page to isolate from its LRU list
177362695a84SNick Piggin  *
177462695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
177562695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
177662695a84SNick Piggin  *
177762695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
177862695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
177962695a84SNick Piggin  *
178062695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1781894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1782894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1783894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
178462695a84SNick Piggin  *
178562695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
178662695a84SNick Piggin  * found will be decremented.
178762695a84SNick Piggin  *
178862695a84SNick Piggin  * Restrictions:
1789a5d09bedSMike Rapoport  *
179062695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
179162695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
179262695a84SNick Piggin  *     without a stable reference).
179362695a84SNick Piggin  * (2) the lru_lock must not be held.
179462695a84SNick Piggin  * (3) interrupts must be enabled.
179562695a84SNick Piggin  */
179662695a84SNick Piggin int isolate_lru_page(struct page *page)
179762695a84SNick Piggin {
179862695a84SNick Piggin 	int ret = -EBUSY;
179962695a84SNick Piggin 
1800309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1801cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
18020c917313SKonstantin Khlebnikov 
180362695a84SNick Piggin 	if (PageLRU(page)) {
1804f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1805fa9add64SHugh Dickins 		struct lruvec *lruvec;
180662695a84SNick Piggin 
1807f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1808f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
18090c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1810894bc310SLee Schermerhorn 			int lru = page_lru(page);
18110c917313SKonstantin Khlebnikov 			get_page(page);
181262695a84SNick Piggin 			ClearPageLRU(page);
1813fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1814fa9add64SHugh Dickins 			ret = 0;
181562695a84SNick Piggin 		}
1816f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
181762695a84SNick Piggin 	}
181862695a84SNick Piggin 	return ret;
181962695a84SNick Piggin }
182062695a84SNick Piggin 
18215ad333ebSAndy Whitcroft /*
1822d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1823d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1824d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1825d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1826d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
182735cd7815SRik van Riel  */
1828599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
182935cd7815SRik van Riel 		struct scan_control *sc)
183035cd7815SRik van Riel {
183135cd7815SRik van Riel 	unsigned long inactive, isolated;
183235cd7815SRik van Riel 
183335cd7815SRik van Riel 	if (current_is_kswapd())
183435cd7815SRik van Riel 		return 0;
183535cd7815SRik van Riel 
183697c9341fSTejun Heo 	if (!sane_reclaim(sc))
183735cd7815SRik van Riel 		return 0;
183835cd7815SRik van Riel 
183935cd7815SRik van Riel 	if (file) {
1840599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1841599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
184235cd7815SRik van Riel 	} else {
1843599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1844599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
184535cd7815SRik van Riel 	}
184635cd7815SRik van Riel 
18473cf23841SFengguang Wu 	/*
18483cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18493cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18503cf23841SFengguang Wu 	 * deadlock.
18513cf23841SFengguang Wu 	 */
1852d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18533cf23841SFengguang Wu 		inactive >>= 3;
18543cf23841SFengguang Wu 
185535cd7815SRik van Riel 	return isolated > inactive;
185635cd7815SRik van Riel }
185735cd7815SRik van Riel 
1858a222f341SKirill Tkhai /*
1859a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1860a222f341SKirill Tkhai  *
1861a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1862a222f341SKirill Tkhai  * processes, from rmap.
1863a222f341SKirill Tkhai  *
1864a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1865a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1866a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1867a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1868a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1869a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1870a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1871a222f341SKirill Tkhai  *
1872a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1873a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1874a222f341SKirill Tkhai  *
1875a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1876a222f341SKirill Tkhai  */
1877a222f341SKirill Tkhai 
1878a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1879a222f341SKirill Tkhai 						     struct list_head *list)
188066635629SMel Gorman {
1881599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1882a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18833f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1884a222f341SKirill Tkhai 	struct page *page;
1885a222f341SKirill Tkhai 	enum lru_list lru;
188666635629SMel Gorman 
1887a222f341SKirill Tkhai 	while (!list_empty(list)) {
1888a222f341SKirill Tkhai 		page = lru_to_page(list);
1889309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
189039b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1891a222f341SKirill Tkhai 			list_del(&page->lru);
1892599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
189366635629SMel Gorman 			putback_lru_page(page);
1894599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
189566635629SMel Gorman 			continue;
189666635629SMel Gorman 		}
1897599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1898fa9add64SHugh Dickins 
18997a608572SLinus Torvalds 		SetPageLRU(page);
190066635629SMel Gorman 		lru = page_lru(page);
1901a222f341SKirill Tkhai 
1902a222f341SKirill Tkhai 		nr_pages = hpage_nr_pages(page);
1903a222f341SKirill Tkhai 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1904a222f341SKirill Tkhai 		list_move(&page->lru, &lruvec->lists[lru]);
1905fa9add64SHugh Dickins 
19062bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
19072bcf8879SHugh Dickins 			__ClearPageLRU(page);
19082bcf8879SHugh Dickins 			__ClearPageActive(page);
1909fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
19102bcf8879SHugh Dickins 
19112bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1912599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
19132bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1914599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
19152bcf8879SHugh Dickins 			} else
19162bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
1917a222f341SKirill Tkhai 		} else {
1918a222f341SKirill Tkhai 			nr_moved += nr_pages;
191966635629SMel Gorman 		}
192066635629SMel Gorman 	}
192166635629SMel Gorman 
19223f79768fSHugh Dickins 	/*
19233f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
19243f79768fSHugh Dickins 	 */
1925a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1926a222f341SKirill Tkhai 
1927a222f341SKirill Tkhai 	return nr_moved;
192866635629SMel Gorman }
192966635629SMel Gorman 
193066635629SMel Gorman /*
1931399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1932399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1933399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1934399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1935399ba0b9SNeilBrown  */
1936399ba0b9SNeilBrown static int current_may_throttle(void)
1937399ba0b9SNeilBrown {
1938399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1939399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1940399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1941399ba0b9SNeilBrown }
1942399ba0b9SNeilBrown 
1943399ba0b9SNeilBrown /*
1944b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
19451742f19fSAndrew Morton  * of reclaimed pages
19461da177e4SLinus Torvalds  */
194766635629SMel Gorman static noinline_for_stack unsigned long
19481a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19499e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19501da177e4SLinus Torvalds {
19511da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1952e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
195305ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1954e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1955060f005fSKirill Tkhai 	struct reclaim_stat stat;
19563cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1957f46b7912SKirill Tkhai 	enum vm_event_item item;
1958599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19591a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1960db73ee0dSMichal Hocko 	bool stalled = false;
196178dc583dSKOSAKI Motohiro 
1962599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1963db73ee0dSMichal Hocko 		if (stalled)
1964db73ee0dSMichal Hocko 			return 0;
1965db73ee0dSMichal Hocko 
1966db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1967db73ee0dSMichal Hocko 		msleep(100);
1968db73ee0dSMichal Hocko 		stalled = true;
196935cd7815SRik van Riel 
197035cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
197135cd7815SRik van Riel 		if (fatal_signal_pending(current))
197235cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
197335cd7815SRik van Riel 	}
197435cd7815SRik van Riel 
19751da177e4SLinus Torvalds 	lru_add_drain();
1976f80c0673SMinchan Kim 
1977599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19781da177e4SLinus Torvalds 
19795dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1980a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
198195d918fcSKonstantin Khlebnikov 
1982599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19839d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
198495d918fcSKonstantin Khlebnikov 
1985f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
19862262185cSRoman Gushchin 	if (global_reclaim(sc))
1987f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1988f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1989599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1990d563c050SHillf Danton 
1991d563c050SHillf Danton 	if (nr_taken == 0)
199266635629SMel Gorman 		return 0;
1993b35ea17bSKOSAKI Motohiro 
1994a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19953c710c1aSMichal Hocko 				&stat, false);
1996c661b078SAndy Whitcroft 
1997599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19983f79768fSHugh Dickins 
1999f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
20002262185cSRoman Gushchin 	if (global_reclaim(sc))
2001f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
2002f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2003b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
2004b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
2005a74609faSNick Piggin 
2006a222f341SKirill Tkhai 	move_pages_to_lru(lruvec, &page_list);
20073f79768fSHugh Dickins 
2008599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
20093f79768fSHugh Dickins 
2010599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20113f79768fSHugh Dickins 
2012747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
20132d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2014e11da5b4SMel Gorman 
201592df3a72SMel Gorman 	/*
20161c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
20171c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
20181c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
20191c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
20201c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
20211c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
20221c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
20231c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
20241c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
20251c610d5fSAndrey Ryabinin 	 */
20261c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
20271c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
20281c610d5fSAndrey Ryabinin 
2029d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2030d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2031d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2032d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2033d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2034d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2035d108c772SAndrey Ryabinin 	if (file)
2036d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
20378e950282SMel Gorman 
2038599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2039d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
204005ff5137SAndrew Morton 	return nr_reclaimed;
20411da177e4SLinus Torvalds }
20421da177e4SLinus Torvalds 
2043f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20441a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2045f16015fbSJohannes Weiner 			       struct scan_control *sc,
20469e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20471cfb419bSKAMEZAWA Hiroyuki {
204844c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2049f626012dSHugh Dickins 	unsigned long nr_scanned;
20506fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20511cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20528cab4754SWu Fengguang 	LIST_HEAD(l_active);
2053b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20541cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20551a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20569d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20579d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20583cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2059599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20601cfb419bSKAMEZAWA Hiroyuki 
20611da177e4SLinus Torvalds 	lru_add_drain();
2062f80c0673SMinchan Kim 
2063599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2064925b7673SJohannes Weiner 
20655dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2066a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
206789b5fae5SJohannes Weiner 
2068599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2069b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20701cfb419bSKAMEZAWA Hiroyuki 
2071599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20722fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20739d5e6a9fSHugh Dickins 
2074599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20751da177e4SLinus Torvalds 
20761da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20771da177e4SLinus Torvalds 		cond_resched();
20781da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20791da177e4SLinus Torvalds 		list_del(&page->lru);
20807e9cd484SRik van Riel 
208139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2082894bc310SLee Schermerhorn 			putback_lru_page(page);
2083894bc310SLee Schermerhorn 			continue;
2084894bc310SLee Schermerhorn 		}
2085894bc310SLee Schermerhorn 
2086cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2087cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2088cc715d99SMel Gorman 				if (page_has_private(page))
2089cc715d99SMel Gorman 					try_to_release_page(page, 0);
2090cc715d99SMel Gorman 				unlock_page(page);
2091cc715d99SMel Gorman 			}
2092cc715d99SMel Gorman 		}
2093cc715d99SMel Gorman 
2094c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2095c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20969992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20978cab4754SWu Fengguang 			/*
20988cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20998cab4754SWu Fengguang 			 * give them one more trip around the active list. So
21008cab4754SWu Fengguang 			 * that executable code get better chances to stay in
21018cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
21028cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
21038cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
21048cab4754SWu Fengguang 			 * so we ignore them here.
21058cab4754SWu Fengguang 			 */
210641e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
21078cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
21088cab4754SWu Fengguang 				continue;
21098cab4754SWu Fengguang 			}
21108cab4754SWu Fengguang 		}
21117e9cd484SRik van Riel 
21125205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
21131899ad18SJohannes Weiner 		SetPageWorkingset(page);
21141da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
21151da177e4SLinus Torvalds 	}
21161da177e4SLinus Torvalds 
2117b555749aSAndrew Morton 	/*
21188cab4754SWu Fengguang 	 * Move pages back to the lru list.
2119b555749aSAndrew Morton 	 */
2120599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
21214f98a2feSRik van Riel 	/*
21228cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
21238cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
21248cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
21257c0db9e9SJerome Marchand 	 * get_scan_count.
2126556adecbSRik van Riel 	 */
2127b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2128556adecbSRik van Riel 
2129a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2130a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2131f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2132f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
21339851ac13SKirill Tkhai 
21349851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
21359851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
21369851ac13SKirill Tkhai 
2137599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2138599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21392bcf8879SHugh Dickins 
2140f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2141f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
21429d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21439d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21441da177e4SLinus Torvalds }
21451da177e4SLinus Torvalds 
21461a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
21471a4e58ccSMinchan Kim {
21481a4e58ccSMinchan Kim 	int nid = -1;
21491a4e58ccSMinchan Kim 	unsigned long nr_reclaimed = 0;
21501a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
21511a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
21521a4e58ccSMinchan Kim 	struct page *page;
21531a4e58ccSMinchan Kim 	struct scan_control sc = {
21541a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
21551a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
21561a4e58ccSMinchan Kim 		.may_writepage = 1,
21571a4e58ccSMinchan Kim 		.may_unmap = 1,
21581a4e58ccSMinchan Kim 		.may_swap = 1,
21591a4e58ccSMinchan Kim 	};
21601a4e58ccSMinchan Kim 
21611a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
21621a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
21631a4e58ccSMinchan Kim 		if (nid == -1) {
21641a4e58ccSMinchan Kim 			nid = page_to_nid(page);
21651a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
21661a4e58ccSMinchan Kim 		}
21671a4e58ccSMinchan Kim 
21681a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
21691a4e58ccSMinchan Kim 			ClearPageActive(page);
21701a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
21711a4e58ccSMinchan Kim 			continue;
21721a4e58ccSMinchan Kim 		}
21731a4e58ccSMinchan Kim 
21741a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21751a4e58ccSMinchan Kim 						NODE_DATA(nid),
21761a4e58ccSMinchan Kim 						&sc, 0,
21771a4e58ccSMinchan Kim 						&dummy_stat, false);
21781a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21791a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21801a4e58ccSMinchan Kim 			list_del(&page->lru);
21811a4e58ccSMinchan Kim 			putback_lru_page(page);
21821a4e58ccSMinchan Kim 		}
21831a4e58ccSMinchan Kim 
21841a4e58ccSMinchan Kim 		nid = -1;
21851a4e58ccSMinchan Kim 	}
21861a4e58ccSMinchan Kim 
21871a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
21881a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21891a4e58ccSMinchan Kim 						NODE_DATA(nid),
21901a4e58ccSMinchan Kim 						&sc, 0,
21911a4e58ccSMinchan Kim 						&dummy_stat, false);
21921a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21931a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21941a4e58ccSMinchan Kim 			list_del(&page->lru);
21951a4e58ccSMinchan Kim 			putback_lru_page(page);
21961a4e58ccSMinchan Kim 		}
21971a4e58ccSMinchan Kim 	}
21981a4e58ccSMinchan Kim 
21991a4e58ccSMinchan Kim 	return nr_reclaimed;
22001a4e58ccSMinchan Kim }
22011a4e58ccSMinchan Kim 
220259dc76b0SRik van Riel /*
220359dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
220459dc76b0SRik van Riel  * to do too much work.
220514797e23SKOSAKI Motohiro  *
220659dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
220759dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
220859dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
220959dc76b0SRik van Riel  *
221059dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
221159dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
221259dc76b0SRik van Riel  *
22132a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
22142a2e4885SJohannes Weiner  *
221559dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
22163a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
221759dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
221859dc76b0SRik van Riel  *
221959dc76b0SRik van Riel  * total     target    max
222059dc76b0SRik van Riel  * memory    ratio     inactive
222159dc76b0SRik van Riel  * -------------------------------------
222259dc76b0SRik van Riel  *   10MB       1         5MB
222359dc76b0SRik van Riel  *  100MB       1        50MB
222459dc76b0SRik van Riel  *    1GB       3       250MB
222559dc76b0SRik van Riel  *   10GB      10       0.9GB
222659dc76b0SRik van Riel  *  100GB      31         3GB
222759dc76b0SRik van Riel  *    1TB     101        10GB
222859dc76b0SRik van Riel  *   10TB     320        32GB
222914797e23SKOSAKI Motohiro  */
2230f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
22312c012a4aSKuo-Hsin Yang 				 struct scan_control *sc, bool trace)
223214797e23SKOSAKI Motohiro {
2233fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
22342a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22352a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
22362a2e4885SJohannes Weiner 	unsigned long inactive, active;
22372a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
22382a2e4885SJohannes Weiner 	unsigned long refaults;
223959dc76b0SRik van Riel 	unsigned long gb;
224059dc76b0SRik van Riel 
224174e3f3c3SMinchan Kim 	/*
224274e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
224374e3f3c3SMinchan Kim 	 * is pointless.
224474e3f3c3SMinchan Kim 	 */
224559dc76b0SRik van Riel 	if (!file && !total_swap_pages)
224642e2e457SYaowei Bai 		return false;
224774e3f3c3SMinchan Kim 
2248fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2249fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2250f8d1a311SMel Gorman 
22512a2e4885SJohannes Weiner 	/*
22522a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
22532a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
22542a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
22552a2e4885SJohannes Weiner 	 */
2256205b20ccSJohannes Weiner 	refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
22572c012a4aSKuo-Hsin Yang 	if (file && lruvec->refaults != refaults) {
22582a2e4885SJohannes Weiner 		inactive_ratio = 0;
22592a2e4885SJohannes Weiner 	} else {
226059dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
226159dc76b0SRik van Riel 		if (gb)
226259dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2263b39415b2SRik van Riel 		else
226459dc76b0SRik van Riel 			inactive_ratio = 1;
22652a2e4885SJohannes Weiner 	}
226659dc76b0SRik van Riel 
22672c012a4aSKuo-Hsin Yang 	if (trace)
22682a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2269fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2270fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2271fd538803SMichal Hocko 			inactive_ratio, file);
2272fd538803SMichal Hocko 
227359dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2274b39415b2SRik van Riel }
2275b39415b2SRik van Riel 
22764f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
22773b991208SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2278b69408e8SChristoph Lameter {
2279b39415b2SRik van Riel 	if (is_active_lru(lru)) {
22803b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc, true))
22811a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2282556adecbSRik van Riel 		return 0;
2283556adecbSRik van Riel 	}
2284556adecbSRik van Riel 
22851a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2286b69408e8SChristoph Lameter }
2287b69408e8SChristoph Lameter 
22889a265114SJohannes Weiner enum scan_balance {
22899a265114SJohannes Weiner 	SCAN_EQUAL,
22909a265114SJohannes Weiner 	SCAN_FRACT,
22919a265114SJohannes Weiner 	SCAN_ANON,
22929a265114SJohannes Weiner 	SCAN_FILE,
22939a265114SJohannes Weiner };
22949a265114SJohannes Weiner 
22951da177e4SLinus Torvalds /*
22964f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22974f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22984f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22994f98a2feSRik van Riel  * onto the active list instead of evict.
23004f98a2feSRik van Riel  *
2301be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2302be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
23034f98a2feSRik van Riel  */
230433377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
23056b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
23066b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
23074f98a2feSRik van Riel {
230833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
230990126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
23109a265114SJohannes Weiner 	u64 fraction[2];
23119a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2312599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
23139a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
23149a265114SJohannes Weiner 	enum scan_balance scan_balance;
23150bf1457fSJohannes Weiner 	unsigned long anon, file;
23169a265114SJohannes Weiner 	unsigned long ap, fp;
23179a265114SJohannes Weiner 	enum lru_list lru;
231876a33fc3SShaohua Li 
231976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2320d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
23219a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
232276a33fc3SShaohua Li 		goto out;
232376a33fc3SShaohua Li 	}
23244f98a2feSRik van Riel 
232510316b31SJohannes Weiner 	/*
232610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
232710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
232810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
232910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
233010316b31SJohannes Weiner 	 * too expensive.
233110316b31SJohannes Weiner 	 */
233202695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
23339a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
233410316b31SJohannes Weiner 		goto out;
233510316b31SJohannes Weiner 	}
233610316b31SJohannes Weiner 
233710316b31SJohannes Weiner 	/*
233810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
233910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
234010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
234110316b31SJohannes Weiner 	 */
234202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
23439a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
234410316b31SJohannes Weiner 		goto out;
234510316b31SJohannes Weiner 	}
234610316b31SJohannes Weiner 
234711d16c25SJohannes Weiner 	/*
234862376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
234962376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
235062376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
235162376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
235262376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
235362376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
235462376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
235562376251SJohannes Weiner 	 */
235662376251SJohannes Weiner 	if (global_reclaim(sc)) {
2357599d0c95SMel Gorman 		unsigned long pgdatfile;
2358599d0c95SMel Gorman 		unsigned long pgdatfree;
2359599d0c95SMel Gorman 		int z;
2360599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
236162376251SJohannes Weiner 
2362599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2363599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2364599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
23652ab051e1SJerome Marchand 
2366599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2367599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
23686aa303deSMel Gorman 			if (!managed_zone(zone))
2369599d0c95SMel Gorman 				continue;
2370599d0c95SMel Gorman 
2371599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2372599d0c95SMel Gorman 		}
2373599d0c95SMel Gorman 
2374599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
237506226226SDavid Rientjes 			/*
237606226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
237706226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
237806226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
237906226226SDavid Rientjes 			 */
23803b991208SJohannes Weiner 			if (!inactive_list_is_low(lruvec, false, sc, false) &&
238106226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
238206226226SDavid Rientjes 					>> sc->priority) {
238362376251SJohannes Weiner 				scan_balance = SCAN_ANON;
238462376251SJohannes Weiner 				goto out;
238562376251SJohannes Weiner 			}
238662376251SJohannes Weiner 		}
238706226226SDavid Rientjes 	}
238862376251SJohannes Weiner 
238962376251SJohannes Weiner 	/*
2390316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2391316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2392316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2393316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2394316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2395316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2396316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2397e9868505SRik van Riel 	 */
23983b991208SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, sc, false) &&
239971ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
24009a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2401e9868505SRik van Riel 		goto out;
24024f98a2feSRik van Riel 	}
24034f98a2feSRik van Riel 
24049a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
24059a265114SJohannes Weiner 
24064f98a2feSRik van Riel 	/*
240758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
240858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
240958c37f6eSKOSAKI Motohiro 	 */
241002695175SJohannes Weiner 	anon_prio = swappiness;
241175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
241258c37f6eSKOSAKI Motohiro 
241358c37f6eSKOSAKI Motohiro 	/*
24144f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
24154f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
24164f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
24174f98a2feSRik van Riel 	 *
24184f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
24194f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
24204f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
24214f98a2feSRik van Riel 	 *
24224f98a2feSRik van Riel 	 * anon in [0], file in [1]
24234f98a2feSRik van Riel 	 */
24242ab051e1SJerome Marchand 
2425fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2426fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2427fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2428fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
24292ab051e1SJerome Marchand 
2430599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
243158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
24326e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
24336e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
24344f98a2feSRik van Riel 	}
24354f98a2feSRik van Riel 
24366e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
24376e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
24386e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
24394f98a2feSRik van Riel 	}
24404f98a2feSRik van Riel 
24414f98a2feSRik van Riel 	/*
244200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
244300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
244400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
24454f98a2feSRik van Riel 	 */
2446fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
24476e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
24484f98a2feSRik van Riel 
2449fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
24506e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2451599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
24524f98a2feSRik van Riel 
245376a33fc3SShaohua Li 	fraction[0] = ap;
245476a33fc3SShaohua Li 	fraction[1] = fp;
245576a33fc3SShaohua Li 	denominator = ap + fp + 1;
245676a33fc3SShaohua Li out:
24576b4f7799SJohannes Weiner 	*lru_pages = 0;
24584111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24594111304dSHugh Dickins 		int file = is_file_lru(lru);
24609783aa99SChris Down 		unsigned long lruvec_size;
246176a33fc3SShaohua Li 		unsigned long scan;
24621bc63fb1SChris Down 		unsigned long protection;
246376a33fc3SShaohua Li 
24649783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
24651bc63fb1SChris Down 		protection = mem_cgroup_protection(memcg,
24661bc63fb1SChris Down 						   sc->memcg_low_reclaim);
24679783aa99SChris Down 
24681bc63fb1SChris Down 		if (protection) {
24699783aa99SChris Down 			/*
24709783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
24719783aa99SChris Down 			 * its current usage to its memory.low or memory.min
24729783aa99SChris Down 			 * setting.
24739783aa99SChris Down 			 *
24749783aa99SChris Down 			 * This is important, as otherwise scanning aggression
24759783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
24769783aa99SChris Down 			 * approach the memory protection threshold, to totally
24779783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
24789783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
24799783aa99SChris Down 			 * also means we simply get no protection at all if we
24809783aa99SChris Down 			 * set it too low, which is not ideal.
24811bc63fb1SChris Down 			 *
24821bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
24831bc63fb1SChris Down 			 * pressure by how much of the total memory used is
24841bc63fb1SChris Down 			 * within protection thresholds.
24859783aa99SChris Down 			 *
24869de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
24879de7ca46SChris Down 			 * we skip over all groups that are within their low
24889de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
24899de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
24909de7ca46SChris Down 			 * the best-effort low protection. However, we still
24919de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
24929de7ca46SChris Down 			 * that case instead of simply punishing them all
24939de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
24941bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
24951bc63fb1SChris Down 			 * again by how much of the total memory used is under
24961bc63fb1SChris Down 			 * hard protection.
24979783aa99SChris Down 			 */
24981bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
24991bc63fb1SChris Down 
25001bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
25011bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
25021bc63fb1SChris Down 
25031bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
25041bc63fb1SChris Down 				cgroup_size;
25059783aa99SChris Down 
25069783aa99SChris Down 			/*
25071bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
25089de7ca46SChris Down 			 * reclaim moving forwards, avoiding decremeting
25099de7ca46SChris Down 			 * sc->priority further than desirable.
25109783aa99SChris Down 			 */
25111bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
25129783aa99SChris Down 		} else {
25139783aa99SChris Down 			scan = lruvec_size;
25149783aa99SChris Down 		}
25159783aa99SChris Down 
25169783aa99SChris Down 		scan >>= sc->priority;
25179783aa99SChris Down 
2518688035f7SJohannes Weiner 		/*
2519688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2520688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2521688035f7SJohannes Weiner 		 */
2522688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
25239783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
25249a265114SJohannes Weiner 
25259a265114SJohannes Weiner 		switch (scan_balance) {
25269a265114SJohannes Weiner 		case SCAN_EQUAL:
25279a265114SJohannes Weiner 			/* Scan lists relative to size */
25289a265114SJohannes Weiner 			break;
25299a265114SJohannes Weiner 		case SCAN_FRACT:
25309a265114SJohannes Weiner 			/*
25319a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
25329a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
253368600f62SRoman Gushchin 			 * Make sure we don't miss the last page
253468600f62SRoman Gushchin 			 * because of a round-off error.
25359a265114SJohannes Weiner 			 */
253668600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
25376f04f48dSSuleiman Souhlal 						  denominator);
25389a265114SJohannes Weiner 			break;
25399a265114SJohannes Weiner 		case SCAN_FILE:
25409a265114SJohannes Weiner 		case SCAN_ANON:
25419a265114SJohannes Weiner 			/* Scan one type exclusively */
25426b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
25439783aa99SChris Down 				lruvec_size = 0;
25449a265114SJohannes Weiner 				scan = 0;
25456b4f7799SJohannes Weiner 			}
25469a265114SJohannes Weiner 			break;
25479a265114SJohannes Weiner 		default:
25489a265114SJohannes Weiner 			/* Look ma, no brain */
25499a265114SJohannes Weiner 			BUG();
25509a265114SJohannes Weiner 		}
25516b4f7799SJohannes Weiner 
25529783aa99SChris Down 		*lru_pages += lruvec_size;
25534111304dSHugh Dickins 		nr[lru] = scan;
255476a33fc3SShaohua Li 	}
25556e08a369SWu Fengguang }
25564f98a2feSRik van Riel 
25579b4f98cdSJohannes Weiner /*
2558a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
25599b4f98cdSJohannes Weiner  */
2560a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
25616b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
25629b4f98cdSJohannes Weiner {
2563ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
25649b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2565e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25669b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25679b4f98cdSJohannes Weiner 	enum lru_list lru;
25689b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25699b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25709b4f98cdSJohannes Weiner 	struct blk_plug plug;
25711a501907SMel Gorman 	bool scan_adjusted;
25729b4f98cdSJohannes Weiner 
257333377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
25749b4f98cdSJohannes Weiner 
2575e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2576e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2577e82e0561SMel Gorman 
25781a501907SMel Gorman 	/*
25791a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25801a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25811a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25821a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25831a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25841a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25851a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25861a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25871a501907SMel Gorman 	 * dropped to zero at the first pass.
25881a501907SMel Gorman 	 */
25891a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
25901a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25911a501907SMel Gorman 
25929b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25939b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25949b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2595e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2596e82e0561SMel Gorman 		unsigned long nr_scanned;
2597e82e0561SMel Gorman 
25989b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25999b4f98cdSJohannes Weiner 			if (nr[lru]) {
26009b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
26019b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
26029b4f98cdSJohannes Weiner 
26039b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
26043b991208SJohannes Weiner 							    lruvec, sc);
26059b4f98cdSJohannes Weiner 			}
26069b4f98cdSJohannes Weiner 		}
2607e82e0561SMel Gorman 
2608bd041733SMichal Hocko 		cond_resched();
2609bd041733SMichal Hocko 
2610e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2611e82e0561SMel Gorman 			continue;
2612e82e0561SMel Gorman 
26139b4f98cdSJohannes Weiner 		/*
2614e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
26151a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2616e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2617e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2618e82e0561SMel Gorman 		 * proportional to the original scan target.
2619e82e0561SMel Gorman 		 */
2620e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2621e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2622e82e0561SMel Gorman 
26231a501907SMel Gorman 		/*
26241a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26251a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
26261a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
26271a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
26281a501907SMel Gorman 		 */
26291a501907SMel Gorman 		if (!nr_file || !nr_anon)
26301a501907SMel Gorman 			break;
26311a501907SMel Gorman 
2632e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2633e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2634e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2635e82e0561SMel Gorman 			lru = LRU_BASE;
2636e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2637e82e0561SMel Gorman 		} else {
2638e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2639e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2640e82e0561SMel Gorman 			lru = LRU_FILE;
2641e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2642e82e0561SMel Gorman 		}
2643e82e0561SMel Gorman 
2644e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2645e82e0561SMel Gorman 		nr[lru] = 0;
2646e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2647e82e0561SMel Gorman 
2648e82e0561SMel Gorman 		/*
2649e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2650e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2651e82e0561SMel Gorman 		 */
2652e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2653e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2654e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2655e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2656e82e0561SMel Gorman 
2657e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2658e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2659e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2660e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2661e82e0561SMel Gorman 
2662e82e0561SMel Gorman 		scan_adjusted = true;
26639b4f98cdSJohannes Weiner 	}
26649b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26659b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26669b4f98cdSJohannes Weiner 
26679b4f98cdSJohannes Weiner 	/*
26689b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26699b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26709b4f98cdSJohannes Weiner 	 */
26713b991208SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, sc, true))
26729b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26739b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26749b4f98cdSJohannes Weiner }
26759b4f98cdSJohannes Weiner 
267623b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26779e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
267823b9da55SMel Gorman {
2679d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
268023b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26819e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
268223b9da55SMel Gorman 		return true;
268323b9da55SMel Gorman 
268423b9da55SMel Gorman 	return false;
268523b9da55SMel Gorman }
268623b9da55SMel Gorman 
26874f98a2feSRik van Riel /*
268823b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
268923b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
269023b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
269123b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
269223b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26933e7d3449SMel Gorman  */
2694a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26953e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26963e7d3449SMel Gorman 					struct scan_control *sc)
26973e7d3449SMel Gorman {
26983e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26993e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2700a9dd0a83SMel Gorman 	int z;
27013e7d3449SMel Gorman 
27023e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
27039e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
27043e7d3449SMel Gorman 		return false;
27053e7d3449SMel Gorman 
27063e7d3449SMel Gorman 	/*
27075ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
27085ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
27095ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
27105ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
27115ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
27125ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
27135ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
27145ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
27152876592fSMel Gorman 	 */
27162876592fSMel Gorman 	if (!nr_reclaimed)
27172876592fSMel Gorman 		return false;
27183e7d3449SMel Gorman 
27193e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2720a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2721a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
27226aa303deSMel Gorman 		if (!managed_zone(zone))
2723a9dd0a83SMel Gorman 			continue;
2724a9dd0a83SMel Gorman 
2725a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2726cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
27273e7d3449SMel Gorman 		case COMPACT_CONTINUE:
27283e7d3449SMel Gorman 			return false;
27293e7d3449SMel Gorman 		default:
2730a9dd0a83SMel Gorman 			/* check next zone */
2731a9dd0a83SMel Gorman 			;
27323e7d3449SMel Gorman 		}
27333e7d3449SMel Gorman 	}
27341c6c1597SHillf Danton 
27351c6c1597SHillf Danton 	/*
27361c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
27371c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
27381c6c1597SHillf Danton 	 */
27391c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
27401c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
27411c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
27421c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
27431c6c1597SHillf Danton 
27445ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2745a9dd0a83SMel Gorman }
27463e7d3449SMel Gorman 
2747e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2748e3c1ac58SAndrey Ryabinin {
2749e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2750e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2751e3c1ac58SAndrey Ryabinin }
2752e3c1ac58SAndrey Ryabinin 
2753970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2754f16015fbSJohannes Weiner {
2755cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
27569b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27572344d7e4SJohannes Weiner 	bool reclaimable = false;
27589b4f98cdSJohannes Weiner 
27599b4f98cdSJohannes Weiner 	do {
27605660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
2761a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2762694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
27635660048cSJohannes Weiner 
2764d108c772SAndrey Ryabinin 		memset(&sc->nr, 0, sizeof(sc->nr));
2765d108c772SAndrey Ryabinin 
27669b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
27679b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
27689b4f98cdSJohannes Weiner 
27691ba6fc9aSJohannes Weiner 		memcg = mem_cgroup_iter(root, NULL, NULL);
2770694fbc0fSAndrew Morton 		do {
27716b4f7799SJohannes Weiner 			unsigned long lru_pages;
27728e8ae645SJohannes Weiner 			unsigned long reclaimed;
2773cb731d6cSVladimir Davydov 			unsigned long scanned;
27749b4f98cdSJohannes Weiner 
2775bf8d5d52SRoman Gushchin 			switch (mem_cgroup_protected(root, memcg)) {
2776bf8d5d52SRoman Gushchin 			case MEMCG_PROT_MIN:
2777bf8d5d52SRoman Gushchin 				/*
2778bf8d5d52SRoman Gushchin 				 * Hard protection.
2779bf8d5d52SRoman Gushchin 				 * If there is no reclaimable memory, OOM.
2780bf8d5d52SRoman Gushchin 				 */
2781bf8d5d52SRoman Gushchin 				continue;
2782bf8d5d52SRoman Gushchin 			case MEMCG_PROT_LOW:
2783bf8d5d52SRoman Gushchin 				/*
2784bf8d5d52SRoman Gushchin 				 * Soft protection.
2785bf8d5d52SRoman Gushchin 				 * Respect the protection only as long as
2786bf8d5d52SRoman Gushchin 				 * there is an unprotected supply
2787bf8d5d52SRoman Gushchin 				 * of reclaimable memory from other cgroups.
2788bf8d5d52SRoman Gushchin 				 */
2789d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2790d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2791241994edSJohannes Weiner 					continue;
2792d6622f63SYisheng Xie 				}
2793e27be240SJohannes Weiner 				memcg_memory_event(memcg, MEMCG_LOW);
2794bf8d5d52SRoman Gushchin 				break;
2795bf8d5d52SRoman Gushchin 			case MEMCG_PROT_NONE:
27969783aa99SChris Down 				/*
27979783aa99SChris Down 				 * All protection thresholds breached. We may
27989783aa99SChris Down 				 * still choose to vary the scan pressure
27999783aa99SChris Down 				 * applied based on by how much the cgroup in
28009783aa99SChris Down 				 * question has exceeded its protection
28019783aa99SChris Down 				 * thresholds (see get_scan_count).
28029783aa99SChris Down 				 */
2803bf8d5d52SRoman Gushchin 				break;
2804241994edSJohannes Weiner 			}
2805241994edSJohannes Weiner 
28068e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2807cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2808a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2809a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2810f9be23d6SKonstantin Khlebnikov 
281128360f39SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
281228360f39SMel Gorman 					sc->priority);
2813cb731d6cSVladimir Davydov 
28148e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
28158e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
28168e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
28178e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
28188e8ae645SJohannes Weiner 
28191ba6fc9aSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, NULL)));
282070ddf637SAnton Vorontsov 
28216b4f7799SJohannes Weiner 		if (reclaim_state) {
2822cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
28236b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
28246b4f7799SJohannes Weiner 		}
28256b4f7799SJohannes Weiner 
28268e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
28278e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
282870ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
282970ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
283070ddf637SAnton Vorontsov 
28312344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
28322344d7e4SJohannes Weiner 			reclaimable = true;
28332344d7e4SJohannes Weiner 
2834e3c1ac58SAndrey Ryabinin 		if (current_is_kswapd()) {
2835d108c772SAndrey Ryabinin 			/*
2836e3c1ac58SAndrey Ryabinin 			 * If reclaim is isolating dirty pages under writeback,
2837e3c1ac58SAndrey Ryabinin 			 * it implies that the long-lived page allocation rate
2838e3c1ac58SAndrey Ryabinin 			 * is exceeding the page laundering rate. Either the
2839e3c1ac58SAndrey Ryabinin 			 * global limits are not being effective at throttling
2840e3c1ac58SAndrey Ryabinin 			 * processes due to the page distribution throughout
2841e3c1ac58SAndrey Ryabinin 			 * zones or there is heavy usage of a slow backing
2842e3c1ac58SAndrey Ryabinin 			 * device. The only option is to throttle from reclaim
2843e3c1ac58SAndrey Ryabinin 			 * context which is not ideal as there is no guarantee
2844d108c772SAndrey Ryabinin 			 * the dirtying process is throttled in the same way
2845d108c772SAndrey Ryabinin 			 * balance_dirty_pages() manages.
2846d108c772SAndrey Ryabinin 			 *
2847e3c1ac58SAndrey Ryabinin 			 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2848e3c1ac58SAndrey Ryabinin 			 * count the number of pages under pages flagged for
2849e3c1ac58SAndrey Ryabinin 			 * immediate reclaim and stall if any are encountered
2850e3c1ac58SAndrey Ryabinin 			 * in the nr_immediate check below.
2851d108c772SAndrey Ryabinin 			 */
2852d108c772SAndrey Ryabinin 			if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2853d108c772SAndrey Ryabinin 				set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2854d108c772SAndrey Ryabinin 
2855d108c772SAndrey Ryabinin 			/*
2856d108c772SAndrey Ryabinin 			 * Tag a node as congested if all the dirty pages
2857d108c772SAndrey Ryabinin 			 * scanned were backed by a congested BDI and
2858d108c772SAndrey Ryabinin 			 * wait_iff_congested will stall.
2859d108c772SAndrey Ryabinin 			 */
2860d108c772SAndrey Ryabinin 			if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2861d108c772SAndrey Ryabinin 				set_bit(PGDAT_CONGESTED, &pgdat->flags);
2862d108c772SAndrey Ryabinin 
2863d108c772SAndrey Ryabinin 			/* Allow kswapd to start writing pages during reclaim.*/
2864d108c772SAndrey Ryabinin 			if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2865d108c772SAndrey Ryabinin 				set_bit(PGDAT_DIRTY, &pgdat->flags);
2866d108c772SAndrey Ryabinin 
2867d108c772SAndrey Ryabinin 			/*
2868d108c772SAndrey Ryabinin 			 * If kswapd scans pages marked marked for immediate
2869d108c772SAndrey Ryabinin 			 * reclaim and under writeback (nr_immediate), it
2870d108c772SAndrey Ryabinin 			 * implies that pages are cycling through the LRU
2871d108c772SAndrey Ryabinin 			 * faster than they are written so also forcibly stall.
2872d108c772SAndrey Ryabinin 			 */
2873d108c772SAndrey Ryabinin 			if (sc->nr.immediate)
2874d108c772SAndrey Ryabinin 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2875d108c772SAndrey Ryabinin 		}
2876d108c772SAndrey Ryabinin 
2877d108c772SAndrey Ryabinin 		/*
2878e3c1ac58SAndrey Ryabinin 		 * Legacy memcg will stall in page writeback so avoid forcibly
2879e3c1ac58SAndrey Ryabinin 		 * stalling in wait_iff_congested().
2880e3c1ac58SAndrey Ryabinin 		 */
2881e3c1ac58SAndrey Ryabinin 		if (!global_reclaim(sc) && sane_reclaim(sc) &&
2882e3c1ac58SAndrey Ryabinin 		    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2883e3c1ac58SAndrey Ryabinin 			set_memcg_congestion(pgdat, root, true);
2884e3c1ac58SAndrey Ryabinin 
2885e3c1ac58SAndrey Ryabinin 		/*
2886d108c772SAndrey Ryabinin 		 * Stall direct reclaim for IO completions if underlying BDIs
2887d108c772SAndrey Ryabinin 		 * and node is congested. Allow kswapd to continue until it
2888d108c772SAndrey Ryabinin 		 * starts encountering unqueued dirty pages or cycling through
2889d108c772SAndrey Ryabinin 		 * the LRU too quickly.
2890d108c772SAndrey Ryabinin 		 */
2891d108c772SAndrey Ryabinin 		if (!sc->hibernation_mode && !current_is_kswapd() &&
2892e3c1ac58SAndrey Ryabinin 		   current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2893e3c1ac58SAndrey Ryabinin 			wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2894d108c772SAndrey Ryabinin 
2895a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
28965ee04716SVlastimil Babka 					 sc));
28972344d7e4SJohannes Weiner 
2898c73322d0SJohannes Weiner 	/*
2899c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2900c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2901c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2902c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2903c73322d0SJohannes Weiner 	 */
2904c73322d0SJohannes Weiner 	if (reclaimable)
2905c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2906c73322d0SJohannes Weiner 
29072344d7e4SJohannes Weiner 	return reclaimable;
2908f16015fbSJohannes Weiner }
2909f16015fbSJohannes Weiner 
291053853e2dSVlastimil Babka /*
2911fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2912fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2913fdd4c614SVlastimil Babka  * should reclaim first.
291453853e2dSVlastimil Babka  */
29154f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2916fe4b1b24SMel Gorman {
291731483b6aSMel Gorman 	unsigned long watermark;
2918fdd4c614SVlastimil Babka 	enum compact_result suitable;
2919fe4b1b24SMel Gorman 
2920fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2921fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2922fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2923fdd4c614SVlastimil Babka 		return true;
2924fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2925fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2926fe4b1b24SMel Gorman 		return false;
2927fe4b1b24SMel Gorman 
2928fdd4c614SVlastimil Babka 	/*
2929fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2930fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2931fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2932fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2933fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2934fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2935fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2936fdd4c614SVlastimil Babka 	 */
2937fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2938fdd4c614SVlastimil Babka 
2939fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2940fe4b1b24SMel Gorman }
2941fe4b1b24SMel Gorman 
29421da177e4SLinus Torvalds /*
29431da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
29441da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
29451da177e4SLinus Torvalds  * request.
29461da177e4SLinus Torvalds  *
29471da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
29481da177e4SLinus Torvalds  * scan then give up on it.
29491da177e4SLinus Torvalds  */
29500a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
29511da177e4SLinus Torvalds {
2952dd1a239fSMel Gorman 	struct zoneref *z;
295354a6eb5cSMel Gorman 	struct zone *zone;
29540608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29550608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2956619d0d76SWeijie Yang 	gfp_t orig_mask;
295779dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
29581cfb419bSKAMEZAWA Hiroyuki 
2959cc715d99SMel Gorman 	/*
2960cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2961cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2962cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2963cc715d99SMel Gorman 	 */
2964619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2965b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2966cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29674f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2968b2e18757SMel Gorman 	}
2969cc715d99SMel Gorman 
2970d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2971b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2972b2e18757SMel Gorman 		/*
29731cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29741cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29751cfb419bSKAMEZAWA Hiroyuki 		 */
297689b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2977344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2978344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29791da177e4SLinus Torvalds 				continue;
298065ec02cbSVladimir Davydov 
2981e0887c19SRik van Riel 			/*
2982e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2983e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2984e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2985e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2986e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2987c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2988c7cfa37bSCopot Alexandru 			 * page allocations.
2989e0887c19SRik van Riel 			 */
29900b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29910b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29924f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29930b06496aSJohannes Weiner 				sc->compaction_ready = true;
2994e0887c19SRik van Riel 				continue;
2995e0887c19SRik van Riel 			}
29960b06496aSJohannes Weiner 
29970608f43dSAndrew Morton 			/*
299879dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
299979dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
300079dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
300179dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
300279dafcdcSMel Gorman 			 */
300379dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
300479dafcdcSMel Gorman 				continue;
300579dafcdcSMel Gorman 
300679dafcdcSMel Gorman 			/*
30070608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
30080608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
30090608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
30100608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
30110608f43dSAndrew Morton 			 */
30120608f43dSAndrew Morton 			nr_soft_scanned = 0;
3013ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
30140608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
30150608f43dSAndrew Morton 						&nr_soft_scanned);
30160608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
30170608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
3018ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
3019ac34a1a3SKAMEZAWA Hiroyuki 		}
3020d149e3b2SYing Han 
302179dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
302279dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
302379dafcdcSMel Gorman 			continue;
302479dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
3025970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
30261da177e4SLinus Torvalds 	}
3027e0c23279SMel Gorman 
302865ec02cbSVladimir Davydov 	/*
3029619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3030619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3031619d0d76SWeijie Yang 	 */
3032619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
30331da177e4SLinus Torvalds }
30341da177e4SLinus Torvalds 
30352a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
30362a2e4885SJohannes Weiner {
30372a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
30382a2e4885SJohannes Weiner 
30392a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
30402a2e4885SJohannes Weiner 	do {
30412a2e4885SJohannes Weiner 		unsigned long refaults;
30422a2e4885SJohannes Weiner 		struct lruvec *lruvec;
30432a2e4885SJohannes Weiner 
30442a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
3045205b20ccSJohannes Weiner 		refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
30462a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
30472a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
30482a2e4885SJohannes Weiner }
30492a2e4885SJohannes Weiner 
30501da177e4SLinus Torvalds /*
30511da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
30521da177e4SLinus Torvalds  *
30531da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
30541da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
30551da177e4SLinus Torvalds  *
30561da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
30571da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
30585b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
30595b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
30605b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
30615b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3062a41f24eaSNishanth Aravamudan  *
3063a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3064a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30651da177e4SLinus Torvalds  */
3066dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30673115cd91SVladimir Davydov 					  struct scan_control *sc)
30681da177e4SLinus Torvalds {
3069241994edSJohannes Weiner 	int initial_priority = sc->priority;
30702a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30712a2e4885SJohannes Weiner 	struct zoneref *z;
30722a2e4885SJohannes Weiner 	struct zone *zone;
3073241994edSJohannes Weiner retry:
3074873b4771SKeika Kobayashi 	delayacct_freepages_start();
3075873b4771SKeika Kobayashi 
307689b5fae5SJohannes Weiner 	if (global_reclaim(sc))
30777cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30781da177e4SLinus Torvalds 
30799e3b2f8cSKonstantin Khlebnikov 	do {
308070ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
308170ddf637SAnton Vorontsov 				sc->priority);
308266e1707bSBalbir Singh 		sc->nr_scanned = 0;
30830a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3084e0c23279SMel Gorman 
3085bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30860b06496aSJohannes Weiner 			break;
30870b06496aSJohannes Weiner 
30880b06496aSJohannes Weiner 		if (sc->compaction_ready)
30890b06496aSJohannes Weiner 			break;
30901da177e4SLinus Torvalds 
30911da177e4SLinus Torvalds 		/*
30920e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30930e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30940e50ce3bSMinchan Kim 		 */
30950e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30960e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30970b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3098bb21c7ceSKOSAKI Motohiro 
30992a2e4885SJohannes Weiner 	last_pgdat = NULL;
31002a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
31012a2e4885SJohannes Weiner 					sc->nodemask) {
31022a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
31032a2e4885SJohannes Weiner 			continue;
31042a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
31052a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3106e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
31072a2e4885SJohannes Weiner 	}
31082a2e4885SJohannes Weiner 
3109873b4771SKeika Kobayashi 	delayacct_freepages_end();
3110873b4771SKeika Kobayashi 
3111bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3112bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3113bb21c7ceSKOSAKI Motohiro 
31140cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
31150b06496aSJohannes Weiner 	if (sc->compaction_ready)
31167335084dSMel Gorman 		return 1;
31177335084dSMel Gorman 
3118241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3119d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3120241994edSJohannes Weiner 		sc->priority = initial_priority;
3121d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3122d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3123241994edSJohannes Weiner 		goto retry;
3124241994edSJohannes Weiner 	}
3125241994edSJohannes Weiner 
3126bb21c7ceSKOSAKI Motohiro 	return 0;
31271da177e4SLinus Torvalds }
31281da177e4SLinus Torvalds 
3129c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
31305515061dSMel Gorman {
31315515061dSMel Gorman 	struct zone *zone;
31325515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
31335515061dSMel Gorman 	unsigned long free_pages = 0;
31345515061dSMel Gorman 	int i;
31355515061dSMel Gorman 	bool wmark_ok;
31365515061dSMel Gorman 
3137c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3138c73322d0SJohannes Weiner 		return true;
3139c73322d0SJohannes Weiner 
31405515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
31415515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3142d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3143d450abd8SJohannes Weiner 			continue;
3144d450abd8SJohannes Weiner 
3145d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3146675becceSMel Gorman 			continue;
3147675becceSMel Gorman 
31485515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
31495515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
31505515061dSMel Gorman 	}
31515515061dSMel Gorman 
3152675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3153675becceSMel Gorman 	if (!pfmemalloc_reserve)
3154675becceSMel Gorman 		return true;
3155675becceSMel Gorman 
31565515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31575515061dSMel Gorman 
31585515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31595515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
316038087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
31615515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
31625515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31635515061dSMel Gorman 	}
31645515061dSMel Gorman 
31655515061dSMel Gorman 	return wmark_ok;
31665515061dSMel Gorman }
31675515061dSMel Gorman 
31685515061dSMel Gorman /*
31695515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31705515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31715515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
317250694c28SMel Gorman  * when the low watermark is reached.
317350694c28SMel Gorman  *
317450694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
317550694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31765515061dSMel Gorman  */
317750694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31785515061dSMel Gorman 					nodemask_t *nodemask)
31795515061dSMel Gorman {
3180675becceSMel Gorman 	struct zoneref *z;
31815515061dSMel Gorman 	struct zone *zone;
3182675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31835515061dSMel Gorman 
31845515061dSMel Gorman 	/*
31855515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31865515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31875515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31885515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31895515061dSMel Gorman 	 * processes to block on log_wait_commit().
31905515061dSMel Gorman 	 */
31915515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
319250694c28SMel Gorman 		goto out;
319350694c28SMel Gorman 
319450694c28SMel Gorman 	/*
319550694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
319650694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
319750694c28SMel Gorman 	 */
319850694c28SMel Gorman 	if (fatal_signal_pending(current))
319950694c28SMel Gorman 		goto out;
32005515061dSMel Gorman 
3201675becceSMel Gorman 	/*
3202675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3203675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3204675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3205675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3206675becceSMel Gorman 	 *
3207675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3208675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3209675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3210675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3211675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3212675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3213675becceSMel Gorman 	 * should make reasonable progress.
3214675becceSMel Gorman 	 */
3215675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
321617636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3217675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3218675becceSMel Gorman 			continue;
3219675becceSMel Gorman 
3220675becceSMel Gorman 		/* Throttle based on the first usable node */
32215515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3222c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
322350694c28SMel Gorman 			goto out;
3224675becceSMel Gorman 		break;
3225675becceSMel Gorman 	}
3226675becceSMel Gorman 
3227675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3228675becceSMel Gorman 	if (!pgdat)
3229675becceSMel Gorman 		goto out;
32305515061dSMel Gorman 
323168243e76SMel Gorman 	/* Account for the throttling */
323268243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
323368243e76SMel Gorman 
32345515061dSMel Gorman 	/*
32355515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
32365515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
32375515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
32385515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
32395515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
32405515061dSMel Gorman 	 * second before continuing.
32415515061dSMel Gorman 	 */
32425515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
32435515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3244c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
324550694c28SMel Gorman 
324650694c28SMel Gorman 		goto check_pending;
32475515061dSMel Gorman 	}
32485515061dSMel Gorman 
32495515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
32505515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3251c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
325250694c28SMel Gorman 
325350694c28SMel Gorman check_pending:
325450694c28SMel Gorman 	if (fatal_signal_pending(current))
325550694c28SMel Gorman 		return true;
325650694c28SMel Gorman 
325750694c28SMel Gorman out:
325850694c28SMel Gorman 	return false;
32595515061dSMel Gorman }
32605515061dSMel Gorman 
3261dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3262327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
326366e1707bSBalbir Singh {
326433906bc5SMel Gorman 	unsigned long nr_reclaimed;
326566e1707bSBalbir Singh 	struct scan_control sc = {
326622fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3267f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3268b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3269ee814fe2SJohannes Weiner 		.order = order,
3270ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3271ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3272ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3273a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32742e2e4259SKOSAKI Motohiro 		.may_swap = 1,
327566e1707bSBalbir Singh 	};
327666e1707bSBalbir Singh 
32775515061dSMel Gorman 	/*
3278bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3279bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3280bb451fdfSGreg Thelen 	 */
3281bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3282bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3283bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3284bb451fdfSGreg Thelen 
3285bb451fdfSGreg Thelen 	/*
328650694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
328750694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
328850694c28SMel Gorman 	 * point.
32895515061dSMel Gorman 	 */
3290f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32915515061dSMel Gorman 		return 1;
32925515061dSMel Gorman 
32931732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
32943481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
329533906bc5SMel Gorman 
32963115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
329733906bc5SMel Gorman 
329833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
32991732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
330033906bc5SMel Gorman 
330133906bc5SMel Gorman 	return nr_reclaimed;
330266e1707bSBalbir Singh }
330366e1707bSBalbir Singh 
3304c255a458SAndrew Morton #ifdef CONFIG_MEMCG
330566e1707bSBalbir Singh 
3306d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3307a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
33084e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3309ef8f2327SMel Gorman 						pg_data_t *pgdat,
33100ae5e89cSYing Han 						unsigned long *nr_scanned)
33114e416953SBalbir Singh {
33124e416953SBalbir Singh 	struct scan_control sc = {
3313b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3314ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
33154e416953SBalbir Singh 		.may_writepage = !laptop_mode,
33164e416953SBalbir Singh 		.may_unmap = 1,
3317b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
33184e416953SBalbir Singh 		.may_swap = !noswap,
33194e416953SBalbir Singh 	};
33206b4f7799SJohannes Weiner 	unsigned long lru_pages;
33210ae5e89cSYing Han 
3322d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3323d2e5fb92SMichal Hocko 
33244e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
33254e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3326bdce6d9eSKOSAKI Motohiro 
33279e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
33283481c37fSYafang Shao 						      sc.gfp_mask);
3329bdce6d9eSKOSAKI Motohiro 
33304e416953SBalbir Singh 	/*
33314e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
33324e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3333a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
33344e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
33354e416953SBalbir Singh 	 * the priority and make it zero.
33364e416953SBalbir Singh 	 */
3337ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3338bdce6d9eSKOSAKI Motohiro 
3339bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3340bdce6d9eSKOSAKI Motohiro 
33410ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
33420308f7cfSYafang Shao 
33434e416953SBalbir Singh 	return sc.nr_reclaimed;
33444e416953SBalbir Singh }
33454e416953SBalbir Singh 
334672835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3347b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
33488c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3349b70a2a21SJohannes Weiner 					   bool may_swap)
335066e1707bSBalbir Singh {
3351bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3352eb414681SJohannes Weiner 	unsigned long pflags;
3353499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
335466e1707bSBalbir Singh 	struct scan_control sc = {
3355b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33567dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3357ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3358b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3359ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3360ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
336166e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3362a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3363b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3364a09ed5e0SYing Han 	};
3365*fa40d1eeSShakeel Butt 	/*
3366*fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3367*fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3368*fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3369*fa40d1eeSShakeel Butt 	 */
3370*fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
337166e1707bSBalbir Singh 
33721732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3373bdce6d9eSKOSAKI Motohiro 
33743481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3375bdce6d9eSKOSAKI Motohiro 
3376eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3377499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3378eb414681SJohannes Weiner 
33793115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3380eb414681SJohannes Weiner 
3381499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3382eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3383bdce6d9eSKOSAKI Motohiro 
3384bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
33851732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3386bdce6d9eSKOSAKI Motohiro 
3387bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
338866e1707bSBalbir Singh }
338966e1707bSBalbir Singh #endif
339066e1707bSBalbir Singh 
33911d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3392ef8f2327SMel Gorman 				struct scan_control *sc)
3393f16015fbSJohannes Weiner {
3394b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3395b95a2f2dSJohannes Weiner 
3396b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3397b95a2f2dSJohannes Weiner 		return;
3398b95a2f2dSJohannes Weiner 
3399b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3400b95a2f2dSJohannes Weiner 	do {
3401ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3402f16015fbSJohannes Weiner 
34033b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, sc, true))
34041a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
34059e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3406b95a2f2dSJohannes Weiner 
3407b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3408b95a2f2dSJohannes Weiner 	} while (memcg);
3409f16015fbSJohannes Weiner }
3410f16015fbSJohannes Weiner 
34111c30844dSMel Gorman static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
34121c30844dSMel Gorman {
34131c30844dSMel Gorman 	int i;
34141c30844dSMel Gorman 	struct zone *zone;
34151c30844dSMel Gorman 
34161c30844dSMel Gorman 	/*
34171c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
34181c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
34191c30844dSMel Gorman 	 * should not be checked at the time time as reclaim would
34201c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
34211c30844dSMel Gorman 	 * zone is balanced.
34221c30844dSMel Gorman 	 */
34231c30844dSMel Gorman 	for (i = classzone_idx; i >= 0; i--) {
34241c30844dSMel Gorman 		zone = pgdat->node_zones + i;
34251c30844dSMel Gorman 		if (!managed_zone(zone))
34261c30844dSMel Gorman 			continue;
34271c30844dSMel Gorman 
34281c30844dSMel Gorman 		if (zone->watermark_boost)
34291c30844dSMel Gorman 			return true;
34301c30844dSMel Gorman 	}
34311c30844dSMel Gorman 
34321c30844dSMel Gorman 	return false;
34331c30844dSMel Gorman }
34341c30844dSMel Gorman 
3435e716f2ebSMel Gorman /*
3436e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3437e716f2ebSMel Gorman  * and classzone_idx
3438e716f2ebSMel Gorman  */
3439e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
344060cefed4SJohannes Weiner {
3441e716f2ebSMel Gorman 	int i;
3442e716f2ebSMel Gorman 	unsigned long mark = -1;
3443e716f2ebSMel Gorman 	struct zone *zone;
344460cefed4SJohannes Weiner 
34451c30844dSMel Gorman 	/*
34461c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
34471c30844dSMel Gorman 	 * meet watermarks.
34481c30844dSMel Gorman 	 */
3449e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3450e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
34516256c6b4SMel Gorman 
3452e716f2ebSMel Gorman 		if (!managed_zone(zone))
3453e716f2ebSMel Gorman 			continue;
3454e716f2ebSMel Gorman 
3455e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3456e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
34576256c6b4SMel Gorman 			return true;
345860cefed4SJohannes Weiner 	}
345960cefed4SJohannes Weiner 
3460e716f2ebSMel Gorman 	/*
3461e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3462e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3463e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3464e716f2ebSMel Gorman 	 */
3465e716f2ebSMel Gorman 	if (mark == -1)
3466e716f2ebSMel Gorman 		return true;
3467e716f2ebSMel Gorman 
3468e716f2ebSMel Gorman 	return false;
3469e716f2ebSMel Gorman }
3470e716f2ebSMel Gorman 
3471631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3472631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3473631b6e08SMel Gorman {
3474631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3475631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3476631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3477631b6e08SMel Gorman }
3478631b6e08SMel Gorman 
34791741c877SMel Gorman /*
34805515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34815515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34825515061dSMel Gorman  *
34835515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34845515061dSMel Gorman  */
3485d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3486f50de2d3SMel Gorman {
34875515061dSMel Gorman 	/*
34889e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3489c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34909e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34919e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34929e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34939e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34949e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34959e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34969e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34979e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34989e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34995515061dSMel Gorman 	 */
35009e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
35019e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3502f50de2d3SMel Gorman 
3503c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3504c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3505c73322d0SJohannes Weiner 		return true;
3506c73322d0SJohannes Weiner 
3507e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3508631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3509333b0a45SShantanu Goel 		return true;
35101d82de61SMel Gorman 	}
35111d82de61SMel Gorman 
3512333b0a45SShantanu Goel 	return false;
3513f50de2d3SMel Gorman }
3514f50de2d3SMel Gorman 
35151da177e4SLinus Torvalds /*
35161d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
35171d82de61SMel Gorman  * zone that is currently unbalanced.
3518b8e83b94SMel Gorman  *
3519b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3520283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3521283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
352275485363SMel Gorman  */
35231d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3524accf6242SVlastimil Babka 			       struct scan_control *sc)
352575485363SMel Gorman {
35261d82de61SMel Gorman 	struct zone *zone;
35271d82de61SMel Gorman 	int z;
352875485363SMel Gorman 
35291d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
35301d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3531970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
35321d82de61SMel Gorman 		zone = pgdat->node_zones + z;
35336aa303deSMel Gorman 		if (!managed_zone(zone))
35341d82de61SMel Gorman 			continue;
35357c954f6dSMel Gorman 
35361d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
35377c954f6dSMel Gorman 	}
35387c954f6dSMel Gorman 
35391d82de61SMel Gorman 	/*
35401d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
35411d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
35421d82de61SMel Gorman 	 */
3543970a39a3SMel Gorman 	shrink_node(pgdat, sc);
35441d82de61SMel Gorman 
35451d82de61SMel Gorman 	/*
35461d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
35471d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
35481d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
35491d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
35501d82de61SMel Gorman 	 * can direct reclaim/compact.
35511d82de61SMel Gorman 	 */
35529861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
35531d82de61SMel Gorman 		sc->order = 0;
35541d82de61SMel Gorman 
3555b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
355675485363SMel Gorman }
355775485363SMel Gorman 
355875485363SMel Gorman /*
35591d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35601d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35611d82de61SMel Gorman  * balanced.
35621da177e4SLinus Torvalds  *
35631d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35641da177e4SLinus Torvalds  *
35651da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
356641858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35678bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
35681d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35691d82de61SMel Gorman  * balanced.
35701da177e4SLinus Torvalds  */
3571accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
35721da177e4SLinus Torvalds {
35731da177e4SLinus Torvalds 	int i;
35740608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35750608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3576eb414681SJohannes Weiner 	unsigned long pflags;
35771c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
35781c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
35791c30844dSMel Gorman 	bool boosted;
35801d82de61SMel Gorman 	struct zone *zone;
3581179e9639SAndrew Morton 	struct scan_control sc = {
3582179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3583ee814fe2SJohannes Weiner 		.order = order,
3584a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3585179e9639SAndrew Morton 	};
358693781325SOmar Sandoval 
35871732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3588eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
358993781325SOmar Sandoval 	__fs_reclaim_acquire();
359093781325SOmar Sandoval 
3591f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35921da177e4SLinus Torvalds 
35931c30844dSMel Gorman 	/*
35941c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
35951c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
35961c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
35971c30844dSMel Gorman 	 */
35981c30844dSMel Gorman 	nr_boost_reclaim = 0;
35991c30844dSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
36001c30844dSMel Gorman 		zone = pgdat->node_zones + i;
36011c30844dSMel Gorman 		if (!managed_zone(zone))
36021c30844dSMel Gorman 			continue;
36031c30844dSMel Gorman 
36041c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
36051c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
36061c30844dSMel Gorman 	}
36071c30844dSMel Gorman 	boosted = nr_boost_reclaim;
36081c30844dSMel Gorman 
36091c30844dSMel Gorman restart:
36101c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
36119e3b2f8cSKonstantin Khlebnikov 	do {
3612c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3613b8e83b94SMel Gorman 		bool raise_priority = true;
36141c30844dSMel Gorman 		bool balanced;
361593781325SOmar Sandoval 		bool ret;
3616b8e83b94SMel Gorman 
361784c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
36181da177e4SLinus Torvalds 
361986c79f6bSMel Gorman 		/*
362084c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
362184c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
362284c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
362384c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
362484c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
362584c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
362684c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
362784c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
362886c79f6bSMel Gorman 		 */
362986c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
363086c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
363186c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
36326aa303deSMel Gorman 				if (!managed_zone(zone))
363386c79f6bSMel Gorman 					continue;
363486c79f6bSMel Gorman 
3635970a39a3SMel Gorman 				sc.reclaim_idx = i;
363686c79f6bSMel Gorman 				break;
363786c79f6bSMel Gorman 			}
363886c79f6bSMel Gorman 		}
363986c79f6bSMel Gorman 
364086c79f6bSMel Gorman 		/*
36411c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
36421c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
36431c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
36441c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
36451c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
364686c79f6bSMel Gorman 		 */
36471c30844dSMel Gorman 		balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
36481c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
36491c30844dSMel Gorman 			nr_boost_reclaim = 0;
36501c30844dSMel Gorman 			goto restart;
36511c30844dSMel Gorman 		}
36521c30844dSMel Gorman 
36531c30844dSMel Gorman 		/*
36541c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
36551c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
36561c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
36571c30844dSMel Gorman 		 */
36581c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
36591da177e4SLinus Torvalds 			goto out;
3660e1dbeda6SAndrew Morton 
36611c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
36621c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
36631c30844dSMel Gorman 			raise_priority = false;
36641c30844dSMel Gorman 
36651c30844dSMel Gorman 		/*
36661c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
36671c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
36681c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
36691c30844dSMel Gorman 		 * reclaim will be aborted.
36701c30844dSMel Gorman 		 */
36711c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
36721c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
36731c30844dSMel Gorman 
36741da177e4SLinus Torvalds 		/*
36751d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
36761d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
36771d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
36781d82de61SMel Gorman 		 * about consistent aging.
36791d82de61SMel Gorman 		 */
3680ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
36811d82de61SMel Gorman 
36821d82de61SMel Gorman 		/*
3683b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3684b7ea3c41SMel Gorman 		 * even in laptop mode.
3685b7ea3c41SMel Gorman 		 */
3686047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3687b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3688b7ea3c41SMel Gorman 
36891d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
36901da177e4SLinus Torvalds 		sc.nr_scanned = 0;
36910608f43dSAndrew Morton 		nr_soft_scanned = 0;
3692ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
36931d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
36940608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
36950608f43dSAndrew Morton 
369632a4330dSRik van Riel 		/*
36971d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
36981d82de61SMel Gorman 		 * enough pages are already being scanned that that high
36991d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
370032a4330dSRik van Riel 		 */
3701970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3702b8e83b94SMel Gorman 			raise_priority = false;
3703d7868daeSMel Gorman 
37045515061dSMel Gorman 		/*
37055515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
37065515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
37075515061dSMel Gorman 		 * able to safely make forward progress. Wake them
37085515061dSMel Gorman 		 */
37095515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3710c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3711cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
37125515061dSMel Gorman 
3713b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
371493781325SOmar Sandoval 		__fs_reclaim_release();
371593781325SOmar Sandoval 		ret = try_to_freeze();
371693781325SOmar Sandoval 		__fs_reclaim_acquire();
371793781325SOmar Sandoval 		if (ret || kthread_should_stop())
3718b8e83b94SMel Gorman 			break;
3719b8e83b94SMel Gorman 
3720b8e83b94SMel Gorman 		/*
3721b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3722b8e83b94SMel Gorman 		 * progress in reclaiming pages
3723b8e83b94SMel Gorman 		 */
3724c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
37251c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
37261c30844dSMel Gorman 
37271c30844dSMel Gorman 		/*
37281c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
37291c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
37301c30844dSMel Gorman 		 * extreme circumstances.
37311c30844dSMel Gorman 		 */
37321c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
37331c30844dSMel Gorman 			break;
37341c30844dSMel Gorman 
3735c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3736b8e83b94SMel Gorman 			sc.priority--;
37371d82de61SMel Gorman 	} while (sc.priority >= 1);
37381da177e4SLinus Torvalds 
3739c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3740c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3741c73322d0SJohannes Weiner 
3742b8e83b94SMel Gorman out:
37431c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
37441c30844dSMel Gorman 	if (boosted) {
37451c30844dSMel Gorman 		unsigned long flags;
37461c30844dSMel Gorman 
37471c30844dSMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
37481c30844dSMel Gorman 			if (!zone_boosts[i])
37491c30844dSMel Gorman 				continue;
37501c30844dSMel Gorman 
37511c30844dSMel Gorman 			/* Increments are under the zone lock */
37521c30844dSMel Gorman 			zone = pgdat->node_zones + i;
37531c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
37541c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
37551c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
37561c30844dSMel Gorman 		}
37571c30844dSMel Gorman 
37581c30844dSMel Gorman 		/*
37591c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
37601c30844dSMel Gorman 		 * pageblocks.
37611c30844dSMel Gorman 		 */
37621c30844dSMel Gorman 		wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
37631c30844dSMel Gorman 	}
37641c30844dSMel Gorman 
37652a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
376693781325SOmar Sandoval 	__fs_reclaim_release();
3767eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
37681732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3769e5ca8071SYafang Shao 
37700abdee2bSMel Gorman 	/*
37711d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
37721d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
37731d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
37741d82de61SMel Gorman 	 * remain at the higher level.
37750abdee2bSMel Gorman 	 */
37761d82de61SMel Gorman 	return sc.order;
37771da177e4SLinus Torvalds }
37781da177e4SLinus Torvalds 
3779e716f2ebSMel Gorman /*
3780dffcac2cSShakeel Butt  * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3781dffcac2cSShakeel Butt  * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3782dffcac2cSShakeel Butt  * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3783dffcac2cSShakeel Butt  * after previous reclaim attempt (node is still unbalanced). In that case
3784dffcac2cSShakeel Butt  * return the zone index of the previous kswapd reclaim cycle.
3785e716f2ebSMel Gorman  */
3786e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3787dffcac2cSShakeel Butt 					   enum zone_type prev_classzone_idx)
3788e716f2ebSMel Gorman {
3789e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3790dffcac2cSShakeel Butt 		return prev_classzone_idx;
3791dffcac2cSShakeel Butt 	return pgdat->kswapd_classzone_idx;
3792e716f2ebSMel Gorman }
3793e716f2ebSMel Gorman 
379438087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
379538087d9bSMel Gorman 				unsigned int classzone_idx)
3796f0bc0a60SKOSAKI Motohiro {
3797f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3798f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3799f0bc0a60SKOSAKI Motohiro 
3800f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3801f0bc0a60SKOSAKI Motohiro 		return;
3802f0bc0a60SKOSAKI Motohiro 
3803f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3804f0bc0a60SKOSAKI Motohiro 
3805333b0a45SShantanu Goel 	/*
3806333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3807333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3808333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3809333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3810333b0a45SShantanu Goel 	 * succeed.
3811333b0a45SShantanu Goel 	 */
3812d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3813fd901c95SVlastimil Babka 		/*
3814fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3815fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3816fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3817fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3818fd901c95SVlastimil Babka 		 */
3819fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3820fd901c95SVlastimil Babka 
3821fd901c95SVlastimil Babka 		/*
3822fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3823fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3824fd901c95SVlastimil Babka 		 */
382538087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3826fd901c95SVlastimil Babka 
3827f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
382838087d9bSMel Gorman 
382938087d9bSMel Gorman 		/*
383038087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
383138087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
383238087d9bSMel Gorman 		 * the previous request that slept prematurely.
383338087d9bSMel Gorman 		 */
383438087d9bSMel Gorman 		if (remaining) {
3835e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
383638087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
383738087d9bSMel Gorman 		}
383838087d9bSMel Gorman 
3839f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3840f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3841f0bc0a60SKOSAKI Motohiro 	}
3842f0bc0a60SKOSAKI Motohiro 
3843f0bc0a60SKOSAKI Motohiro 	/*
3844f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3845f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3846f0bc0a60SKOSAKI Motohiro 	 */
3847d9f21d42SMel Gorman 	if (!remaining &&
3848d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3849f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3850f0bc0a60SKOSAKI Motohiro 
3851f0bc0a60SKOSAKI Motohiro 		/*
3852f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3853f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3854f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3855f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3856f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3857f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3858f0bc0a60SKOSAKI Motohiro 		 */
3859f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
38601c7e7f6cSAaditya Kumar 
38611c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3862f0bc0a60SKOSAKI Motohiro 			schedule();
38631c7e7f6cSAaditya Kumar 
3864f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3865f0bc0a60SKOSAKI Motohiro 	} else {
3866f0bc0a60SKOSAKI Motohiro 		if (remaining)
3867f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3868f0bc0a60SKOSAKI Motohiro 		else
3869f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3870f0bc0a60SKOSAKI Motohiro 	}
3871f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3872f0bc0a60SKOSAKI Motohiro }
3873f0bc0a60SKOSAKI Motohiro 
38741da177e4SLinus Torvalds /*
38751da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
38761da177e4SLinus Torvalds  * from the init process.
38771da177e4SLinus Torvalds  *
38781da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
38791da177e4SLinus Torvalds  * free memory available even if there is no other activity
38801da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
38811da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
38821da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
38831da177e4SLinus Torvalds  *
38841da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
38851da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
38861da177e4SLinus Torvalds  */
38871da177e4SLinus Torvalds static int kswapd(void *p)
38881da177e4SLinus Torvalds {
3889e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3890e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
38911da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
38921da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3893a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
38941da177e4SLinus Torvalds 
3895174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3896c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
38971da177e4SLinus Torvalds 
38981da177e4SLinus Torvalds 	/*
38991da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
39001da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
39011da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
39021da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
39031da177e4SLinus Torvalds 	 *
39041da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
39051da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
39061da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
39071da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
39081da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
39091da177e4SLinus Torvalds 	 */
3910930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
391183144186SRafael J. Wysocki 	set_freezable();
39121da177e4SLinus Torvalds 
3913e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3914e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
39151da177e4SLinus Torvalds 	for ( ; ; ) {
39166f6313d4SJeff Liu 		bool ret;
39173e1d1d28SChristoph Lameter 
3918e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3919e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3920e716f2ebSMel Gorman 
392138087d9bSMel Gorman kswapd_try_sleep:
392238087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
392338087d9bSMel Gorman 					classzone_idx);
3924215ddd66SMel Gorman 
392538087d9bSMel Gorman 		/* Read the new order and classzone_idx */
392638087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3927dffcac2cSShakeel Butt 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
392838087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3929e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
39301da177e4SLinus Torvalds 
39318fe23e05SDavid Rientjes 		ret = try_to_freeze();
39328fe23e05SDavid Rientjes 		if (kthread_should_stop())
39338fe23e05SDavid Rientjes 			break;
39348fe23e05SDavid Rientjes 
39358fe23e05SDavid Rientjes 		/*
39368fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
39378fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3938b1296cc4SRafael J. Wysocki 		 */
393938087d9bSMel Gorman 		if (ret)
394038087d9bSMel Gorman 			continue;
39411d82de61SMel Gorman 
394238087d9bSMel Gorman 		/*
394338087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
394438087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
394538087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
394638087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
394738087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
394838087d9bSMel Gorman 		 * request (alloc_order).
394938087d9bSMel Gorman 		 */
3950e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3951e5146b12SMel Gorman 						alloc_order);
395238087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
395338087d9bSMel Gorman 		if (reclaim_order < alloc_order)
395438087d9bSMel Gorman 			goto kswapd_try_sleep;
395533906bc5SMel Gorman 	}
3956b0a8cc58STakamori Yamaguchi 
395771abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
395871abdc15SJohannes Weiner 
39591da177e4SLinus Torvalds 	return 0;
39601da177e4SLinus Torvalds }
39611da177e4SLinus Torvalds 
39621da177e4SLinus Torvalds /*
39635ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
39645ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
39655ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
39665ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
39675ecd9d40SDavid Rientjes  * needed.
39681da177e4SLinus Torvalds  */
39695ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
39705ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
39711da177e4SLinus Torvalds {
39721da177e4SLinus Torvalds 	pg_data_t *pgdat;
39731da177e4SLinus Torvalds 
39746aa303deSMel Gorman 	if (!managed_zone(zone))
39751da177e4SLinus Torvalds 		return;
39761da177e4SLinus Torvalds 
39775ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
39781da177e4SLinus Torvalds 		return;
397988f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3980dffcac2cSShakeel Butt 
3981dffcac2cSShakeel Butt 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3982dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = classzone_idx;
3983dffcac2cSShakeel Butt 	else
3984dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3985e716f2ebSMel Gorman 						  classzone_idx);
398638087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
39878d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
39881da177e4SLinus Torvalds 		return;
3989e1a55637SMel Gorman 
39905ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
39915ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
39921c30844dSMel Gorman 	    (pgdat_balanced(pgdat, order, classzone_idx) &&
39931c30844dSMel Gorman 	     !pgdat_watermark_boosted(pgdat, classzone_idx))) {
39945ecd9d40SDavid Rientjes 		/*
39955ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
39965ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
39975ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
39985ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
39995ecd9d40SDavid Rientjes 		 * ratelimit its work.
40005ecd9d40SDavid Rientjes 		 */
40015ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
40025ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
4003c73322d0SJohannes Weiner 		return;
40045ecd9d40SDavid Rientjes 	}
4005c73322d0SJohannes Weiner 
40065ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
40075ecd9d40SDavid Rientjes 				      gfp_flags);
40088d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
40091da177e4SLinus Torvalds }
40101da177e4SLinus Torvalds 
4011c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
40121da177e4SLinus Torvalds /*
40137b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4014d6277db4SRafael J. Wysocki  * freed pages.
4015d6277db4SRafael J. Wysocki  *
4016d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4017d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4018d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
40191da177e4SLinus Torvalds  */
40207b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
40211da177e4SLinus Torvalds {
4022d6277db4SRafael J. Wysocki 	struct scan_control sc = {
40237b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4024ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4025b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
40269e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4027ee814fe2SJohannes Weiner 		.may_writepage = 1,
4028ee814fe2SJohannes Weiner 		.may_unmap = 1,
4029ee814fe2SJohannes Weiner 		.may_swap = 1,
4030ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
40311da177e4SLinus Torvalds 	};
40327b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
40337b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4034499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
40351da177e4SLinus Torvalds 
4036d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
403793781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
40381732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4039d6277db4SRafael J. Wysocki 
40403115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4041d6277db4SRafael J. Wysocki 
40421732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4043499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
404493781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4045d6277db4SRafael J. Wysocki 
40467b51755cSKOSAKI Motohiro 	return nr_reclaimed;
40471da177e4SLinus Torvalds }
4048c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
40491da177e4SLinus Torvalds 
40501da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
40511da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
40521da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
40531da177e4SLinus Torvalds    restore their cpu bindings. */
4054517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
40551da177e4SLinus Torvalds {
405658c0a4a7SYasunori Goto 	int nid;
40571da177e4SLinus Torvalds 
405848fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
4059c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
4060a70f7302SRusty Russell 		const struct cpumask *mask;
4061a70f7302SRusty Russell 
4062a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
4063c5f59f08SMike Travis 
40643e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
40651da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
4066c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
40671da177e4SLinus Torvalds 	}
4068517bbed9SSebastian Andrzej Siewior 	return 0;
40691da177e4SLinus Torvalds }
40701da177e4SLinus Torvalds 
40713218ae14SYasunori Goto /*
40723218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
40733218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
40743218ae14SYasunori Goto  */
40753218ae14SYasunori Goto int kswapd_run(int nid)
40763218ae14SYasunori Goto {
40773218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
40783218ae14SYasunori Goto 	int ret = 0;
40793218ae14SYasunori Goto 
40803218ae14SYasunori Goto 	if (pgdat->kswapd)
40813218ae14SYasunori Goto 		return 0;
40823218ae14SYasunori Goto 
40833218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
40843218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
40853218ae14SYasunori Goto 		/* failure at boot is fatal */
4086c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4087d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4088d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4089d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
40903218ae14SYasunori Goto 	}
40913218ae14SYasunori Goto 	return ret;
40923218ae14SYasunori Goto }
40933218ae14SYasunori Goto 
40948fe23e05SDavid Rientjes /*
4095d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4096bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
40978fe23e05SDavid Rientjes  */
40988fe23e05SDavid Rientjes void kswapd_stop(int nid)
40998fe23e05SDavid Rientjes {
41008fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
41018fe23e05SDavid Rientjes 
4102d8adde17SJiang Liu 	if (kswapd) {
41038fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4104d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4105d8adde17SJiang Liu 	}
41068fe23e05SDavid Rientjes }
41078fe23e05SDavid Rientjes 
41081da177e4SLinus Torvalds static int __init kswapd_init(void)
41091da177e4SLinus Torvalds {
4110517bbed9SSebastian Andrzej Siewior 	int nid, ret;
411169e05944SAndrew Morton 
41121da177e4SLinus Torvalds 	swap_setup();
411348fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
41143218ae14SYasunori Goto  		kswapd_run(nid);
4115517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4116517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
4117517bbed9SSebastian Andrzej Siewior 					NULL);
4118517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
41191da177e4SLinus Torvalds 	return 0;
41201da177e4SLinus Torvalds }
41211da177e4SLinus Torvalds 
41221da177e4SLinus Torvalds module_init(kswapd_init)
41239eeff239SChristoph Lameter 
41249eeff239SChristoph Lameter #ifdef CONFIG_NUMA
41259eeff239SChristoph Lameter /*
4126a5f5f91dSMel Gorman  * Node reclaim mode
41279eeff239SChristoph Lameter  *
4128a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
41299eeff239SChristoph Lameter  * the watermarks.
41309eeff239SChristoph Lameter  */
4131a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
41329eeff239SChristoph Lameter 
41331b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
41347d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
41351b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
413695bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
41371b2ffb78SChristoph Lameter 
41389eeff239SChristoph Lameter /*
4139a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4140a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4141a92f7126SChristoph Lameter  * a zone.
4142a92f7126SChristoph Lameter  */
4143a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4144a92f7126SChristoph Lameter 
41459eeff239SChristoph Lameter /*
4146a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
41479614634fSChristoph Lameter  * occur.
41489614634fSChristoph Lameter  */
41499614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
41509614634fSChristoph Lameter 
41519614634fSChristoph Lameter /*
41520ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
41530ff38490SChristoph Lameter  * slab reclaim needs to occur.
41540ff38490SChristoph Lameter  */
41550ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
41560ff38490SChristoph Lameter 
415711fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
415890afa5deSMel Gorman {
415911fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
416011fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
416111fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
416290afa5deSMel Gorman 
416390afa5deSMel Gorman 	/*
416490afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
416590afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
416690afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
416790afa5deSMel Gorman 	 */
416890afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
416990afa5deSMel Gorman }
417090afa5deSMel Gorman 
417190afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4172a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
417390afa5deSMel Gorman {
4174d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4175d031a157SAlexandru Moise 	unsigned long delta = 0;
417690afa5deSMel Gorman 
417790afa5deSMel Gorman 	/*
417895bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
417990afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
418011fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
418190afa5deSMel Gorman 	 * a better estimate
418290afa5deSMel Gorman 	 */
4183a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4184a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
418590afa5deSMel Gorman 	else
4186a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
418790afa5deSMel Gorman 
418890afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4189a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4190a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
419190afa5deSMel Gorman 
419290afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
419390afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
419490afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
419590afa5deSMel Gorman 
419690afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
419790afa5deSMel Gorman }
419890afa5deSMel Gorman 
41990ff38490SChristoph Lameter /*
4200a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
42019eeff239SChristoph Lameter  */
4202a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
42039eeff239SChristoph Lameter {
42047fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
420569e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
42069eeff239SChristoph Lameter 	struct task_struct *p = current;
4207499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4208179e9639SAndrew Morton 	struct scan_control sc = {
420962b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4210f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4211bd2f6199SJohannes Weiner 		.order = order,
4212a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4213a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4214a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4215ee814fe2SJohannes Weiner 		.may_swap = 1,
4216f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4217179e9639SAndrew Morton 	};
42189eeff239SChristoph Lameter 
4219132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4220132bb8cfSYafang Shao 					   sc.gfp_mask);
4221132bb8cfSYafang Shao 
42229eeff239SChristoph Lameter 	cond_resched();
422393781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4224d4f7796eSChristoph Lameter 	/*
422595bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4226d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
422795bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4228d4f7796eSChristoph Lameter 	 */
4229499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4230499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
42311732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4232c84db23cSChristoph Lameter 
4233a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4234a92f7126SChristoph Lameter 		/*
4235894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
42360ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4237a92f7126SChristoph Lameter 		 */
4238a92f7126SChristoph Lameter 		do {
4239970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
42409e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
42410ff38490SChristoph Lameter 	}
4242a92f7126SChristoph Lameter 
42431732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4244499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4245499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
424693781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4247132bb8cfSYafang Shao 
4248132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4249132bb8cfSYafang Shao 
4250a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
42519eeff239SChristoph Lameter }
4252179e9639SAndrew Morton 
4253a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4254179e9639SAndrew Morton {
4255d773ed6bSDavid Rientjes 	int ret;
4256179e9639SAndrew Morton 
4257179e9639SAndrew Morton 	/*
4258a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
42590ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
426034aa1330SChristoph Lameter 	 *
42619614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
42629614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4263a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4264a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
42659614634fSChristoph Lameter 	 * unmapped file backed pages.
4266179e9639SAndrew Morton 	 */
4267a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4268385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4269a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4270179e9639SAndrew Morton 
4271179e9639SAndrew Morton 	/*
4272d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4273179e9639SAndrew Morton 	 */
4274d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4275a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4276179e9639SAndrew Morton 
4277179e9639SAndrew Morton 	/*
4278a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4279179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4280179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4281179e9639SAndrew Morton 	 * as wide as possible.
4282179e9639SAndrew Morton 	 */
4283a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4284a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4285d773ed6bSDavid Rientjes 
4286a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4287a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4288fa5e084eSMel Gorman 
4289a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4290a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4291d773ed6bSDavid Rientjes 
429224cf7251SMel Gorman 	if (!ret)
429324cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
429424cf7251SMel Gorman 
4295d773ed6bSDavid Rientjes 	return ret;
4296179e9639SAndrew Morton }
42979eeff239SChristoph Lameter #endif
4298894bc310SLee Schermerhorn 
4299894bc310SLee Schermerhorn /*
4300894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4301894bc310SLee Schermerhorn  * @page: the page to test
4302894bc310SLee Schermerhorn  *
4303894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
430439b5f29aSHugh Dickins  * lists vs unevictable list.
4305894bc310SLee Schermerhorn  *
4306894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4307ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4308b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4309ba9ddf49SLee Schermerhorn  *
4310894bc310SLee Schermerhorn  */
431139b5f29aSHugh Dickins int page_evictable(struct page *page)
4312894bc310SLee Schermerhorn {
4313e92bb4ddSHuang Ying 	int ret;
4314e92bb4ddSHuang Ying 
4315e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4316e92bb4ddSHuang Ying 	rcu_read_lock();
4317e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4318e92bb4ddSHuang Ying 	rcu_read_unlock();
4319e92bb4ddSHuang Ying 	return ret;
4320894bc310SLee Schermerhorn }
432189e004eaSLee Schermerhorn 
432289e004eaSLee Schermerhorn /**
432364e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
432464e3d12fSKuo-Hsin Yang  * appropriate zone lru list
432564e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
432689e004eaSLee Schermerhorn  *
432764e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
432864e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
432964e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
433089e004eaSLee Schermerhorn  */
433164e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
433289e004eaSLee Schermerhorn {
4333925b7673SJohannes Weiner 	struct lruvec *lruvec;
4334785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
433524513264SHugh Dickins 	int pgscanned = 0;
433624513264SHugh Dickins 	int pgrescued = 0;
433789e004eaSLee Schermerhorn 	int i;
433889e004eaSLee Schermerhorn 
433964e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
434064e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4341785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
434289e004eaSLee Schermerhorn 
434324513264SHugh Dickins 		pgscanned++;
4344785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4345785b99feSMel Gorman 			if (pgdat)
4346785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4347785b99feSMel Gorman 			pgdat = pagepgdat;
4348785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
434989e004eaSLee Schermerhorn 		}
4350785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
435189e004eaSLee Schermerhorn 
435224513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
435324513264SHugh Dickins 			continue;
435489e004eaSLee Schermerhorn 
435539b5f29aSHugh Dickins 		if (page_evictable(page)) {
435624513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
435724513264SHugh Dickins 
4358309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
435924513264SHugh Dickins 			ClearPageUnevictable(page);
4360fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4361fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
436224513264SHugh Dickins 			pgrescued++;
436389e004eaSLee Schermerhorn 		}
436489e004eaSLee Schermerhorn 	}
436524513264SHugh Dickins 
4366785b99feSMel Gorman 	if (pgdat) {
436724513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
436824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4369785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
437024513264SHugh Dickins 	}
437185046579SHugh Dickins }
437264e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4373