xref: /openbmc/linux/mm/vmscan.c (revision d2af339706be318dadcbe14c8935426ff401d7b1)
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 
242b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
24389b5fae5SJohannes Weiner {
244b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
24589b5fae5SJohannes Weiner }
24697c9341fSTejun Heo 
24797c9341fSTejun Heo /**
248b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
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  */
260b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
26197c9341fSTejun Heo {
262b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
26397c9341fSTejun Heo 		return true;
26497c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26569234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26697c9341fSTejun Heo 		return true;
26797c9341fSTejun Heo #endif
26897c9341fSTejun Heo 	return false;
26997c9341fSTejun Heo }
270e3c1ac58SAndrey Ryabinin 
271e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
272e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
273e3c1ac58SAndrey Ryabinin 				bool congested)
274e3c1ac58SAndrey Ryabinin {
275e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
276e3c1ac58SAndrey Ryabinin 
277e3c1ac58SAndrey Ryabinin 	if (!memcg)
278e3c1ac58SAndrey Ryabinin 		return;
279e3c1ac58SAndrey Ryabinin 
280e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
281e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
282e3c1ac58SAndrey Ryabinin }
283e3c1ac58SAndrey Ryabinin 
284e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
285e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
286e3c1ac58SAndrey Ryabinin {
287e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
288e3c1ac58SAndrey Ryabinin 
289e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
290e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
291e3c1ac58SAndrey Ryabinin 
292e3c1ac58SAndrey Ryabinin }
29391a45470SKAMEZAWA Hiroyuki #else
2940a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
2950a432dcbSYang Shi {
2960a432dcbSYang Shi 	return 0;
2970a432dcbSYang Shi }
2980a432dcbSYang Shi 
2990a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
3000a432dcbSYang Shi {
3010a432dcbSYang Shi }
3020a432dcbSYang Shi 
303b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
30489b5fae5SJohannes Weiner {
305b5ead35eSJohannes Weiner 	return false;
30689b5fae5SJohannes Weiner }
30797c9341fSTejun Heo 
308b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
30997c9341fSTejun Heo {
31097c9341fSTejun Heo 	return true;
31197c9341fSTejun Heo }
312e3c1ac58SAndrey Ryabinin 
313e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
314e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
315e3c1ac58SAndrey Ryabinin {
316e3c1ac58SAndrey Ryabinin }
317e3c1ac58SAndrey Ryabinin 
318e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
319e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
320e3c1ac58SAndrey Ryabinin {
321e3c1ac58SAndrey Ryabinin 	return false;
322e3c1ac58SAndrey Ryabinin 
323e3c1ac58SAndrey Ryabinin }
32491a45470SKAMEZAWA Hiroyuki #endif
32591a45470SKAMEZAWA Hiroyuki 
3265a1c84b4SMel Gorman /*
3275a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3285a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3295a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3305a1c84b4SMel Gorman  */
3315a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3325a1c84b4SMel Gorman {
3335a1c84b4SMel Gorman 	unsigned long nr;
3345a1c84b4SMel Gorman 
3355a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3365a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3375a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3385a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3395a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3405a1c84b4SMel Gorman 
3415a1c84b4SMel Gorman 	return nr;
3425a1c84b4SMel Gorman }
3435a1c84b4SMel Gorman 
344fd538803SMichal Hocko /**
345fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
346fd538803SMichal Hocko  * @lruvec: lru vector
347fd538803SMichal Hocko  * @lru: lru to use
348fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
349fd538803SMichal Hocko  */
350fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
351c9f299d9SKOSAKI Motohiro {
352de3b0150SJohannes Weiner 	unsigned long size = 0;
353fd538803SMichal Hocko 	int zid;
354a3d8e054SKOSAKI Motohiro 
355de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
356fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
357fd538803SMichal Hocko 
358fd538803SMichal Hocko 		if (!managed_zone(zone))
359fd538803SMichal Hocko 			continue;
360fd538803SMichal Hocko 
361fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
362de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
363fd538803SMichal Hocko 		else
364de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
365c9f299d9SKOSAKI Motohiro 	}
366de3b0150SJohannes Weiner 	return size;
367b4536f0cSMichal Hocko }
368b4536f0cSMichal Hocko 
3691da177e4SLinus Torvalds /*
3701d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3711da177e4SLinus Torvalds  */
3728e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3731da177e4SLinus Torvalds {
374b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3751d3d4437SGlauber Costa 
3761d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3771d3d4437SGlauber Costa 		size *= nr_node_ids;
3781d3d4437SGlauber Costa 
3791d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3801d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3811d3d4437SGlauber Costa 		return -ENOMEM;
382b4c2b231SKirill Tkhai 
383b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
384b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
385b4c2b231SKirill Tkhai 			goto free_deferred;
386b4c2b231SKirill Tkhai 	}
387b4c2b231SKirill Tkhai 
3888e04944fSTetsuo Handa 	return 0;
389b4c2b231SKirill Tkhai 
390b4c2b231SKirill Tkhai free_deferred:
391b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
392b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
393b4c2b231SKirill Tkhai 	return -ENOMEM;
3948e04944fSTetsuo Handa }
3951d3d4437SGlauber Costa 
3968e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3978e04944fSTetsuo Handa {
398b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
399b4c2b231SKirill Tkhai 		return;
400b4c2b231SKirill Tkhai 
401b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
402b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
403b4c2b231SKirill Tkhai 
4048e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4058e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4068e04944fSTetsuo Handa }
4078e04944fSTetsuo Handa 
4088e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4098e04944fSTetsuo Handa {
4101da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4111da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
4127e010df5SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
4138df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
4147e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
4157e010df5SKirill Tkhai #endif
4161da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
4178e04944fSTetsuo Handa }
4188e04944fSTetsuo Handa 
4198e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
4208e04944fSTetsuo Handa {
4218e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4228e04944fSTetsuo Handa 
4238e04944fSTetsuo Handa 	if (err)
4248e04944fSTetsuo Handa 		return err;
4258e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4261d3d4437SGlauber Costa 	return 0;
4271da177e4SLinus Torvalds }
4288e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4291da177e4SLinus Torvalds 
4301da177e4SLinus Torvalds /*
4311da177e4SLinus Torvalds  * Remove one
4321da177e4SLinus Torvalds  */
4338e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4341da177e4SLinus Torvalds {
435bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
436bb422a73STetsuo Handa 		return;
437b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
438b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4391da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4401da177e4SLinus Torvalds 	list_del(&shrinker->list);
4411da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
442ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
443bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4441da177e4SLinus Torvalds }
4458e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4461da177e4SLinus Torvalds 
4471da177e4SLinus Torvalds #define SHRINK_BATCH 128
4481d3d4437SGlauber Costa 
449cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4509092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4511da177e4SLinus Torvalds {
45224f7c6b9SDave Chinner 	unsigned long freed = 0;
4531da177e4SLinus Torvalds 	unsigned long long delta;
454635697c6SKonstantin Khlebnikov 	long total_scan;
455d5bc5fd3SVladimir Davydov 	long freeable;
456acf92b48SDave Chinner 	long nr;
457acf92b48SDave Chinner 	long new_nr;
4581d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
459e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
460e9299f50SDave Chinner 					  : SHRINK_BATCH;
4615f33a080SShaohua Li 	long scanned = 0, next_deferred;
4621da177e4SLinus Torvalds 
463ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
464ac7fb3adSKirill Tkhai 		nid = 0;
465ac7fb3adSKirill Tkhai 
466d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4679b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4689b996468SKirill Tkhai 		return freeable;
469635697c6SKonstantin Khlebnikov 
470acf92b48SDave Chinner 	/*
471acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
472acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
473acf92b48SDave Chinner 	 * don't also do this scanning work.
474acf92b48SDave Chinner 	 */
4751d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
476acf92b48SDave Chinner 
477acf92b48SDave Chinner 	total_scan = nr;
4784b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4799092c71bSJosef Bacik 		delta = freeable >> priority;
4809092c71bSJosef Bacik 		delta *= 4;
4819092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4824b85afbdSJohannes Weiner 	} else {
4834b85afbdSJohannes Weiner 		/*
4844b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4854b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4864b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
4874b85afbdSJohannes Weiner 		 */
4884b85afbdSJohannes Weiner 		delta = freeable / 2;
4894b85afbdSJohannes Weiner 	}
490172b06c3SRoman Gushchin 
491acf92b48SDave Chinner 	total_scan += delta;
492acf92b48SDave Chinner 	if (total_scan < 0) {
493d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
494a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
495d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4965f33a080SShaohua Li 		next_deferred = nr;
4975f33a080SShaohua Li 	} else
4985f33a080SShaohua Li 		next_deferred = total_scan;
499ea164d73SAndrea Arcangeli 
500ea164d73SAndrea Arcangeli 	/*
5013567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5023567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5033567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5043567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5053567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
506d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5073567b59aSDave Chinner 	 * memory.
5083567b59aSDave Chinner 	 *
5093567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
5103567b59aSDave Chinner 	 * a large delta change is calculated directly.
5113567b59aSDave Chinner 	 */
512d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
513d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
5143567b59aSDave Chinner 
5153567b59aSDave Chinner 	/*
516ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
517ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
518ea164d73SAndrea Arcangeli 	 * freeable entries.
519ea164d73SAndrea Arcangeli 	 */
520d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
521d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5221da177e4SLinus Torvalds 
52324f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5249092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
52509576073SDave Chinner 
5260b1fb40aSVladimir Davydov 	/*
5270b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5280b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5290b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5300b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5310b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5320b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5330b1fb40aSVladimir Davydov 	 * batch_size.
5340b1fb40aSVladimir Davydov 	 *
5350b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5360b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
537d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5380b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5390b1fb40aSVladimir Davydov 	 * possible.
5400b1fb40aSVladimir Davydov 	 */
5410b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
542d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
54324f7c6b9SDave Chinner 		unsigned long ret;
5440b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5451da177e4SLinus Torvalds 
5460b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
547d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
54824f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
54924f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5501da177e4SLinus Torvalds 			break;
55124f7c6b9SDave Chinner 		freed += ret;
55224f7c6b9SDave Chinner 
553d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
554d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
555d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5561da177e4SLinus Torvalds 
5571da177e4SLinus Torvalds 		cond_resched();
5581da177e4SLinus Torvalds 	}
5591da177e4SLinus Torvalds 
5605f33a080SShaohua Li 	if (next_deferred >= scanned)
5615f33a080SShaohua Li 		next_deferred -= scanned;
5625f33a080SShaohua Li 	else
5635f33a080SShaohua Li 		next_deferred = 0;
564acf92b48SDave Chinner 	/*
565acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
566acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
567acf92b48SDave Chinner 	 * scan, there is no need to do an update.
568acf92b48SDave Chinner 	 */
5695f33a080SShaohua Li 	if (next_deferred > 0)
5705f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5711d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
57283aeeadaSKonstantin Khlebnikov 	else
5731d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
574acf92b48SDave Chinner 
575df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5761d3d4437SGlauber Costa 	return freed;
5771d3d4437SGlauber Costa }
5781d3d4437SGlauber Costa 
5790a432dcbSYang Shi #ifdef CONFIG_MEMCG
580b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
581b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
582b0dedc49SKirill Tkhai {
583b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
584b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
585b8e57efaSKirill Tkhai 	int i;
586b0dedc49SKirill Tkhai 
5870a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
588b0dedc49SKirill Tkhai 		return 0;
589b0dedc49SKirill Tkhai 
590b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
591b0dedc49SKirill Tkhai 		return 0;
592b0dedc49SKirill Tkhai 
593b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
594b0dedc49SKirill Tkhai 					true);
595b0dedc49SKirill Tkhai 	if (unlikely(!map))
596b0dedc49SKirill Tkhai 		goto unlock;
597b0dedc49SKirill Tkhai 
598b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
599b0dedc49SKirill Tkhai 		struct shrink_control sc = {
600b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
601b0dedc49SKirill Tkhai 			.nid = nid,
602b0dedc49SKirill Tkhai 			.memcg = memcg,
603b0dedc49SKirill Tkhai 		};
604b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
605b0dedc49SKirill Tkhai 
606b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6077e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6087e010df5SKirill Tkhai 			if (!shrinker)
609b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
610b0dedc49SKirill Tkhai 			continue;
611b0dedc49SKirill Tkhai 		}
612b0dedc49SKirill Tkhai 
6130a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
6140a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
6150a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
6160a432dcbSYang Shi 			continue;
6170a432dcbSYang Shi 
618b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
619f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
620f90280d6SKirill Tkhai 			clear_bit(i, map->map);
621f90280d6SKirill Tkhai 			/*
622f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
623f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
624f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
625f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
626f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
627f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
628f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
629f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
630f90280d6SKirill Tkhai 			 *
631f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
632f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
633f90280d6SKirill Tkhai 			 *   <MB>               <MB>
634f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
635f90280d6SKirill Tkhai 			 */
636f90280d6SKirill Tkhai 			smp_mb__after_atomic();
637f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6389b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6399b996468SKirill Tkhai 				ret = 0;
640f90280d6SKirill Tkhai 			else
641f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
642f90280d6SKirill Tkhai 		}
643b0dedc49SKirill Tkhai 		freed += ret;
644b0dedc49SKirill Tkhai 
645b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
646b0dedc49SKirill Tkhai 			freed = freed ? : 1;
647b0dedc49SKirill Tkhai 			break;
648b0dedc49SKirill Tkhai 		}
649b0dedc49SKirill Tkhai 	}
650b0dedc49SKirill Tkhai unlock:
651b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
652b0dedc49SKirill Tkhai 	return freed;
653b0dedc49SKirill Tkhai }
6540a432dcbSYang Shi #else /* CONFIG_MEMCG */
655b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
656b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
657b0dedc49SKirill Tkhai {
658b0dedc49SKirill Tkhai 	return 0;
659b0dedc49SKirill Tkhai }
6600a432dcbSYang Shi #endif /* CONFIG_MEMCG */
661b0dedc49SKirill Tkhai 
6626b4f7799SJohannes Weiner /**
663cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6646b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6656b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
666cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6679092c71bSJosef Bacik  * @priority: the reclaim priority
6681d3d4437SGlauber Costa  *
6696b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6701d3d4437SGlauber Costa  *
6716b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6726b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6731d3d4437SGlauber Costa  *
674aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
675aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
676cb731d6cSVladimir Davydov  *
6779092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6789092c71bSJosef Bacik  * in order to get the scan target.
6791d3d4437SGlauber Costa  *
6806b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6811d3d4437SGlauber Costa  */
682cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
683cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6849092c71bSJosef Bacik 				 int priority)
6851d3d4437SGlauber Costa {
686b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6871d3d4437SGlauber Costa 	struct shrinker *shrinker;
6881d3d4437SGlauber Costa 
689fa1e512fSYang Shi 	/*
690fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
691fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
692fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
693fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
694fa1e512fSYang Shi 	 * oom.
695fa1e512fSYang Shi 	 */
696fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
697b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
698cb731d6cSVladimir Davydov 
699e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
7001d3d4437SGlauber Costa 		goto out;
7011d3d4437SGlauber Costa 
7021d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
7036b4f7799SJohannes Weiner 		struct shrink_control sc = {
7046b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
7056b4f7799SJohannes Weiner 			.nid = nid,
706cb731d6cSVladimir Davydov 			.memcg = memcg,
7076b4f7799SJohannes Weiner 		};
7086b4f7799SJohannes Weiner 
7099b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
7109b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
7119b996468SKirill Tkhai 			ret = 0;
7129b996468SKirill Tkhai 		freed += ret;
713e496612cSMinchan Kim 		/*
714e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
715e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
716e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
717e496612cSMinchan Kim 		 */
718e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
719e496612cSMinchan Kim 			freed = freed ? : 1;
720e496612cSMinchan Kim 			break;
721e496612cSMinchan Kim 		}
722ec97097bSVladimir Davydov 	}
7231d3d4437SGlauber Costa 
7241da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
725f06590bdSMinchan Kim out:
726f06590bdSMinchan Kim 	cond_resched();
72724f7c6b9SDave Chinner 	return freed;
7281da177e4SLinus Torvalds }
7291da177e4SLinus Torvalds 
730cb731d6cSVladimir Davydov void drop_slab_node(int nid)
731cb731d6cSVladimir Davydov {
732cb731d6cSVladimir Davydov 	unsigned long freed;
733cb731d6cSVladimir Davydov 
734cb731d6cSVladimir Davydov 	do {
735cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
736cb731d6cSVladimir Davydov 
737cb731d6cSVladimir Davydov 		freed = 0;
738aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
739cb731d6cSVladimir Davydov 		do {
7409092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
741cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
742cb731d6cSVladimir Davydov 	} while (freed > 10);
743cb731d6cSVladimir Davydov }
744cb731d6cSVladimir Davydov 
745cb731d6cSVladimir Davydov void drop_slab(void)
746cb731d6cSVladimir Davydov {
747cb731d6cSVladimir Davydov 	int nid;
748cb731d6cSVladimir Davydov 
749cb731d6cSVladimir Davydov 	for_each_online_node(nid)
750cb731d6cSVladimir Davydov 		drop_slab_node(nid);
751cb731d6cSVladimir Davydov }
752cb731d6cSVladimir Davydov 
7531da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7541da177e4SLinus Torvalds {
755ceddc3a5SJohannes Weiner 	/*
756ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
75767891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
75867891fffSMatthew Wilcox 	 * heads at page->private.
759ceddc3a5SJohannes Weiner 	 */
76067891fffSMatthew Wilcox 	int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
761bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
76267891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7631da177e4SLinus Torvalds }
7641da177e4SLinus Torvalds 
765cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
7661da177e4SLinus Torvalds {
767930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7681da177e4SLinus Torvalds 		return 1;
769703c2708STejun Heo 	if (!inode_write_congested(inode))
7701da177e4SLinus Torvalds 		return 1;
771703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7721da177e4SLinus Torvalds 		return 1;
7731da177e4SLinus Torvalds 	return 0;
7741da177e4SLinus Torvalds }
7751da177e4SLinus Torvalds 
7761da177e4SLinus Torvalds /*
7771da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7781da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7791da177e4SLinus Torvalds  * fsync(), msync() or close().
7801da177e4SLinus Torvalds  *
7811da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7821da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7831da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7841da177e4SLinus Torvalds  *
7851da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7861da177e4SLinus Torvalds  * __GFP_FS.
7871da177e4SLinus Torvalds  */
7881da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7891da177e4SLinus Torvalds 				struct page *page, int error)
7901da177e4SLinus Torvalds {
7917eaceaccSJens Axboe 	lock_page(page);
7923e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7933e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7941da177e4SLinus Torvalds 	unlock_page(page);
7951da177e4SLinus Torvalds }
7961da177e4SLinus Torvalds 
79704e62a29SChristoph Lameter /* possible outcome of pageout() */
79804e62a29SChristoph Lameter typedef enum {
79904e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
80004e62a29SChristoph Lameter 	PAGE_KEEP,
80104e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
80204e62a29SChristoph Lameter 	PAGE_ACTIVATE,
80304e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
80404e62a29SChristoph Lameter 	PAGE_SUCCESS,
80504e62a29SChristoph Lameter 	/* page is clean and locked */
80604e62a29SChristoph Lameter 	PAGE_CLEAN,
80704e62a29SChristoph Lameter } pageout_t;
80804e62a29SChristoph Lameter 
8091da177e4SLinus Torvalds /*
8101742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
8111742f19fSAndrew Morton  * Calls ->writepage().
8121da177e4SLinus Torvalds  */
813cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
8141da177e4SLinus Torvalds {
8151da177e4SLinus Torvalds 	/*
8161da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
8171da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
8181da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
8191da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
8201da177e4SLinus Torvalds 	 * PagePrivate for that.
8211da177e4SLinus Torvalds 	 *
8228174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
8231da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
8241da177e4SLinus Torvalds 	 * will block.
8251da177e4SLinus Torvalds 	 *
8261da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
8271da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
8281da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
8291da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
8301da177e4SLinus Torvalds 	 */
8311da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
8321da177e4SLinus Torvalds 		return PAGE_KEEP;
8331da177e4SLinus Torvalds 	if (!mapping) {
8341da177e4SLinus Torvalds 		/*
8351da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8361da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8371da177e4SLinus Torvalds 		 */
838266cf658SDavid Howells 		if (page_has_private(page)) {
8391da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8401da177e4SLinus Torvalds 				ClearPageDirty(page);
841b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8421da177e4SLinus Torvalds 				return PAGE_CLEAN;
8431da177e4SLinus Torvalds 			}
8441da177e4SLinus Torvalds 		}
8451da177e4SLinus Torvalds 		return PAGE_KEEP;
8461da177e4SLinus Torvalds 	}
8471da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8481da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
849cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
8501da177e4SLinus Torvalds 		return PAGE_KEEP;
8511da177e4SLinus Torvalds 
8521da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8531da177e4SLinus Torvalds 		int res;
8541da177e4SLinus Torvalds 		struct writeback_control wbc = {
8551da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8561da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
857111ebb6eSOGAWA Hirofumi 			.range_start = 0,
858111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8591da177e4SLinus Torvalds 			.for_reclaim = 1,
8601da177e4SLinus Torvalds 		};
8611da177e4SLinus Torvalds 
8621da177e4SLinus Torvalds 		SetPageReclaim(page);
8631da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8641da177e4SLinus Torvalds 		if (res < 0)
8651da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
866994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8671da177e4SLinus Torvalds 			ClearPageReclaim(page);
8681da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8691da177e4SLinus Torvalds 		}
870c661b078SAndy Whitcroft 
8711da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8721da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8731da177e4SLinus Torvalds 			ClearPageReclaim(page);
8741da177e4SLinus Torvalds 		}
8753aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
876c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8771da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8781da177e4SLinus Torvalds 	}
8791da177e4SLinus Torvalds 
8801da177e4SLinus Torvalds 	return PAGE_CLEAN;
8811da177e4SLinus Torvalds }
8821da177e4SLinus Torvalds 
883a649fd92SAndrew Morton /*
884e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
885e286781dSNick Piggin  * gets returned with a refcount of 0.
886a649fd92SAndrew Morton  */
887a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
888a528910eSJohannes Weiner 			    bool reclaimed)
88949d2e9ccSChristoph Lameter {
890c4843a75SGreg Thelen 	unsigned long flags;
891bd4c82c2SHuang Ying 	int refcount;
892c4843a75SGreg Thelen 
89328e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
89428e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
89549d2e9ccSChristoph Lameter 
896b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
89749d2e9ccSChristoph Lameter 	/*
8980fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8990fd0e6b0SNick Piggin 	 *
9000fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
9010fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
9020fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
9030fd0e6b0SNick Piggin 	 * here, then the following race may occur:
9040fd0e6b0SNick Piggin 	 *
9050fd0e6b0SNick Piggin 	 * get_user_pages(&page);
9060fd0e6b0SNick Piggin 	 * [user mapping goes away]
9070fd0e6b0SNick Piggin 	 * write_to(page);
9080fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
9090fd0e6b0SNick Piggin 	 * SetPageDirty(page);
9100fd0e6b0SNick Piggin 	 * put_page(page);
9110fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
9120fd0e6b0SNick Piggin 	 *
9130fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
9140fd0e6b0SNick Piggin 	 *
9150fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
9160fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
9170139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
9180fd0e6b0SNick Piggin 	 *
9190fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
920b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
92149d2e9ccSChristoph Lameter 	 */
922906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
923bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
92449d2e9ccSChristoph Lameter 		goto cannot_free;
9251c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
926e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
927bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
92849d2e9ccSChristoph Lameter 		goto cannot_free;
929e286781dSNick Piggin 	}
93049d2e9ccSChristoph Lameter 
93149d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
93249d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
9330a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
9344e17ec25SMatthew Wilcox 		__delete_from_swap_cache(page, swap);
935b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
93675f6d6d2SMinchan Kim 		put_swap_page(page, swap);
937e286781dSNick Piggin 	} else {
9386072d13cSLinus Torvalds 		void (*freepage)(struct page *);
939a528910eSJohannes Weiner 		void *shadow = NULL;
9406072d13cSLinus Torvalds 
9416072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
942a528910eSJohannes Weiner 		/*
943a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
944a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
945a528910eSJohannes Weiner 		 *
946a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
947a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
948a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
949a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
950a528910eSJohannes Weiner 		 * back.
951f9fe48beSRoss Zwisler 		 *
952f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
953f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
954f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
955f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
956b93b0163SMatthew Wilcox 		 * same address_space.
957a528910eSJohannes Weiner 		 */
958a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
959f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
960a7ca12f9SAndrey Ryabinin 			shadow = workingset_eviction(page);
96162cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
962b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9636072d13cSLinus Torvalds 
9646072d13cSLinus Torvalds 		if (freepage != NULL)
9656072d13cSLinus Torvalds 			freepage(page);
966e286781dSNick Piggin 	}
967e286781dSNick Piggin 
96849d2e9ccSChristoph Lameter 	return 1;
96949d2e9ccSChristoph Lameter 
97049d2e9ccSChristoph Lameter cannot_free:
971b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
97249d2e9ccSChristoph Lameter 	return 0;
97349d2e9ccSChristoph Lameter }
97449d2e9ccSChristoph Lameter 
9751da177e4SLinus Torvalds /*
976e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
977e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
978e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
979e286781dSNick Piggin  * this page.
980e286781dSNick Piggin  */
981e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
982e286781dSNick Piggin {
983a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
984e286781dSNick Piggin 		/*
985e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
986e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
987e286781dSNick Piggin 		 * atomic operation.
988e286781dSNick Piggin 		 */
989fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
990e286781dSNick Piggin 		return 1;
991e286781dSNick Piggin 	}
992e286781dSNick Piggin 	return 0;
993e286781dSNick Piggin }
994e286781dSNick Piggin 
995894bc310SLee Schermerhorn /**
996894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
997894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
998894bc310SLee Schermerhorn  *
999894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1000894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1001894bc310SLee Schermerhorn  *
1002894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1003894bc310SLee Schermerhorn  */
1004894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1005894bc310SLee Schermerhorn {
1006c53954a0SMel Gorman 	lru_cache_add(page);
1007894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1008894bc310SLee Schermerhorn }
1009894bc310SLee Schermerhorn 
1010dfc8d636SJohannes Weiner enum page_references {
1011dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1012dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
101364574746SJohannes Weiner 	PAGEREF_KEEP,
1014dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1015dfc8d636SJohannes Weiner };
1016dfc8d636SJohannes Weiner 
1017dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1018dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1019dfc8d636SJohannes Weiner {
102064574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1021dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1022dfc8d636SJohannes Weiner 
1023c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1024c3ac9a8aSJohannes Weiner 					  &vm_flags);
102564574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1026dfc8d636SJohannes Weiner 
1027dfc8d636SJohannes Weiner 	/*
1028dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1029dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1030dfc8d636SJohannes Weiner 	 */
1031dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1032dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1033dfc8d636SJohannes Weiner 
103464574746SJohannes Weiner 	if (referenced_ptes) {
1035e4898273SMichal Hocko 		if (PageSwapBacked(page))
103664574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
103764574746SJohannes Weiner 		/*
103864574746SJohannes Weiner 		 * All mapped pages start out with page table
103964574746SJohannes Weiner 		 * references from the instantiating fault, so we need
104064574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
104164574746SJohannes Weiner 		 * than once.
104264574746SJohannes Weiner 		 *
104364574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
104464574746SJohannes Weiner 		 * inactive list.  Another page table reference will
104564574746SJohannes Weiner 		 * lead to its activation.
104664574746SJohannes Weiner 		 *
104764574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
104864574746SJohannes Weiner 		 * so that recently deactivated but used pages are
104964574746SJohannes Weiner 		 * quickly recovered.
105064574746SJohannes Weiner 		 */
105164574746SJohannes Weiner 		SetPageReferenced(page);
105264574746SJohannes Weiner 
105334dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1054dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1055dfc8d636SJohannes Weiner 
1056c909e993SKonstantin Khlebnikov 		/*
1057c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1058c909e993SKonstantin Khlebnikov 		 */
1059c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1060c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1061c909e993SKonstantin Khlebnikov 
106264574746SJohannes Weiner 		return PAGEREF_KEEP;
106364574746SJohannes Weiner 	}
106464574746SJohannes Weiner 
1065dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10662e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1067dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
106864574746SJohannes Weiner 
106964574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1070dfc8d636SJohannes Weiner }
1071dfc8d636SJohannes Weiner 
1072e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1073e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1074e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1075e2be15f6SMel Gorman {
1076b4597226SMel Gorman 	struct address_space *mapping;
1077b4597226SMel Gorman 
1078e2be15f6SMel Gorman 	/*
1079e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1080e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1081e2be15f6SMel Gorman 	 */
1082802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1083802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1084e2be15f6SMel Gorman 		*dirty = false;
1085e2be15f6SMel Gorman 		*writeback = false;
1086e2be15f6SMel Gorman 		return;
1087e2be15f6SMel Gorman 	}
1088e2be15f6SMel Gorman 
1089e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1090e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1091e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1092b4597226SMel Gorman 
1093b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1094b4597226SMel Gorman 	if (!page_has_private(page))
1095b4597226SMel Gorman 		return;
1096b4597226SMel Gorman 
1097b4597226SMel Gorman 	mapping = page_mapping(page);
1098b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1099b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1100e2be15f6SMel Gorman }
1101e2be15f6SMel Gorman 
1102e286781dSNick Piggin /*
11031742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
11041da177e4SLinus Torvalds  */
11051742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1106599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1107f84f6e2bSMel Gorman 				      struct scan_control *sc,
110802c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
11093c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
11108940b34aSMinchan Kim 				      bool ignore_references)
11111da177e4SLinus Torvalds {
11121da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1113abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
11143c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
1115886cf190SKirill Tkhai 	unsigned pgactivate = 0;
11161da177e4SLinus Torvalds 
1117060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
11181da177e4SLinus Torvalds 	cond_resched();
11191da177e4SLinus Torvalds 
11201da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
11211da177e4SLinus Torvalds 		struct address_space *mapping;
11221da177e4SLinus Torvalds 		struct page *page;
11231da177e4SLinus Torvalds 		int may_enter_fs;
11248940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1125e2be15f6SMel Gorman 		bool dirty, writeback;
112698879b3bSYang Shi 		unsigned int nr_pages;
11271da177e4SLinus Torvalds 
11281da177e4SLinus Torvalds 		cond_resched();
11291da177e4SLinus Torvalds 
11301da177e4SLinus Torvalds 		page = lru_to_page(page_list);
11311da177e4SLinus Torvalds 		list_del(&page->lru);
11321da177e4SLinus Torvalds 
1133529ae9aaSNick Piggin 		if (!trylock_page(page))
11341da177e4SLinus Torvalds 			goto keep;
11351da177e4SLinus Torvalds 
1136309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11371da177e4SLinus Torvalds 
1138d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
113998879b3bSYang Shi 
114098879b3bSYang Shi 		/* Account the number of base pages even though THP */
114198879b3bSYang Shi 		sc->nr_scanned += nr_pages;
114280e43426SChristoph Lameter 
114339b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1144ad6b6704SMinchan Kim 			goto activate_locked;
1145894bc310SLee Schermerhorn 
1146a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
114780e43426SChristoph Lameter 			goto keep_locked;
114880e43426SChristoph Lameter 
1149c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1150c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1151c661b078SAndy Whitcroft 
1152e62e384eSMichal Hocko 		/*
1153894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1154e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1155e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1156e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1157e2be15f6SMel Gorman 		 */
1158e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1159e2be15f6SMel Gorman 		if (dirty || writeback)
1160060f005fSKirill Tkhai 			stat->nr_dirty++;
1161e2be15f6SMel Gorman 
1162e2be15f6SMel Gorman 		if (dirty && !writeback)
1163060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1164e2be15f6SMel Gorman 
1165d04e8acdSMel Gorman 		/*
1166d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1167d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1168d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1169d04e8acdSMel Gorman 		 * end of the LRU a second time.
1170d04e8acdSMel Gorman 		 */
1171e2be15f6SMel Gorman 		mapping = page_mapping(page);
11721da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1173703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1174d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1175060f005fSKirill Tkhai 			stat->nr_congested++;
1176e2be15f6SMel Gorman 
1177e2be15f6SMel Gorman 		/*
1178283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1179283aba9fSMel Gorman 		 * are three cases to consider.
1180e62e384eSMichal Hocko 		 *
1181283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1182283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1183283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1184283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1185283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1186283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1187283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1188b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1189b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1190c3b94f44SHugh Dickins 		 *
119197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1192ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1193ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1194ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
119597c9341fSTejun Heo 		 *    reclaim and continue scanning.
1196283aba9fSMel Gorman 		 *
1197ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1198ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1199283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1200283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1201283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1202283aba9fSMel Gorman 		 *    would probably show more reasons.
1203283aba9fSMel Gorman 		 *
12047fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1205283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1206283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1207283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1208283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1209c55e8d03SJohannes Weiner 		 *
1210c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1211c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1212c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1213c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1214c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1215c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1216c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1217c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1218e62e384eSMichal Hocko 		 */
1219283aba9fSMel Gorman 		if (PageWriteback(page)) {
1220283aba9fSMel Gorman 			/* Case 1 above */
1221283aba9fSMel Gorman 			if (current_is_kswapd() &&
1222283aba9fSMel Gorman 			    PageReclaim(page) &&
1223599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1224060f005fSKirill Tkhai 				stat->nr_immediate++;
1225c55e8d03SJohannes Weiner 				goto activate_locked;
1226283aba9fSMel Gorman 
1227283aba9fSMel Gorman 			/* Case 2 above */
1228b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1229ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1230c3b94f44SHugh Dickins 				/*
1231c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1232c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1233c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1234c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1235c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1236c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1237c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1238c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1239c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1240c3b94f44SHugh Dickins 				 */
1241c3b94f44SHugh Dickins 				SetPageReclaim(page);
1242060f005fSKirill Tkhai 				stat->nr_writeback++;
1243c55e8d03SJohannes Weiner 				goto activate_locked;
1244283aba9fSMel Gorman 
1245283aba9fSMel Gorman 			/* Case 3 above */
1246283aba9fSMel Gorman 			} else {
12477fadc820SHugh Dickins 				unlock_page(page);
1248c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12497fadc820SHugh Dickins 				/* then go back and try same page again */
12507fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12517fadc820SHugh Dickins 				continue;
1252e62e384eSMichal Hocko 			}
1253283aba9fSMel Gorman 		}
12541da177e4SLinus Torvalds 
12558940b34aSMinchan Kim 		if (!ignore_references)
12566a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
125702c6de8dSMinchan Kim 
1258dfc8d636SJohannes Weiner 		switch (references) {
1259dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12601da177e4SLinus Torvalds 			goto activate_locked;
126164574746SJohannes Weiner 		case PAGEREF_KEEP:
126298879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
126364574746SJohannes Weiner 			goto keep_locked;
1264dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1265dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1266dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1267dfc8d636SJohannes Weiner 		}
12681da177e4SLinus Torvalds 
12691da177e4SLinus Torvalds 		/*
12701da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12711da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1272802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12731da177e4SLinus Torvalds 		 */
1274bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1275bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
127663eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
127763eb6b93SHugh Dickins 					goto keep_locked;
1278747552b1SHuang Ying 				if (PageTransHuge(page)) {
1279b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1280747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1281b8f593cdSHuang Ying 						goto activate_locked;
1282747552b1SHuang Ying 					/*
1283747552b1SHuang Ying 					 * Split pages without a PMD map right
1284747552b1SHuang Ying 					 * away. Chances are some or all of the
1285747552b1SHuang Ying 					 * tail pages can be freed without IO.
1286747552b1SHuang Ying 					 */
1287747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1288bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1289bd4c82c2SHuang Ying 								    page_list))
1290747552b1SHuang Ying 						goto activate_locked;
1291747552b1SHuang Ying 				}
12920f074658SMinchan Kim 				if (!add_to_swap(page)) {
12930f074658SMinchan Kim 					if (!PageTransHuge(page))
129498879b3bSYang Shi 						goto activate_locked_split;
1295bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1296bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1297bd4c82c2SHuang Ying 								    page_list))
12980f074658SMinchan Kim 						goto activate_locked;
1299fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1300fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1301fe490cc0SHuang Ying #endif
13020f074658SMinchan Kim 					if (!add_to_swap(page))
130398879b3bSYang Shi 						goto activate_locked_split;
13040f074658SMinchan Kim 				}
13050f074658SMinchan Kim 
130663eb6b93SHugh Dickins 				may_enter_fs = 1;
13071da177e4SLinus Torvalds 
1308e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
13091da177e4SLinus Torvalds 				mapping = page_mapping(page);
1310bd4c82c2SHuang Ying 			}
13117751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
13127751b2daSKirill A. Shutemov 			/* Split file THP */
13137751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
13147751b2daSKirill A. Shutemov 				goto keep_locked;
1315e2be15f6SMel Gorman 		}
13161da177e4SLinus Torvalds 
13171da177e4SLinus Torvalds 		/*
131898879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
131998879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
132098879b3bSYang Shi 		 *
132198879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
132298879b3bSYang Shi 		 * reach here.
132398879b3bSYang Shi 		 */
132498879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
132598879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
132698879b3bSYang Shi 			nr_pages = 1;
132798879b3bSYang Shi 		}
132898879b3bSYang Shi 
132998879b3bSYang Shi 		/*
13301da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
13311da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
13321da177e4SLinus Torvalds 		 */
1333802a3a92SShaohua Li 		if (page_mapped(page)) {
1334bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1335bd4c82c2SHuang Ying 
1336bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1337bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1338bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
133998879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
13401da177e4SLinus Torvalds 				goto activate_locked;
13411da177e4SLinus Torvalds 			}
13421da177e4SLinus Torvalds 		}
13431da177e4SLinus Torvalds 
13441da177e4SLinus Torvalds 		if (PageDirty(page)) {
1345ee72886dSMel Gorman 			/*
13464eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13474eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13484eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13494eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13504eda4823SJohannes Weiner 			 * write pages when we've encountered many
13514eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13524eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13534eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1354ee72886dSMel Gorman 			 */
1355f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13564eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1357599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
135849ea7eb6SMel Gorman 				/*
135949ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
136049ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
136149ea7eb6SMel Gorman 				 * except we already have the page isolated
136249ea7eb6SMel Gorman 				 * and know it's dirty
136349ea7eb6SMel Gorman 				 */
1364c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
136549ea7eb6SMel Gorman 				SetPageReclaim(page);
136649ea7eb6SMel Gorman 
1367c55e8d03SJohannes Weiner 				goto activate_locked;
1368ee72886dSMel Gorman 			}
1369ee72886dSMel Gorman 
1370dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13711da177e4SLinus Torvalds 				goto keep_locked;
13724dd4b920SAndrew Morton 			if (!may_enter_fs)
13731da177e4SLinus Torvalds 				goto keep_locked;
137452a8363eSChristoph Lameter 			if (!sc->may_writepage)
13751da177e4SLinus Torvalds 				goto keep_locked;
13761da177e4SLinus Torvalds 
1377d950c947SMel Gorman 			/*
1378d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1379d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1380d950c947SMel Gorman 			 * starts and then write it out here.
1381d950c947SMel Gorman 			 */
1382d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1383cb16556dSYang Shi 			switch (pageout(page, mapping)) {
13841da177e4SLinus Torvalds 			case PAGE_KEEP:
13851da177e4SLinus Torvalds 				goto keep_locked;
13861da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13871da177e4SLinus Torvalds 				goto activate_locked;
13881da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13897d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
139041ac1999SMel Gorman 					goto keep;
13917d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13921da177e4SLinus Torvalds 					goto keep;
13937d3579e8SKOSAKI Motohiro 
13941da177e4SLinus Torvalds 				/*
13951da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13961da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13971da177e4SLinus Torvalds 				 */
1398529ae9aaSNick Piggin 				if (!trylock_page(page))
13991da177e4SLinus Torvalds 					goto keep;
14001da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
14011da177e4SLinus Torvalds 					goto keep_locked;
14021da177e4SLinus Torvalds 				mapping = page_mapping(page);
14031da177e4SLinus Torvalds 			case PAGE_CLEAN:
14041da177e4SLinus Torvalds 				; /* try to free the page below */
14051da177e4SLinus Torvalds 			}
14061da177e4SLinus Torvalds 		}
14071da177e4SLinus Torvalds 
14081da177e4SLinus Torvalds 		/*
14091da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
14101da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
14111da177e4SLinus Torvalds 		 * the page as well.
14121da177e4SLinus Torvalds 		 *
14131da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
14141da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
14151da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
14161da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
14171da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
14181da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
14191da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
14201da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
14211da177e4SLinus Torvalds 		 *
14221da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
14231da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
14241da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
14251da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
14261da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
14271da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
14281da177e4SLinus Torvalds 		 */
1429266cf658SDavid Howells 		if (page_has_private(page)) {
14301da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14311da177e4SLinus Torvalds 				goto activate_locked;
1432e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1433e286781dSNick Piggin 				unlock_page(page);
1434e286781dSNick Piggin 				if (put_page_testzero(page))
14351da177e4SLinus Torvalds 					goto free_it;
1436e286781dSNick Piggin 				else {
1437e286781dSNick Piggin 					/*
1438e286781dSNick Piggin 					 * rare race with speculative reference.
1439e286781dSNick Piggin 					 * the speculative reference will free
1440e286781dSNick Piggin 					 * this page shortly, so we may
1441e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1442e286781dSNick Piggin 					 * leave it off the LRU).
1443e286781dSNick Piggin 					 */
1444e286781dSNick Piggin 					nr_reclaimed++;
1445e286781dSNick Piggin 					continue;
1446e286781dSNick Piggin 				}
1447e286781dSNick Piggin 			}
14481da177e4SLinus Torvalds 		}
14491da177e4SLinus Torvalds 
1450802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1451802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1452802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
145349d2e9ccSChristoph Lameter 				goto keep_locked;
1454802a3a92SShaohua Li 			if (PageDirty(page)) {
1455802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1456802a3a92SShaohua Li 				goto keep_locked;
1457802a3a92SShaohua Li 			}
14581da177e4SLinus Torvalds 
1459802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14602262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1461802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1462802a3a92SShaohua Li 			goto keep_locked;
14639a1ea439SHugh Dickins 
14649a1ea439SHugh Dickins 		unlock_page(page);
1465e286781dSNick Piggin free_it:
146698879b3bSYang Shi 		/*
146798879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
146898879b3bSYang Shi 		 * all base pages.
146998879b3bSYang Shi 		 */
147098879b3bSYang Shi 		nr_reclaimed += nr_pages;
1471abe4c3b5SMel Gorman 
1472abe4c3b5SMel Gorman 		/*
1473abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1474abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1475abe4c3b5SMel Gorman 		 */
14767ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1477bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
14787ae88534SYang Shi 		else
1479abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14801da177e4SLinus Torvalds 		continue;
14811da177e4SLinus Torvalds 
148298879b3bSYang Shi activate_locked_split:
148398879b3bSYang Shi 		/*
148498879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
148598879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
148698879b3bSYang Shi 		 */
148798879b3bSYang Shi 		if (nr_pages > 1) {
148898879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
148998879b3bSYang Shi 			nr_pages = 1;
149098879b3bSYang Shi 		}
14911da177e4SLinus Torvalds activate_locked:
149268a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1493ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1494ad6b6704SMinchan Kim 						PageMlocked(page)))
1495a2c43eedSHugh Dickins 			try_to_free_swap(page);
1496309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1497ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
1498886cf190SKirill Tkhai 			int type = page_is_file_cache(page);
14991da177e4SLinus Torvalds 			SetPageActive(page);
150098879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
15012262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1502ad6b6704SMinchan Kim 		}
15031da177e4SLinus Torvalds keep_locked:
15041da177e4SLinus Torvalds 		unlock_page(page);
15051da177e4SLinus Torvalds keep:
15061da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1507309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
15081da177e4SLinus Torvalds 	}
1509abe4c3b5SMel Gorman 
151098879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
151198879b3bSYang Shi 
1512747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
151372b252aeSMel Gorman 	try_to_unmap_flush();
15142d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1515abe4c3b5SMel Gorman 
15161da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1517886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
15180a31bc97SJohannes Weiner 
151905ff5137SAndrew Morton 	return nr_reclaimed;
15201da177e4SLinus Torvalds }
15211da177e4SLinus Torvalds 
152202c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
152302c6de8dSMinchan Kim 					    struct list_head *page_list)
152402c6de8dSMinchan Kim {
152502c6de8dSMinchan Kim 	struct scan_control sc = {
152602c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
152702c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
152802c6de8dSMinchan Kim 		.may_unmap = 1,
152902c6de8dSMinchan Kim 	};
1530060f005fSKirill Tkhai 	struct reclaim_stat dummy_stat;
15313c710c1aSMichal Hocko 	unsigned long ret;
153202c6de8dSMinchan Kim 	struct page *page, *next;
153302c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
153402c6de8dSMinchan Kim 
153502c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1536117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1537a58f2cefSMinchan Kim 		    !__PageMovable(page) && !PageUnevictable(page)) {
153802c6de8dSMinchan Kim 			ClearPageActive(page);
153902c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
154002c6de8dSMinchan Kim 		}
154102c6de8dSMinchan Kim 	}
154202c6de8dSMinchan Kim 
1543599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1544060f005fSKirill Tkhai 			TTU_IGNORE_ACCESS, &dummy_stat, true);
154502c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1546599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
154702c6de8dSMinchan Kim 	return ret;
154802c6de8dSMinchan Kim }
154902c6de8dSMinchan Kim 
15505ad333ebSAndy Whitcroft /*
15515ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15525ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15535ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15545ad333ebSAndy Whitcroft  *
15555ad333ebSAndy Whitcroft  * page:	page to consider
15565ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15575ad333ebSAndy Whitcroft  *
15585ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15595ad333ebSAndy Whitcroft  */
1560f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15615ad333ebSAndy Whitcroft {
15625ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15635ad333ebSAndy Whitcroft 
15645ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15655ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15665ad333ebSAndy Whitcroft 		return ret;
15675ad333ebSAndy Whitcroft 
1568e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1569e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1570894bc310SLee Schermerhorn 		return ret;
1571894bc310SLee Schermerhorn 
15725ad333ebSAndy Whitcroft 	ret = -EBUSY;
157308e552c6SKAMEZAWA Hiroyuki 
1574c8244935SMel Gorman 	/*
1575c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1576c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1577c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1578c8244935SMel Gorman 	 *
1579c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1580c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1581c8244935SMel Gorman 	 */
15821276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1583c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1584c8244935SMel Gorman 		if (PageWriteback(page))
158539deaf85SMinchan Kim 			return ret;
158639deaf85SMinchan Kim 
1587c8244935SMel Gorman 		if (PageDirty(page)) {
1588c8244935SMel Gorman 			struct address_space *mapping;
158969d763fcSMel Gorman 			bool migrate_dirty;
1590c8244935SMel Gorman 
1591c8244935SMel Gorman 			/*
1592c8244935SMel Gorman 			 * Only pages without mappings or that have a
1593c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
159469d763fcSMel Gorman 			 * without blocking. However, we can be racing with
159569d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
159669d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
159769d763fcSMel Gorman 			 * the page lock until after the page is removed
159869d763fcSMel Gorman 			 * from the page cache.
1599c8244935SMel Gorman 			 */
160069d763fcSMel Gorman 			if (!trylock_page(page))
160169d763fcSMel Gorman 				return ret;
160269d763fcSMel Gorman 
1603c8244935SMel Gorman 			mapping = page_mapping(page);
1604145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
160569d763fcSMel Gorman 			unlock_page(page);
160669d763fcSMel Gorman 			if (!migrate_dirty)
1607c8244935SMel Gorman 				return ret;
1608c8244935SMel Gorman 		}
1609c8244935SMel Gorman 	}
1610c8244935SMel Gorman 
1611f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1612f80c0673SMinchan Kim 		return ret;
1613f80c0673SMinchan Kim 
16145ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
16155ad333ebSAndy Whitcroft 		/*
16165ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
16175ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
16185ad333ebSAndy Whitcroft 		 * page release code relies on it.
16195ad333ebSAndy Whitcroft 		 */
16205ad333ebSAndy Whitcroft 		ClearPageLRU(page);
16215ad333ebSAndy Whitcroft 		ret = 0;
16225ad333ebSAndy Whitcroft 	}
16235ad333ebSAndy Whitcroft 
16245ad333ebSAndy Whitcroft 	return ret;
16255ad333ebSAndy Whitcroft }
16265ad333ebSAndy Whitcroft 
16277ee36a14SMel Gorman 
16287ee36a14SMel Gorman /*
16297ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
16307ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
16317ee36a14SMel Gorman  */
16327ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1633b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16347ee36a14SMel Gorman {
16357ee36a14SMel Gorman 	int zid;
16367ee36a14SMel Gorman 
16377ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16387ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16397ee36a14SMel Gorman 			continue;
16407ee36a14SMel Gorman 
16417ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1642b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1643b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1644b4536f0cSMichal Hocko #endif
16457ee36a14SMel Gorman 	}
16467ee36a14SMel Gorman 
16477ee36a14SMel Gorman }
16487ee36a14SMel Gorman 
1649f4b7e272SAndrey Ryabinin /**
1650f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16511da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16521da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16531da177e4SLinus Torvalds  *
16541da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16551da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16561da177e4SLinus Torvalds  *
16571da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16581da177e4SLinus Torvalds  *
1659791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16605dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16611da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1662f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1663fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16645ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16653cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16661da177e4SLinus Torvalds  *
16671da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16681da177e4SLinus Torvalds  */
166969e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16705dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1671fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1672a9e7c39fSKirill Tkhai 		enum lru_list lru)
16731da177e4SLinus Torvalds {
167475b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
167569e05944SAndrew Morton 	unsigned long nr_taken = 0;
1676599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16777cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16783db65812SJohannes Weiner 	unsigned long skipped = 0;
1679791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1680b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1681a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16821da177e4SLinus Torvalds 
168398879b3bSYang Shi 	total_scan = 0;
1684791b48b6SMinchan Kim 	scan = 0;
168598879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
16865ad333ebSAndy Whitcroft 		struct page *page;
16875ad333ebSAndy Whitcroft 
16881da177e4SLinus Torvalds 		page = lru_to_page(src);
16891da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16901da177e4SLinus Torvalds 
1691309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16928d438f96SNick Piggin 
1693d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
169498879b3bSYang Shi 		total_scan += nr_pages;
169598879b3bSYang Shi 
1696b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1697b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
169898879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1699b2e18757SMel Gorman 			continue;
1700b2e18757SMel Gorman 		}
1701b2e18757SMel Gorman 
1702791b48b6SMinchan Kim 		/*
1703791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1704791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1705791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1706791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
170798879b3bSYang Shi 		 *
170898879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
170998879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
171098879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1711791b48b6SMinchan Kim 		 */
171298879b3bSYang Shi 		scan += nr_pages;
1713f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
17145ad333ebSAndy Whitcroft 		case 0:
1715599d0c95SMel Gorman 			nr_taken += nr_pages;
1716599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
17175ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
17185ad333ebSAndy Whitcroft 			break;
17197c8ee9a8SNick Piggin 
17205ad333ebSAndy Whitcroft 		case -EBUSY:
17215ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
17225ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
17235ad333ebSAndy Whitcroft 			continue;
17245ad333ebSAndy Whitcroft 
17255ad333ebSAndy Whitcroft 		default:
17265ad333ebSAndy Whitcroft 			BUG();
17275ad333ebSAndy Whitcroft 		}
17285ad333ebSAndy Whitcroft 	}
17291da177e4SLinus Torvalds 
1730b2e18757SMel Gorman 	/*
1731b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1732b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1733b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1734b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1735b2e18757SMel Gorman 	 * system at risk of premature OOM.
1736b2e18757SMel Gorman 	 */
17377cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17387cc30fcfSMel Gorman 		int zid;
17397cc30fcfSMel Gorman 
17403db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17417cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17427cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17437cc30fcfSMel Gorman 				continue;
17447cc30fcfSMel Gorman 
17457cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17461265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17477cc30fcfSMel Gorman 		}
17487cc30fcfSMel Gorman 	}
1749791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17501265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1751791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1752b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17531da177e4SLinus Torvalds 	return nr_taken;
17541da177e4SLinus Torvalds }
17551da177e4SLinus Torvalds 
175662695a84SNick Piggin /**
175762695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
175862695a84SNick Piggin  * @page: page to isolate from its LRU list
175962695a84SNick Piggin  *
176062695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
176162695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
176262695a84SNick Piggin  *
176362695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
176462695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
176562695a84SNick Piggin  *
176662695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1767894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1768894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1769894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
177062695a84SNick Piggin  *
177162695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
177262695a84SNick Piggin  * found will be decremented.
177362695a84SNick Piggin  *
177462695a84SNick Piggin  * Restrictions:
1775a5d09bedSMike Rapoport  *
177662695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
177762695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
177862695a84SNick Piggin  *     without a stable reference).
177962695a84SNick Piggin  * (2) the lru_lock must not be held.
178062695a84SNick Piggin  * (3) interrupts must be enabled.
178162695a84SNick Piggin  */
178262695a84SNick Piggin int isolate_lru_page(struct page *page)
178362695a84SNick Piggin {
178462695a84SNick Piggin 	int ret = -EBUSY;
178562695a84SNick Piggin 
1786309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1787cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17880c917313SKonstantin Khlebnikov 
178962695a84SNick Piggin 	if (PageLRU(page)) {
1790f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1791fa9add64SHugh Dickins 		struct lruvec *lruvec;
179262695a84SNick Piggin 
1793f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1794f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17950c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1796894bc310SLee Schermerhorn 			int lru = page_lru(page);
17970c917313SKonstantin Khlebnikov 			get_page(page);
179862695a84SNick Piggin 			ClearPageLRU(page);
1799fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1800fa9add64SHugh Dickins 			ret = 0;
180162695a84SNick Piggin 		}
1802f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
180362695a84SNick Piggin 	}
180462695a84SNick Piggin 	return ret;
180562695a84SNick Piggin }
180662695a84SNick Piggin 
18075ad333ebSAndy Whitcroft /*
1808d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1809d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1810d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1811d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1812d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
181335cd7815SRik van Riel  */
1814599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
181535cd7815SRik van Riel 		struct scan_control *sc)
181635cd7815SRik van Riel {
181735cd7815SRik van Riel 	unsigned long inactive, isolated;
181835cd7815SRik van Riel 
181935cd7815SRik van Riel 	if (current_is_kswapd())
182035cd7815SRik van Riel 		return 0;
182135cd7815SRik van Riel 
1822b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
182335cd7815SRik van Riel 		return 0;
182435cd7815SRik van Riel 
182535cd7815SRik van Riel 	if (file) {
1826599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1827599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
182835cd7815SRik van Riel 	} else {
1829599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1830599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
183135cd7815SRik van Riel 	}
183235cd7815SRik van Riel 
18333cf23841SFengguang Wu 	/*
18343cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18353cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18363cf23841SFengguang Wu 	 * deadlock.
18373cf23841SFengguang Wu 	 */
1838d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18393cf23841SFengguang Wu 		inactive >>= 3;
18403cf23841SFengguang Wu 
184135cd7815SRik van Riel 	return isolated > inactive;
184235cd7815SRik van Riel }
184335cd7815SRik van Riel 
1844a222f341SKirill Tkhai /*
1845a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1846a222f341SKirill Tkhai  *
1847a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1848a222f341SKirill Tkhai  * processes, from rmap.
1849a222f341SKirill Tkhai  *
1850a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1851a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1852a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1853a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1854a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1855a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1856a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1857a222f341SKirill Tkhai  *
1858a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1859a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1860a222f341SKirill Tkhai  *
1861a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1862a222f341SKirill Tkhai  */
1863a222f341SKirill Tkhai 
1864a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1865a222f341SKirill Tkhai 						     struct list_head *list)
186666635629SMel Gorman {
1867599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1868a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18693f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1870a222f341SKirill Tkhai 	struct page *page;
1871a222f341SKirill Tkhai 	enum lru_list lru;
187266635629SMel Gorman 
1873a222f341SKirill Tkhai 	while (!list_empty(list)) {
1874a222f341SKirill Tkhai 		page = lru_to_page(list);
1875309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
187639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1877a222f341SKirill Tkhai 			list_del(&page->lru);
1878599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
187966635629SMel Gorman 			putback_lru_page(page);
1880599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
188166635629SMel Gorman 			continue;
188266635629SMel Gorman 		}
1883599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1884fa9add64SHugh Dickins 
18857a608572SLinus Torvalds 		SetPageLRU(page);
188666635629SMel Gorman 		lru = page_lru(page);
1887a222f341SKirill Tkhai 
1888a222f341SKirill Tkhai 		nr_pages = hpage_nr_pages(page);
1889a222f341SKirill Tkhai 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1890a222f341SKirill Tkhai 		list_move(&page->lru, &lruvec->lists[lru]);
1891fa9add64SHugh Dickins 
18922bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18932bcf8879SHugh Dickins 			__ClearPageLRU(page);
18942bcf8879SHugh Dickins 			__ClearPageActive(page);
1895fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18962bcf8879SHugh Dickins 
18972bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1898599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
18992bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1900599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
19012bcf8879SHugh Dickins 			} else
19022bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
1903a222f341SKirill Tkhai 		} else {
1904a222f341SKirill Tkhai 			nr_moved += nr_pages;
190566635629SMel Gorman 		}
190666635629SMel Gorman 	}
190766635629SMel Gorman 
19083f79768fSHugh Dickins 	/*
19093f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
19103f79768fSHugh Dickins 	 */
1911a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1912a222f341SKirill Tkhai 
1913a222f341SKirill Tkhai 	return nr_moved;
191466635629SMel Gorman }
191566635629SMel Gorman 
191666635629SMel Gorman /*
1917399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1918399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1919399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1920399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1921399ba0b9SNeilBrown  */
1922399ba0b9SNeilBrown static int current_may_throttle(void)
1923399ba0b9SNeilBrown {
1924399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1925399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1926399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1927399ba0b9SNeilBrown }
1928399ba0b9SNeilBrown 
1929399ba0b9SNeilBrown /*
1930b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
19311742f19fSAndrew Morton  * of reclaimed pages
19321da177e4SLinus Torvalds  */
193366635629SMel Gorman static noinline_for_stack unsigned long
19341a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19359e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19361da177e4SLinus Torvalds {
19371da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1938e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
193905ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1940e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1941060f005fSKirill Tkhai 	struct reclaim_stat stat;
19423cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1943f46b7912SKirill Tkhai 	enum vm_event_item item;
1944599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19451a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1946db73ee0dSMichal Hocko 	bool stalled = false;
194778dc583dSKOSAKI Motohiro 
1948599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1949db73ee0dSMichal Hocko 		if (stalled)
1950db73ee0dSMichal Hocko 			return 0;
1951db73ee0dSMichal Hocko 
1952db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1953db73ee0dSMichal Hocko 		msleep(100);
1954db73ee0dSMichal Hocko 		stalled = true;
195535cd7815SRik van Riel 
195635cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
195735cd7815SRik van Riel 		if (fatal_signal_pending(current))
195835cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
195935cd7815SRik van Riel 	}
196035cd7815SRik van Riel 
19611da177e4SLinus Torvalds 	lru_add_drain();
1962f80c0673SMinchan Kim 
1963599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19641da177e4SLinus Torvalds 
19655dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1966a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
196795d918fcSKonstantin Khlebnikov 
1968599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19699d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
197095d918fcSKonstantin Khlebnikov 
1971f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1972b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1973f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1974f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1975599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1976d563c050SHillf Danton 
1977d563c050SHillf Danton 	if (nr_taken == 0)
197866635629SMel Gorman 		return 0;
1979b35ea17bSKOSAKI Motohiro 
1980a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19813c710c1aSMichal Hocko 				&stat, false);
1982c661b078SAndy Whitcroft 
1983599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19843f79768fSHugh Dickins 
1985f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1986b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1987f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
1988f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1989b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1990b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1991a74609faSNick Piggin 
1992a222f341SKirill Tkhai 	move_pages_to_lru(lruvec, &page_list);
19933f79768fSHugh Dickins 
1994599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19953f79768fSHugh Dickins 
1996599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19973f79768fSHugh Dickins 
1998747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19992d4894b5SMel Gorman 	free_unref_page_list(&page_list);
2000e11da5b4SMel Gorman 
200192df3a72SMel Gorman 	/*
20021c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
20031c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
20041c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
20051c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
20061c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
20071c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
20081c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
20091c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
20101c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
20111c610d5fSAndrey Ryabinin 	 */
20121c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
20131c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
20141c610d5fSAndrey Ryabinin 
2015d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2016d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2017d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2018d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2019d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2020d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2021d108c772SAndrey Ryabinin 	if (file)
2022d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
20238e950282SMel Gorman 
2024599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2025d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
202605ff5137SAndrew Morton 	return nr_reclaimed;
20271da177e4SLinus Torvalds }
20281da177e4SLinus Torvalds 
2029f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20301a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2031f16015fbSJohannes Weiner 			       struct scan_control *sc,
20329e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20331cfb419bSKAMEZAWA Hiroyuki {
203444c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2035f626012dSHugh Dickins 	unsigned long nr_scanned;
20366fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20371cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20388cab4754SWu Fengguang 	LIST_HEAD(l_active);
2039b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20401cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20411a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20429d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20439d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20443cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2045599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20461cfb419bSKAMEZAWA Hiroyuki 
20471da177e4SLinus Torvalds 	lru_add_drain();
2048f80c0673SMinchan Kim 
2049599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2050925b7673SJohannes Weiner 
20515dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2052a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
205389b5fae5SJohannes Weiner 
2054599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2055b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20561cfb419bSKAMEZAWA Hiroyuki 
2057599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20582fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20599d5e6a9fSHugh Dickins 
2060599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20611da177e4SLinus Torvalds 
20621da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20631da177e4SLinus Torvalds 		cond_resched();
20641da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20651da177e4SLinus Torvalds 		list_del(&page->lru);
20667e9cd484SRik van Riel 
206739b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2068894bc310SLee Schermerhorn 			putback_lru_page(page);
2069894bc310SLee Schermerhorn 			continue;
2070894bc310SLee Schermerhorn 		}
2071894bc310SLee Schermerhorn 
2072cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2073cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2074cc715d99SMel Gorman 				if (page_has_private(page))
2075cc715d99SMel Gorman 					try_to_release_page(page, 0);
2076cc715d99SMel Gorman 				unlock_page(page);
2077cc715d99SMel Gorman 			}
2078cc715d99SMel Gorman 		}
2079cc715d99SMel Gorman 
2080c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2081c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20829992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20838cab4754SWu Fengguang 			/*
20848cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20858cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20868cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20878cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20888cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20898cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20908cab4754SWu Fengguang 			 * so we ignore them here.
20918cab4754SWu Fengguang 			 */
209241e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20938cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20948cab4754SWu Fengguang 				continue;
20958cab4754SWu Fengguang 			}
20968cab4754SWu Fengguang 		}
20977e9cd484SRik van Riel 
20985205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20991899ad18SJohannes Weiner 		SetPageWorkingset(page);
21001da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
21011da177e4SLinus Torvalds 	}
21021da177e4SLinus Torvalds 
2103b555749aSAndrew Morton 	/*
21048cab4754SWu Fengguang 	 * Move pages back to the lru list.
2105b555749aSAndrew Morton 	 */
2106599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
21074f98a2feSRik van Riel 	/*
21088cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
21098cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
21108cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
21117c0db9e9SJerome Marchand 	 * get_scan_count.
2112556adecbSRik van Riel 	 */
2113b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2114556adecbSRik van Riel 
2115a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2116a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2117f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2118f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
21199851ac13SKirill Tkhai 
21209851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
21219851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
21229851ac13SKirill Tkhai 
2123599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2124599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21252bcf8879SHugh Dickins 
2126f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2127f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
21289d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21299d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21301da177e4SLinus Torvalds }
21311da177e4SLinus Torvalds 
21321a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
21331a4e58ccSMinchan Kim {
21341a4e58ccSMinchan Kim 	int nid = -1;
21351a4e58ccSMinchan Kim 	unsigned long nr_reclaimed = 0;
21361a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
21371a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
21381a4e58ccSMinchan Kim 	struct page *page;
21391a4e58ccSMinchan Kim 	struct scan_control sc = {
21401a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
21411a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
21421a4e58ccSMinchan Kim 		.may_writepage = 1,
21431a4e58ccSMinchan Kim 		.may_unmap = 1,
21441a4e58ccSMinchan Kim 		.may_swap = 1,
21451a4e58ccSMinchan Kim 	};
21461a4e58ccSMinchan Kim 
21471a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
21481a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
21491a4e58ccSMinchan Kim 		if (nid == -1) {
21501a4e58ccSMinchan Kim 			nid = page_to_nid(page);
21511a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
21521a4e58ccSMinchan Kim 		}
21531a4e58ccSMinchan Kim 
21541a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
21551a4e58ccSMinchan Kim 			ClearPageActive(page);
21561a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
21571a4e58ccSMinchan Kim 			continue;
21581a4e58ccSMinchan Kim 		}
21591a4e58ccSMinchan Kim 
21601a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21611a4e58ccSMinchan Kim 						NODE_DATA(nid),
21621a4e58ccSMinchan Kim 						&sc, 0,
21631a4e58ccSMinchan Kim 						&dummy_stat, false);
21641a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21651a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21661a4e58ccSMinchan Kim 			list_del(&page->lru);
21671a4e58ccSMinchan Kim 			putback_lru_page(page);
21681a4e58ccSMinchan Kim 		}
21691a4e58ccSMinchan Kim 
21701a4e58ccSMinchan Kim 		nid = -1;
21711a4e58ccSMinchan Kim 	}
21721a4e58ccSMinchan Kim 
21731a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
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 
21851a4e58ccSMinchan Kim 	return nr_reclaimed;
21861a4e58ccSMinchan Kim }
21871a4e58ccSMinchan Kim 
218859dc76b0SRik van Riel /*
218959dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
219059dc76b0SRik van Riel  * to do too much work.
219114797e23SKOSAKI Motohiro  *
219259dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
219359dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
219459dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
219559dc76b0SRik van Riel  *
219659dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
219759dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
219859dc76b0SRik van Riel  *
21992a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
22002a2e4885SJohannes Weiner  *
220159dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
22023a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
220359dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
220459dc76b0SRik van Riel  *
220559dc76b0SRik van Riel  * total     target    max
220659dc76b0SRik van Riel  * memory    ratio     inactive
220759dc76b0SRik van Riel  * -------------------------------------
220859dc76b0SRik van Riel  *   10MB       1         5MB
220959dc76b0SRik van Riel  *  100MB       1        50MB
221059dc76b0SRik van Riel  *    1GB       3       250MB
221159dc76b0SRik van Riel  *   10GB      10       0.9GB
221259dc76b0SRik van Riel  *  100GB      31         3GB
221359dc76b0SRik van Riel  *    1TB     101        10GB
221459dc76b0SRik van Riel  *   10TB     320        32GB
221514797e23SKOSAKI Motohiro  */
2216f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
22172c012a4aSKuo-Hsin Yang 				 struct scan_control *sc, bool trace)
221814797e23SKOSAKI Motohiro {
2219fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
22202a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22212a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
22222a2e4885SJohannes Weiner 	unsigned long inactive, active;
22232a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
22242a2e4885SJohannes Weiner 	unsigned long refaults;
222559dc76b0SRik van Riel 	unsigned long gb;
222659dc76b0SRik van Riel 
2227fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2228fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2229f8d1a311SMel Gorman 
22302a2e4885SJohannes Weiner 	/*
22312a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
22322a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
22332a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
22342a2e4885SJohannes Weiner 	 */
2235205b20ccSJohannes Weiner 	refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
22362c012a4aSKuo-Hsin Yang 	if (file && lruvec->refaults != refaults) {
22372a2e4885SJohannes Weiner 		inactive_ratio = 0;
22382a2e4885SJohannes Weiner 	} else {
223959dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
224059dc76b0SRik van Riel 		if (gb)
224159dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2242b39415b2SRik van Riel 		else
224359dc76b0SRik van Riel 			inactive_ratio = 1;
22442a2e4885SJohannes Weiner 	}
224559dc76b0SRik van Riel 
22462c012a4aSKuo-Hsin Yang 	if (trace)
22472a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2248fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2249fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2250fd538803SMichal Hocko 			inactive_ratio, file);
2251fd538803SMichal Hocko 
225259dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2253b39415b2SRik van Riel }
2254b39415b2SRik van Riel 
22554f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
22563b991208SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2257b69408e8SChristoph Lameter {
2258b39415b2SRik van Riel 	if (is_active_lru(lru)) {
22593b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru), sc, true))
22601a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2261556adecbSRik van Riel 		return 0;
2262556adecbSRik van Riel 	}
2263556adecbSRik van Riel 
22641a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2265b69408e8SChristoph Lameter }
2266b69408e8SChristoph Lameter 
22679a265114SJohannes Weiner enum scan_balance {
22689a265114SJohannes Weiner 	SCAN_EQUAL,
22699a265114SJohannes Weiner 	SCAN_FRACT,
22709a265114SJohannes Weiner 	SCAN_ANON,
22719a265114SJohannes Weiner 	SCAN_FILE,
22729a265114SJohannes Weiner };
22739a265114SJohannes Weiner 
22741da177e4SLinus Torvalds /*
22754f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22764f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22774f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22784f98a2feSRik van Riel  * onto the active list instead of evict.
22794f98a2feSRik van Riel  *
2280be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2281be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22824f98a2feSRik van Riel  */
228333377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
2284f87bccdeSAndrey Ryabinin 			   struct scan_control *sc, unsigned long *nr)
22854f98a2feSRik van Riel {
228633377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
228790126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
22889a265114SJohannes Weiner 	u64 fraction[2];
22899a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2290599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22919a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
22929a265114SJohannes Weiner 	enum scan_balance scan_balance;
22930bf1457fSJohannes Weiner 	unsigned long anon, file;
22949a265114SJohannes Weiner 	unsigned long ap, fp;
22959a265114SJohannes Weiner 	enum lru_list lru;
229676a33fc3SShaohua Li 
229776a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2298d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22999a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
230076a33fc3SShaohua Li 		goto out;
230176a33fc3SShaohua Li 	}
23024f98a2feSRik van Riel 
230310316b31SJohannes Weiner 	/*
230410316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
230510316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
230610316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
230710316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
230810316b31SJohannes Weiner 	 * too expensive.
230910316b31SJohannes Weiner 	 */
2310b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
23119a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
231210316b31SJohannes Weiner 		goto out;
231310316b31SJohannes Weiner 	}
231410316b31SJohannes Weiner 
231510316b31SJohannes Weiner 	/*
231610316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
231710316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
231810316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
231910316b31SJohannes Weiner 	 */
232002695175SJohannes Weiner 	if (!sc->priority && swappiness) {
23219a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
232210316b31SJohannes Weiner 		goto out;
232310316b31SJohannes Weiner 	}
232410316b31SJohannes Weiner 
232511d16c25SJohannes Weiner 	/*
232662376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
232762376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
232862376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
232962376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
233062376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
233162376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
233262376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
233362376251SJohannes Weiner 	 */
2334b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
2335599d0c95SMel Gorman 		unsigned long pgdatfile;
2336599d0c95SMel Gorman 		unsigned long pgdatfree;
2337599d0c95SMel Gorman 		int z;
2338599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
233962376251SJohannes Weiner 
2340599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2341599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2342599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
23432ab051e1SJerome Marchand 
2344599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2345599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
23466aa303deSMel Gorman 			if (!managed_zone(zone))
2347599d0c95SMel Gorman 				continue;
2348599d0c95SMel Gorman 
2349599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2350599d0c95SMel Gorman 		}
2351599d0c95SMel Gorman 
2352599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
235306226226SDavid Rientjes 			/*
235406226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
235506226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
235606226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
235706226226SDavid Rientjes 			 */
23583b991208SJohannes Weiner 			if (!inactive_list_is_low(lruvec, false, sc, false) &&
235906226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
236006226226SDavid Rientjes 					>> sc->priority) {
236162376251SJohannes Weiner 				scan_balance = SCAN_ANON;
236262376251SJohannes Weiner 				goto out;
236362376251SJohannes Weiner 			}
236462376251SJohannes Weiner 		}
236506226226SDavid Rientjes 	}
236662376251SJohannes Weiner 
236762376251SJohannes Weiner 	/*
2368316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2369316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2370316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2371316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2372316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2373316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2374316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2375e9868505SRik van Riel 	 */
23763b991208SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, sc, false) &&
237771ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
23789a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2379e9868505SRik van Riel 		goto out;
23804f98a2feSRik van Riel 	}
23814f98a2feSRik van Riel 
23829a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23839a265114SJohannes Weiner 
23844f98a2feSRik van Riel 	/*
238558c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
238658c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
238758c37f6eSKOSAKI Motohiro 	 */
238802695175SJohannes Weiner 	anon_prio = swappiness;
238975b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
239058c37f6eSKOSAKI Motohiro 
239158c37f6eSKOSAKI Motohiro 	/*
23924f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
23934f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
23944f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
23954f98a2feSRik van Riel 	 *
23964f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
23974f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
23984f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
23994f98a2feSRik van Riel 	 *
24004f98a2feSRik van Riel 	 * anon in [0], file in [1]
24014f98a2feSRik van Riel 	 */
24022ab051e1SJerome Marchand 
2403fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2404fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2405fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2406fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
24072ab051e1SJerome Marchand 
2408599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
240958c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
24106e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
24116e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
24124f98a2feSRik van Riel 	}
24134f98a2feSRik van Riel 
24146e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
24156e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
24166e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
24174f98a2feSRik van Riel 	}
24184f98a2feSRik van Riel 
24194f98a2feSRik van Riel 	/*
242000d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
242100d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
242200d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
24234f98a2feSRik van Riel 	 */
2424fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
24256e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
24264f98a2feSRik van Riel 
2427fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
24286e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2429599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
24304f98a2feSRik van Riel 
243176a33fc3SShaohua Li 	fraction[0] = ap;
243276a33fc3SShaohua Li 	fraction[1] = fp;
243376a33fc3SShaohua Li 	denominator = ap + fp + 1;
243476a33fc3SShaohua Li out:
24354111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24364111304dSHugh Dickins 		int file = is_file_lru(lru);
24379783aa99SChris Down 		unsigned long lruvec_size;
243876a33fc3SShaohua Li 		unsigned long scan;
24391bc63fb1SChris Down 		unsigned long protection;
244076a33fc3SShaohua Li 
24419783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
24421bc63fb1SChris Down 		protection = mem_cgroup_protection(memcg,
24431bc63fb1SChris Down 						   sc->memcg_low_reclaim);
24449783aa99SChris Down 
24451bc63fb1SChris Down 		if (protection) {
24469783aa99SChris Down 			/*
24479783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
24489783aa99SChris Down 			 * its current usage to its memory.low or memory.min
24499783aa99SChris Down 			 * setting.
24509783aa99SChris Down 			 *
24519783aa99SChris Down 			 * This is important, as otherwise scanning aggression
24529783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
24539783aa99SChris Down 			 * approach the memory protection threshold, to totally
24549783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
24559783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
24569783aa99SChris Down 			 * also means we simply get no protection at all if we
24579783aa99SChris Down 			 * set it too low, which is not ideal.
24581bc63fb1SChris Down 			 *
24591bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
24601bc63fb1SChris Down 			 * pressure by how much of the total memory used is
24611bc63fb1SChris Down 			 * within protection thresholds.
24629783aa99SChris Down 			 *
24639de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
24649de7ca46SChris Down 			 * we skip over all groups that are within their low
24659de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
24669de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
24679de7ca46SChris Down 			 * the best-effort low protection. However, we still
24689de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
24699de7ca46SChris Down 			 * that case instead of simply punishing them all
24709de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
24711bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
24721bc63fb1SChris Down 			 * again by how much of the total memory used is under
24731bc63fb1SChris Down 			 * hard protection.
24749783aa99SChris Down 			 */
24751bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
24761bc63fb1SChris Down 
24771bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
24781bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
24791bc63fb1SChris Down 
24801bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
24811bc63fb1SChris Down 				cgroup_size;
24829783aa99SChris Down 
24839783aa99SChris Down 			/*
24841bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
24859de7ca46SChris Down 			 * reclaim moving forwards, avoiding decremeting
24869de7ca46SChris Down 			 * sc->priority further than desirable.
24879783aa99SChris Down 			 */
24881bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
24899783aa99SChris Down 		} else {
24909783aa99SChris Down 			scan = lruvec_size;
24919783aa99SChris Down 		}
24929783aa99SChris Down 
24939783aa99SChris Down 		scan >>= sc->priority;
24949783aa99SChris Down 
2495688035f7SJohannes Weiner 		/*
2496688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2497688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2498688035f7SJohannes Weiner 		 */
2499688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
25009783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
25019a265114SJohannes Weiner 
25029a265114SJohannes Weiner 		switch (scan_balance) {
25039a265114SJohannes Weiner 		case SCAN_EQUAL:
25049a265114SJohannes Weiner 			/* Scan lists relative to size */
25059a265114SJohannes Weiner 			break;
25069a265114SJohannes Weiner 		case SCAN_FRACT:
25079a265114SJohannes Weiner 			/*
25089a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
25099a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
251068600f62SRoman Gushchin 			 * Make sure we don't miss the last page
251168600f62SRoman Gushchin 			 * because of a round-off error.
25129a265114SJohannes Weiner 			 */
251368600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
25146f04f48dSSuleiman Souhlal 						  denominator);
25159a265114SJohannes Weiner 			break;
25169a265114SJohannes Weiner 		case SCAN_FILE:
25179a265114SJohannes Weiner 		case SCAN_ANON:
25189a265114SJohannes Weiner 			/* Scan one type exclusively */
25196b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
25209783aa99SChris Down 				lruvec_size = 0;
25219a265114SJohannes Weiner 				scan = 0;
25226b4f7799SJohannes Weiner 			}
25239a265114SJohannes Weiner 			break;
25249a265114SJohannes Weiner 		default:
25259a265114SJohannes Weiner 			/* Look ma, no brain */
25269a265114SJohannes Weiner 			BUG();
25279a265114SJohannes Weiner 		}
25286b4f7799SJohannes Weiner 
25294111304dSHugh Dickins 		nr[lru] = scan;
253076a33fc3SShaohua Li 	}
25316e08a369SWu Fengguang }
25324f98a2feSRik van Riel 
25339b4f98cdSJohannes Weiner /*
2534a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
25359b4f98cdSJohannes Weiner  */
2536a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
2537f87bccdeSAndrey Ryabinin 			      struct scan_control *sc)
25389b4f98cdSJohannes Weiner {
2539867e5e1dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
25409b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2541e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25429b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25439b4f98cdSJohannes Weiner 	enum lru_list lru;
25449b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25459b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25469b4f98cdSJohannes Weiner 	struct blk_plug plug;
25471a501907SMel Gorman 	bool scan_adjusted;
25489b4f98cdSJohannes Weiner 
2549f87bccdeSAndrey Ryabinin 	get_scan_count(lruvec, memcg, sc, nr);
25509b4f98cdSJohannes Weiner 
2551e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2552e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2553e82e0561SMel Gorman 
25541a501907SMel Gorman 	/*
25551a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25561a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25571a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25581a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25591a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25601a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25611a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25621a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25631a501907SMel Gorman 	 * dropped to zero at the first pass.
25641a501907SMel Gorman 	 */
2565b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
25661a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25671a501907SMel Gorman 
25689b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25699b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25709b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2571e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2572e82e0561SMel Gorman 		unsigned long nr_scanned;
2573e82e0561SMel Gorman 
25749b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25759b4f98cdSJohannes Weiner 			if (nr[lru]) {
25769b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
25779b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
25789b4f98cdSJohannes Weiner 
25799b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
25803b991208SJohannes Weiner 							    lruvec, sc);
25819b4f98cdSJohannes Weiner 			}
25829b4f98cdSJohannes Weiner 		}
2583e82e0561SMel Gorman 
2584bd041733SMichal Hocko 		cond_resched();
2585bd041733SMichal Hocko 
2586e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2587e82e0561SMel Gorman 			continue;
2588e82e0561SMel Gorman 
25899b4f98cdSJohannes Weiner 		/*
2590e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25911a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2592e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2593e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2594e82e0561SMel Gorman 		 * proportional to the original scan target.
2595e82e0561SMel Gorman 		 */
2596e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2597e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2598e82e0561SMel Gorman 
25991a501907SMel Gorman 		/*
26001a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
26011a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
26021a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
26031a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
26041a501907SMel Gorman 		 */
26051a501907SMel Gorman 		if (!nr_file || !nr_anon)
26061a501907SMel Gorman 			break;
26071a501907SMel Gorman 
2608e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2609e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2610e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2611e82e0561SMel Gorman 			lru = LRU_BASE;
2612e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2613e82e0561SMel Gorman 		} else {
2614e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2615e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2616e82e0561SMel Gorman 			lru = LRU_FILE;
2617e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2618e82e0561SMel Gorman 		}
2619e82e0561SMel Gorman 
2620e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2621e82e0561SMel Gorman 		nr[lru] = 0;
2622e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2623e82e0561SMel Gorman 
2624e82e0561SMel Gorman 		/*
2625e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2626e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2627e82e0561SMel Gorman 		 */
2628e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2629e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2630e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2631e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2632e82e0561SMel Gorman 
2633e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2634e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2635e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2636e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2637e82e0561SMel Gorman 
2638e82e0561SMel Gorman 		scan_adjusted = true;
26399b4f98cdSJohannes Weiner 	}
26409b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26419b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26429b4f98cdSJohannes Weiner 
26439b4f98cdSJohannes Weiner 	/*
26449b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26459b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26469b4f98cdSJohannes Weiner 	 */
2647a1086291SJohannes Weiner 	if (total_swap_pages && inactive_list_is_low(lruvec, false, sc, true))
26489b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26499b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26509b4f98cdSJohannes Weiner }
26519b4f98cdSJohannes Weiner 
265223b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26539e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
265423b9da55SMel Gorman {
2655d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
265623b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26579e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
265823b9da55SMel Gorman 		return true;
265923b9da55SMel Gorman 
266023b9da55SMel Gorman 	return false;
266123b9da55SMel Gorman }
266223b9da55SMel Gorman 
26634f98a2feSRik van Riel /*
266423b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
266523b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
266623b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
266723b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
266823b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26693e7d3449SMel Gorman  */
2670a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26713e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26723e7d3449SMel Gorman 					struct scan_control *sc)
26733e7d3449SMel Gorman {
26743e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26753e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2676a9dd0a83SMel Gorman 	int z;
26773e7d3449SMel Gorman 
26783e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
26799e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
26803e7d3449SMel Gorman 		return false;
26813e7d3449SMel Gorman 
26823e7d3449SMel Gorman 	/*
26835ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
26845ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
26855ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
26865ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
26875ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
26885ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
26895ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
26905ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
26912876592fSMel Gorman 	 */
26922876592fSMel Gorman 	if (!nr_reclaimed)
26932876592fSMel Gorman 		return false;
26943e7d3449SMel Gorman 
26953e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2696a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2697a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
26986aa303deSMel Gorman 		if (!managed_zone(zone))
2699a9dd0a83SMel Gorman 			continue;
2700a9dd0a83SMel Gorman 
2701a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2702cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
27033e7d3449SMel Gorman 		case COMPACT_CONTINUE:
27043e7d3449SMel Gorman 			return false;
27053e7d3449SMel Gorman 		default:
2706a9dd0a83SMel Gorman 			/* check next zone */
2707a9dd0a83SMel Gorman 			;
27083e7d3449SMel Gorman 		}
27093e7d3449SMel Gorman 	}
27101c6c1597SHillf Danton 
27111c6c1597SHillf Danton 	/*
27121c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
27131c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
27141c6c1597SHillf Danton 	 */
27151c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
27161c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
27171c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
27181c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
27191c6c1597SHillf Danton 
27205ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2721a9dd0a83SMel Gorman }
27223e7d3449SMel Gorman 
2723e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2724e3c1ac58SAndrey Ryabinin {
2725e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2726e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2727e3c1ac58SAndrey Ryabinin }
2728e3c1ac58SAndrey Ryabinin 
2729970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2730f16015fbSJohannes Weiner {
2731cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
2732*d2af3397SJohannes Weiner 	struct mem_cgroup *root = sc->target_mem_cgroup;
27339b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27342344d7e4SJohannes Weiner 	bool reclaimable = false;
2735694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2736*d2af3397SJohannes Weiner again:
2737d108c772SAndrey Ryabinin 	memset(&sc->nr, 0, sizeof(sc->nr));
2738d108c772SAndrey Ryabinin 
27399b4f98cdSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
27409b4f98cdSJohannes Weiner 	nr_scanned = sc->nr_scanned;
27419b4f98cdSJohannes Weiner 
27421ba6fc9aSJohannes Weiner 	memcg = mem_cgroup_iter(root, NULL, NULL);
2743694fbc0fSAndrew Morton 	do {
27448e8ae645SJohannes Weiner 		unsigned long reclaimed;
2745cb731d6cSVladimir Davydov 		unsigned long scanned;
27469b4f98cdSJohannes Weiner 
2747bf8d5d52SRoman Gushchin 		switch (mem_cgroup_protected(root, memcg)) {
2748bf8d5d52SRoman Gushchin 		case MEMCG_PROT_MIN:
2749bf8d5d52SRoman Gushchin 			/*
2750bf8d5d52SRoman Gushchin 			 * Hard protection.
2751bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2752bf8d5d52SRoman Gushchin 			 */
2753bf8d5d52SRoman Gushchin 			continue;
2754bf8d5d52SRoman Gushchin 		case MEMCG_PROT_LOW:
2755bf8d5d52SRoman Gushchin 			/*
2756bf8d5d52SRoman Gushchin 			 * Soft protection.
2757bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2758bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2759bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2760bf8d5d52SRoman Gushchin 			 */
2761d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2762d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2763241994edSJohannes Weiner 				continue;
2764d6622f63SYisheng Xie 			}
2765e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2766bf8d5d52SRoman Gushchin 			break;
2767bf8d5d52SRoman Gushchin 		case MEMCG_PROT_NONE:
27689783aa99SChris Down 			/*
27699783aa99SChris Down 			 * All protection thresholds breached. We may
27709783aa99SChris Down 			 * still choose to vary the scan pressure
27719783aa99SChris Down 			 * applied based on by how much the cgroup in
27729783aa99SChris Down 			 * question has exceeded its protection
27739783aa99SChris Down 			 * thresholds (see get_scan_count).
27749783aa99SChris Down 			 */
2775bf8d5d52SRoman Gushchin 			break;
2776241994edSJohannes Weiner 		}
2777241994edSJohannes Weiner 
27788e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2779cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2780f87bccdeSAndrey Ryabinin 		shrink_node_memcg(pgdat, memcg, sc);
2781f9be23d6SKonstantin Khlebnikov 
278228360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
278328360f39SMel Gorman 			    sc->priority);
2784cb731d6cSVladimir Davydov 
27858e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
27868e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
27878e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
27888e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
27898e8ae645SJohannes Weiner 
27901ba6fc9aSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root, memcg, NULL)));
279170ddf637SAnton Vorontsov 
27926b4f7799SJohannes Weiner 	if (reclaim_state) {
2793cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27946b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
27956b4f7799SJohannes Weiner 	}
27966b4f7799SJohannes Weiner 
27978e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
27988e8ae645SJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
279970ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
280070ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
280170ddf637SAnton Vorontsov 
28022344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
28032344d7e4SJohannes Weiner 		reclaimable = true;
28042344d7e4SJohannes Weiner 
2805e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2806d108c772SAndrey Ryabinin 		/*
2807e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2808e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2809e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2810e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2811e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2812e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2813e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2814e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2815d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2816d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2817d108c772SAndrey Ryabinin 		 *
2818e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2819e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2820e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2821e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2822d108c772SAndrey Ryabinin 		 */
2823d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2824d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2825d108c772SAndrey Ryabinin 
2826d108c772SAndrey Ryabinin 		/*
2827d108c772SAndrey Ryabinin 		 * Tag a node as congested if all the dirty pages
2828d108c772SAndrey Ryabinin 		 * scanned were backed by a congested BDI and
2829d108c772SAndrey Ryabinin 		 * wait_iff_congested will stall.
2830d108c772SAndrey Ryabinin 		 */
2831d108c772SAndrey Ryabinin 		if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2832d108c772SAndrey Ryabinin 			set_bit(PGDAT_CONGESTED, &pgdat->flags);
2833d108c772SAndrey Ryabinin 
2834d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2835d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2836d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2837d108c772SAndrey Ryabinin 
2838d108c772SAndrey Ryabinin 		/*
2839d108c772SAndrey Ryabinin 		 * If kswapd scans pages marked marked for immediate
2840d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2841d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2842d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2843d108c772SAndrey Ryabinin 		 */
2844d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2845d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2846d108c772SAndrey Ryabinin 	}
2847d108c772SAndrey Ryabinin 
2848d108c772SAndrey Ryabinin 	/*
2849e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2850e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2851e3c1ac58SAndrey Ryabinin 	 */
2852b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && writeback_throttling_sane(sc) &&
2853e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2854e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(pgdat, root, true);
2855e3c1ac58SAndrey Ryabinin 
2856e3c1ac58SAndrey Ryabinin 	/*
2857d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2858d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2859d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2860d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2861d108c772SAndrey Ryabinin 	 */
2862d108c772SAndrey Ryabinin 	if (!sc->hibernation_mode && !current_is_kswapd() &&
2863e3c1ac58SAndrey Ryabinin 	    current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2864e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2865d108c772SAndrey Ryabinin 
2866*d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2867*d2af3397SJohannes Weiner 				    sc))
2868*d2af3397SJohannes Weiner 		goto again;
28692344d7e4SJohannes Weiner 
2870c73322d0SJohannes Weiner 	/*
2871c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2872c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2873c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2874c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2875c73322d0SJohannes Weiner 	 */
2876c73322d0SJohannes Weiner 	if (reclaimable)
2877c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2878c73322d0SJohannes Weiner 
28792344d7e4SJohannes Weiner 	return reclaimable;
2880f16015fbSJohannes Weiner }
2881f16015fbSJohannes Weiner 
288253853e2dSVlastimil Babka /*
2883fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2884fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2885fdd4c614SVlastimil Babka  * should reclaim first.
288653853e2dSVlastimil Babka  */
28874f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2888fe4b1b24SMel Gorman {
288931483b6aSMel Gorman 	unsigned long watermark;
2890fdd4c614SVlastimil Babka 	enum compact_result suitable;
2891fe4b1b24SMel Gorman 
2892fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2893fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2894fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2895fdd4c614SVlastimil Babka 		return true;
2896fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2897fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2898fe4b1b24SMel Gorman 		return false;
2899fe4b1b24SMel Gorman 
2900fdd4c614SVlastimil Babka 	/*
2901fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2902fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2903fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2904fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2905fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2906fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2907fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2908fdd4c614SVlastimil Babka 	 */
2909fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2910fdd4c614SVlastimil Babka 
2911fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2912fe4b1b24SMel Gorman }
2913fe4b1b24SMel Gorman 
29141da177e4SLinus Torvalds /*
29151da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
29161da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
29171da177e4SLinus Torvalds  * request.
29181da177e4SLinus Torvalds  *
29191da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
29201da177e4SLinus Torvalds  * scan then give up on it.
29211da177e4SLinus Torvalds  */
29220a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
29231da177e4SLinus Torvalds {
2924dd1a239fSMel Gorman 	struct zoneref *z;
292554a6eb5cSMel Gorman 	struct zone *zone;
29260608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29270608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2928619d0d76SWeijie Yang 	gfp_t orig_mask;
292979dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
29301cfb419bSKAMEZAWA Hiroyuki 
2931cc715d99SMel Gorman 	/*
2932cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2933cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2934cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2935cc715d99SMel Gorman 	 */
2936619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2937b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2938cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29394f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2940b2e18757SMel Gorman 	}
2941cc715d99SMel Gorman 
2942d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2943b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2944b2e18757SMel Gorman 		/*
29451cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29461cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29471cfb419bSKAMEZAWA Hiroyuki 		 */
2948b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
2949344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2950344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29511da177e4SLinus Torvalds 				continue;
295265ec02cbSVladimir Davydov 
2953e0887c19SRik van Riel 			/*
2954e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2955e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2956e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2957e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2958e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2959c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2960c7cfa37bSCopot Alexandru 			 * page allocations.
2961e0887c19SRik van Riel 			 */
29620b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29630b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29644f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29650b06496aSJohannes Weiner 				sc->compaction_ready = true;
2966e0887c19SRik van Riel 				continue;
2967e0887c19SRik van Riel 			}
29680b06496aSJohannes Weiner 
29690608f43dSAndrew Morton 			/*
297079dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
297179dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
297279dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
297379dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
297479dafcdcSMel Gorman 			 */
297579dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
297679dafcdcSMel Gorman 				continue;
297779dafcdcSMel Gorman 
297879dafcdcSMel Gorman 			/*
29790608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29800608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29810608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29820608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29830608f43dSAndrew Morton 			 */
29840608f43dSAndrew Morton 			nr_soft_scanned = 0;
2985ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29860608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29870608f43dSAndrew Morton 						&nr_soft_scanned);
29880608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29890608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2990ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2991ac34a1a3SKAMEZAWA Hiroyuki 		}
2992d149e3b2SYing Han 
299379dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
299479dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
299579dafcdcSMel Gorman 			continue;
299679dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2997970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29981da177e4SLinus Torvalds 	}
2999e0c23279SMel Gorman 
300065ec02cbSVladimir Davydov 	/*
3001619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
3002619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3003619d0d76SWeijie Yang 	 */
3004619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
30051da177e4SLinus Torvalds }
30061da177e4SLinus Torvalds 
30072a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
30082a2e4885SJohannes Weiner {
30092a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
30102a2e4885SJohannes Weiner 
30112a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
30122a2e4885SJohannes Weiner 	do {
30132a2e4885SJohannes Weiner 		unsigned long refaults;
30142a2e4885SJohannes Weiner 		struct lruvec *lruvec;
30152a2e4885SJohannes Weiner 
3016867e5e1dSJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
3017205b20ccSJohannes Weiner 		refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
30182a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
30192a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
30202a2e4885SJohannes Weiner }
30212a2e4885SJohannes Weiner 
30221da177e4SLinus Torvalds /*
30231da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
30241da177e4SLinus Torvalds  *
30251da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
30261da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
30271da177e4SLinus Torvalds  *
30281da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
30291da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
30305b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
30315b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
30325b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
30335b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3034a41f24eaSNishanth Aravamudan  *
3035a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3036a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30371da177e4SLinus Torvalds  */
3038dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30393115cd91SVladimir Davydov 					  struct scan_control *sc)
30401da177e4SLinus Torvalds {
3041241994edSJohannes Weiner 	int initial_priority = sc->priority;
30422a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30432a2e4885SJohannes Weiner 	struct zoneref *z;
30442a2e4885SJohannes Weiner 	struct zone *zone;
3045241994edSJohannes Weiner retry:
3046873b4771SKeika Kobayashi 	delayacct_freepages_start();
3047873b4771SKeika Kobayashi 
3048b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
30497cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30501da177e4SLinus Torvalds 
30519e3b2f8cSKonstantin Khlebnikov 	do {
305270ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
305370ddf637SAnton Vorontsov 				sc->priority);
305466e1707bSBalbir Singh 		sc->nr_scanned = 0;
30550a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3056e0c23279SMel Gorman 
3057bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30580b06496aSJohannes Weiner 			break;
30590b06496aSJohannes Weiner 
30600b06496aSJohannes Weiner 		if (sc->compaction_ready)
30610b06496aSJohannes Weiner 			break;
30621da177e4SLinus Torvalds 
30631da177e4SLinus Torvalds 		/*
30640e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30650e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30660e50ce3bSMinchan Kim 		 */
30670e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30680e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30690b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3070bb21c7ceSKOSAKI Motohiro 
30712a2e4885SJohannes Weiner 	last_pgdat = NULL;
30722a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30732a2e4885SJohannes Weiner 					sc->nodemask) {
30742a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30752a2e4885SJohannes Weiner 			continue;
30762a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
30772a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3078e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
30792a2e4885SJohannes Weiner 	}
30802a2e4885SJohannes Weiner 
3081873b4771SKeika Kobayashi 	delayacct_freepages_end();
3082873b4771SKeika Kobayashi 
3083bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3084bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3085bb21c7ceSKOSAKI Motohiro 
30860cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30870b06496aSJohannes Weiner 	if (sc->compaction_ready)
30887335084dSMel Gorman 		return 1;
30897335084dSMel Gorman 
3090241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3091d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3092241994edSJohannes Weiner 		sc->priority = initial_priority;
3093d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3094d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3095241994edSJohannes Weiner 		goto retry;
3096241994edSJohannes Weiner 	}
3097241994edSJohannes Weiner 
3098bb21c7ceSKOSAKI Motohiro 	return 0;
30991da177e4SLinus Torvalds }
31001da177e4SLinus Torvalds 
3101c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
31025515061dSMel Gorman {
31035515061dSMel Gorman 	struct zone *zone;
31045515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
31055515061dSMel Gorman 	unsigned long free_pages = 0;
31065515061dSMel Gorman 	int i;
31075515061dSMel Gorman 	bool wmark_ok;
31085515061dSMel Gorman 
3109c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3110c73322d0SJohannes Weiner 		return true;
3111c73322d0SJohannes Weiner 
31125515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
31135515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3114d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3115d450abd8SJohannes Weiner 			continue;
3116d450abd8SJohannes Weiner 
3117d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3118675becceSMel Gorman 			continue;
3119675becceSMel Gorman 
31205515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
31215515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
31225515061dSMel Gorman 	}
31235515061dSMel Gorman 
3124675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3125675becceSMel Gorman 	if (!pfmemalloc_reserve)
3126675becceSMel Gorman 		return true;
3127675becceSMel Gorman 
31285515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31295515061dSMel Gorman 
31305515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31315515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
313238087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
31335515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
31345515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31355515061dSMel Gorman 	}
31365515061dSMel Gorman 
31375515061dSMel Gorman 	return wmark_ok;
31385515061dSMel Gorman }
31395515061dSMel Gorman 
31405515061dSMel Gorman /*
31415515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31425515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31435515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
314450694c28SMel Gorman  * when the low watermark is reached.
314550694c28SMel Gorman  *
314650694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
314750694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31485515061dSMel Gorman  */
314950694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31505515061dSMel Gorman 					nodemask_t *nodemask)
31515515061dSMel Gorman {
3152675becceSMel Gorman 	struct zoneref *z;
31535515061dSMel Gorman 	struct zone *zone;
3154675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31555515061dSMel Gorman 
31565515061dSMel Gorman 	/*
31575515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31585515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31595515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31605515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31615515061dSMel Gorman 	 * processes to block on log_wait_commit().
31625515061dSMel Gorman 	 */
31635515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
316450694c28SMel Gorman 		goto out;
316550694c28SMel Gorman 
316650694c28SMel Gorman 	/*
316750694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
316850694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
316950694c28SMel Gorman 	 */
317050694c28SMel Gorman 	if (fatal_signal_pending(current))
317150694c28SMel Gorman 		goto out;
31725515061dSMel Gorman 
3173675becceSMel Gorman 	/*
3174675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3175675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3176675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3177675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3178675becceSMel Gorman 	 *
3179675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3180675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3181675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3182675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3183675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3184675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3185675becceSMel Gorman 	 * should make reasonable progress.
3186675becceSMel Gorman 	 */
3187675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
318817636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3189675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3190675becceSMel Gorman 			continue;
3191675becceSMel Gorman 
3192675becceSMel Gorman 		/* Throttle based on the first usable node */
31935515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3194c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
319550694c28SMel Gorman 			goto out;
3196675becceSMel Gorman 		break;
3197675becceSMel Gorman 	}
3198675becceSMel Gorman 
3199675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3200675becceSMel Gorman 	if (!pgdat)
3201675becceSMel Gorman 		goto out;
32025515061dSMel Gorman 
320368243e76SMel Gorman 	/* Account for the throttling */
320468243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
320568243e76SMel Gorman 
32065515061dSMel Gorman 	/*
32075515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
32085515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
32095515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
32105515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
32115515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
32125515061dSMel Gorman 	 * second before continuing.
32135515061dSMel Gorman 	 */
32145515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
32155515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3216c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
321750694c28SMel Gorman 
321850694c28SMel Gorman 		goto check_pending;
32195515061dSMel Gorman 	}
32205515061dSMel Gorman 
32215515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
32225515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3223c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
322450694c28SMel Gorman 
322550694c28SMel Gorman check_pending:
322650694c28SMel Gorman 	if (fatal_signal_pending(current))
322750694c28SMel Gorman 		return true;
322850694c28SMel Gorman 
322950694c28SMel Gorman out:
323050694c28SMel Gorman 	return false;
32315515061dSMel Gorman }
32325515061dSMel Gorman 
3233dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3234327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
323566e1707bSBalbir Singh {
323633906bc5SMel Gorman 	unsigned long nr_reclaimed;
323766e1707bSBalbir Singh 	struct scan_control sc = {
323822fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3239f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3240b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3241ee814fe2SJohannes Weiner 		.order = order,
3242ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3243ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3244ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3245a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32462e2e4259SKOSAKI Motohiro 		.may_swap = 1,
324766e1707bSBalbir Singh 	};
324866e1707bSBalbir Singh 
32495515061dSMel Gorman 	/*
3250bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3251bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3252bb451fdfSGreg Thelen 	 */
3253bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3254bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3255bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3256bb451fdfSGreg Thelen 
3257bb451fdfSGreg Thelen 	/*
325850694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
325950694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
326050694c28SMel Gorman 	 * point.
32615515061dSMel Gorman 	 */
3262f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32635515061dSMel Gorman 		return 1;
32645515061dSMel Gorman 
32651732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
32663481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
326733906bc5SMel Gorman 
32683115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
326933906bc5SMel Gorman 
327033906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
32711732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
327233906bc5SMel Gorman 
327333906bc5SMel Gorman 	return nr_reclaimed;
327466e1707bSBalbir Singh }
327566e1707bSBalbir Singh 
3276c255a458SAndrew Morton #ifdef CONFIG_MEMCG
327766e1707bSBalbir Singh 
3278d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3279a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32804e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3281ef8f2327SMel Gorman 						pg_data_t *pgdat,
32820ae5e89cSYing Han 						unsigned long *nr_scanned)
32834e416953SBalbir Singh {
32844e416953SBalbir Singh 	struct scan_control sc = {
3285b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3286ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
32874e416953SBalbir Singh 		.may_writepage = !laptop_mode,
32884e416953SBalbir Singh 		.may_unmap = 1,
3289b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
32904e416953SBalbir Singh 		.may_swap = !noswap,
32914e416953SBalbir Singh 	};
32920ae5e89cSYing Han 
3293d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3294d2e5fb92SMichal Hocko 
32954e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
32964e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3297bdce6d9eSKOSAKI Motohiro 
32989e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
32993481c37fSYafang Shao 						      sc.gfp_mask);
3300bdce6d9eSKOSAKI Motohiro 
33014e416953SBalbir Singh 	/*
33024e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
33034e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3304a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
33054e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
33064e416953SBalbir Singh 	 * the priority and make it zero.
33074e416953SBalbir Singh 	 */
3308f87bccdeSAndrey Ryabinin 	shrink_node_memcg(pgdat, memcg, &sc);
3309bdce6d9eSKOSAKI Motohiro 
3310bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3311bdce6d9eSKOSAKI Motohiro 
33120ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
33130308f7cfSYafang Shao 
33144e416953SBalbir Singh 	return sc.nr_reclaimed;
33154e416953SBalbir Singh }
33164e416953SBalbir Singh 
331772835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3318b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
33198c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3320b70a2a21SJohannes Weiner 					   bool may_swap)
332166e1707bSBalbir Singh {
3322bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3323eb414681SJohannes Weiner 	unsigned long pflags;
3324499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
332566e1707bSBalbir Singh 	struct scan_control sc = {
3326b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33277dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3328ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3329b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3330ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3331ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
333266e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3333a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3334b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3335a09ed5e0SYing Han 	};
3336fa40d1eeSShakeel Butt 	/*
3337fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3338fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3339fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3340fa40d1eeSShakeel Butt 	 */
3341fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
334266e1707bSBalbir Singh 
33431732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3344bdce6d9eSKOSAKI Motohiro 
33453481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3346bdce6d9eSKOSAKI Motohiro 
3347eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3348499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3349eb414681SJohannes Weiner 
33503115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3351eb414681SJohannes Weiner 
3352499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3353eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3354bdce6d9eSKOSAKI Motohiro 
3355bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
33561732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3357bdce6d9eSKOSAKI Motohiro 
3358bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
335966e1707bSBalbir Singh }
336066e1707bSBalbir Singh #endif
336166e1707bSBalbir Singh 
33621d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3363ef8f2327SMel Gorman 				struct scan_control *sc)
3364f16015fbSJohannes Weiner {
3365b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3366b95a2f2dSJohannes Weiner 
3367b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3368b95a2f2dSJohannes Weiner 		return;
3369b95a2f2dSJohannes Weiner 
3370b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3371b95a2f2dSJohannes Weiner 	do {
3372867e5e1dSJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3373f16015fbSJohannes Weiner 
33743b991208SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, sc, true))
33751a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33769e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3377b95a2f2dSJohannes Weiner 
3378b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3379b95a2f2dSJohannes Weiner 	} while (memcg);
3380f16015fbSJohannes Weiner }
3381f16015fbSJohannes Weiner 
33821c30844dSMel Gorman static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
33831c30844dSMel Gorman {
33841c30844dSMel Gorman 	int i;
33851c30844dSMel Gorman 	struct zone *zone;
33861c30844dSMel Gorman 
33871c30844dSMel Gorman 	/*
33881c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
33891c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
33901c30844dSMel Gorman 	 * should not be checked at the time time as reclaim would
33911c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
33921c30844dSMel Gorman 	 * zone is balanced.
33931c30844dSMel Gorman 	 */
33941c30844dSMel Gorman 	for (i = classzone_idx; i >= 0; i--) {
33951c30844dSMel Gorman 		zone = pgdat->node_zones + i;
33961c30844dSMel Gorman 		if (!managed_zone(zone))
33971c30844dSMel Gorman 			continue;
33981c30844dSMel Gorman 
33991c30844dSMel Gorman 		if (zone->watermark_boost)
34001c30844dSMel Gorman 			return true;
34011c30844dSMel Gorman 	}
34021c30844dSMel Gorman 
34031c30844dSMel Gorman 	return false;
34041c30844dSMel Gorman }
34051c30844dSMel Gorman 
3406e716f2ebSMel Gorman /*
3407e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3408e716f2ebSMel Gorman  * and classzone_idx
3409e716f2ebSMel Gorman  */
3410e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
341160cefed4SJohannes Weiner {
3412e716f2ebSMel Gorman 	int i;
3413e716f2ebSMel Gorman 	unsigned long mark = -1;
3414e716f2ebSMel Gorman 	struct zone *zone;
341560cefed4SJohannes Weiner 
34161c30844dSMel Gorman 	/*
34171c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
34181c30844dSMel Gorman 	 * meet watermarks.
34191c30844dSMel Gorman 	 */
3420e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3421e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
34226256c6b4SMel Gorman 
3423e716f2ebSMel Gorman 		if (!managed_zone(zone))
3424e716f2ebSMel Gorman 			continue;
3425e716f2ebSMel Gorman 
3426e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3427e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
34286256c6b4SMel Gorman 			return true;
342960cefed4SJohannes Weiner 	}
343060cefed4SJohannes Weiner 
3431e716f2ebSMel Gorman 	/*
3432e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3433e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3434e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3435e716f2ebSMel Gorman 	 */
3436e716f2ebSMel Gorman 	if (mark == -1)
3437e716f2ebSMel Gorman 		return true;
3438e716f2ebSMel Gorman 
3439e716f2ebSMel Gorman 	return false;
3440e716f2ebSMel Gorman }
3441e716f2ebSMel Gorman 
3442631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3443631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3444631b6e08SMel Gorman {
3445631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3446631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3447631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3448631b6e08SMel Gorman }
3449631b6e08SMel Gorman 
34501741c877SMel Gorman /*
34515515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34525515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34535515061dSMel Gorman  *
34545515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34555515061dSMel Gorman  */
3456d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3457f50de2d3SMel Gorman {
34585515061dSMel Gorman 	/*
34599e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3460c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34619e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34629e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34639e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34649e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34659e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34669e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34679e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34689e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34699e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34705515061dSMel Gorman 	 */
34719e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
34729e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3473f50de2d3SMel Gorman 
3474c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3475c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3476c73322d0SJohannes Weiner 		return true;
3477c73322d0SJohannes Weiner 
3478e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3479631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3480333b0a45SShantanu Goel 		return true;
34811d82de61SMel Gorman 	}
34821d82de61SMel Gorman 
3483333b0a45SShantanu Goel 	return false;
3484f50de2d3SMel Gorman }
3485f50de2d3SMel Gorman 
34861da177e4SLinus Torvalds /*
34871d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
34881d82de61SMel Gorman  * zone that is currently unbalanced.
3489b8e83b94SMel Gorman  *
3490b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3491283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3492283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
349375485363SMel Gorman  */
34941d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3495accf6242SVlastimil Babka 			       struct scan_control *sc)
349675485363SMel Gorman {
34971d82de61SMel Gorman 	struct zone *zone;
34981d82de61SMel Gorman 	int z;
349975485363SMel Gorman 
35001d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
35011d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3502970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
35031d82de61SMel Gorman 		zone = pgdat->node_zones + z;
35046aa303deSMel Gorman 		if (!managed_zone(zone))
35051d82de61SMel Gorman 			continue;
35067c954f6dSMel Gorman 
35071d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
35087c954f6dSMel Gorman 	}
35097c954f6dSMel Gorman 
35101d82de61SMel Gorman 	/*
35111d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
35121d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
35131d82de61SMel Gorman 	 */
3514970a39a3SMel Gorman 	shrink_node(pgdat, sc);
35151d82de61SMel Gorman 
35161d82de61SMel Gorman 	/*
35171d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
35181d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
35191d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
35201d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
35211d82de61SMel Gorman 	 * can direct reclaim/compact.
35221d82de61SMel Gorman 	 */
35239861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
35241d82de61SMel Gorman 		sc->order = 0;
35251d82de61SMel Gorman 
3526b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
352775485363SMel Gorman }
352875485363SMel Gorman 
352975485363SMel Gorman /*
35301d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35311d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35321d82de61SMel Gorman  * balanced.
35331da177e4SLinus Torvalds  *
35341d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35351da177e4SLinus Torvalds  *
35361da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
353741858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35388bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
35391d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35401d82de61SMel Gorman  * balanced.
35411da177e4SLinus Torvalds  */
3542accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
35431da177e4SLinus Torvalds {
35441da177e4SLinus Torvalds 	int i;
35450608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35460608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3547eb414681SJohannes Weiner 	unsigned long pflags;
35481c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
35491c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
35501c30844dSMel Gorman 	bool boosted;
35511d82de61SMel Gorman 	struct zone *zone;
3552179e9639SAndrew Morton 	struct scan_control sc = {
3553179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3554ee814fe2SJohannes Weiner 		.order = order,
3555a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3556179e9639SAndrew Morton 	};
355793781325SOmar Sandoval 
35581732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3559eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
356093781325SOmar Sandoval 	__fs_reclaim_acquire();
356193781325SOmar Sandoval 
3562f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35631da177e4SLinus Torvalds 
35641c30844dSMel Gorman 	/*
35651c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
35661c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
35671c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
35681c30844dSMel Gorman 	 */
35691c30844dSMel Gorman 	nr_boost_reclaim = 0;
35701c30844dSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
35711c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35721c30844dSMel Gorman 		if (!managed_zone(zone))
35731c30844dSMel Gorman 			continue;
35741c30844dSMel Gorman 
35751c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
35761c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
35771c30844dSMel Gorman 	}
35781c30844dSMel Gorman 	boosted = nr_boost_reclaim;
35791c30844dSMel Gorman 
35801c30844dSMel Gorman restart:
35811c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
35829e3b2f8cSKonstantin Khlebnikov 	do {
3583c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3584b8e83b94SMel Gorman 		bool raise_priority = true;
35851c30844dSMel Gorman 		bool balanced;
358693781325SOmar Sandoval 		bool ret;
3587b8e83b94SMel Gorman 
358884c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
35891da177e4SLinus Torvalds 
359086c79f6bSMel Gorman 		/*
359184c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
359284c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
359384c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
359484c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
359584c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
359684c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
359784c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
359884c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
359986c79f6bSMel Gorman 		 */
360086c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
360186c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
360286c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
36036aa303deSMel Gorman 				if (!managed_zone(zone))
360486c79f6bSMel Gorman 					continue;
360586c79f6bSMel Gorman 
3606970a39a3SMel Gorman 				sc.reclaim_idx = i;
360786c79f6bSMel Gorman 				break;
360886c79f6bSMel Gorman 			}
360986c79f6bSMel Gorman 		}
361086c79f6bSMel Gorman 
361186c79f6bSMel Gorman 		/*
36121c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
36131c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
36141c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
36151c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
36161c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
361786c79f6bSMel Gorman 		 */
36181c30844dSMel Gorman 		balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
36191c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
36201c30844dSMel Gorman 			nr_boost_reclaim = 0;
36211c30844dSMel Gorman 			goto restart;
36221c30844dSMel Gorman 		}
36231c30844dSMel Gorman 
36241c30844dSMel Gorman 		/*
36251c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
36261c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
36271c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
36281c30844dSMel Gorman 		 */
36291c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
36301da177e4SLinus Torvalds 			goto out;
3631e1dbeda6SAndrew Morton 
36321c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
36331c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
36341c30844dSMel Gorman 			raise_priority = false;
36351c30844dSMel Gorman 
36361c30844dSMel Gorman 		/*
36371c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
36381c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
36391c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
36401c30844dSMel Gorman 		 * reclaim will be aborted.
36411c30844dSMel Gorman 		 */
36421c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
36431c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
36441c30844dSMel Gorman 
36451da177e4SLinus Torvalds 		/*
36461d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
36471d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
36481d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
36491d82de61SMel Gorman 		 * about consistent aging.
36501d82de61SMel Gorman 		 */
3651ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
36521d82de61SMel Gorman 
36531d82de61SMel Gorman 		/*
3654b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3655b7ea3c41SMel Gorman 		 * even in laptop mode.
3656b7ea3c41SMel Gorman 		 */
3657047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3658b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3659b7ea3c41SMel Gorman 
36601d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
36611da177e4SLinus Torvalds 		sc.nr_scanned = 0;
36620608f43dSAndrew Morton 		nr_soft_scanned = 0;
3663ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
36641d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
36650608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
36660608f43dSAndrew Morton 
366732a4330dSRik van Riel 		/*
36681d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
36691d82de61SMel Gorman 		 * enough pages are already being scanned that that high
36701d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
367132a4330dSRik van Riel 		 */
3672970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3673b8e83b94SMel Gorman 			raise_priority = false;
3674d7868daeSMel Gorman 
36755515061dSMel Gorman 		/*
36765515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
36775515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
36785515061dSMel Gorman 		 * able to safely make forward progress. Wake them
36795515061dSMel Gorman 		 */
36805515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3681c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3682cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
36835515061dSMel Gorman 
3684b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
368593781325SOmar Sandoval 		__fs_reclaim_release();
368693781325SOmar Sandoval 		ret = try_to_freeze();
368793781325SOmar Sandoval 		__fs_reclaim_acquire();
368893781325SOmar Sandoval 		if (ret || kthread_should_stop())
3689b8e83b94SMel Gorman 			break;
3690b8e83b94SMel Gorman 
3691b8e83b94SMel Gorman 		/*
3692b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3693b8e83b94SMel Gorman 		 * progress in reclaiming pages
3694b8e83b94SMel Gorman 		 */
3695c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
36961c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
36971c30844dSMel Gorman 
36981c30844dSMel Gorman 		/*
36991c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
37001c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
37011c30844dSMel Gorman 		 * extreme circumstances.
37021c30844dSMel Gorman 		 */
37031c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
37041c30844dSMel Gorman 			break;
37051c30844dSMel Gorman 
3706c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3707b8e83b94SMel Gorman 			sc.priority--;
37081d82de61SMel Gorman 	} while (sc.priority >= 1);
37091da177e4SLinus Torvalds 
3710c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3711c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3712c73322d0SJohannes Weiner 
3713b8e83b94SMel Gorman out:
37141c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
37151c30844dSMel Gorman 	if (boosted) {
37161c30844dSMel Gorman 		unsigned long flags;
37171c30844dSMel Gorman 
37181c30844dSMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
37191c30844dSMel Gorman 			if (!zone_boosts[i])
37201c30844dSMel Gorman 				continue;
37211c30844dSMel Gorman 
37221c30844dSMel Gorman 			/* Increments are under the zone lock */
37231c30844dSMel Gorman 			zone = pgdat->node_zones + i;
37241c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
37251c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
37261c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
37271c30844dSMel Gorman 		}
37281c30844dSMel Gorman 
37291c30844dSMel Gorman 		/*
37301c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
37311c30844dSMel Gorman 		 * pageblocks.
37321c30844dSMel Gorman 		 */
37331c30844dSMel Gorman 		wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
37341c30844dSMel Gorman 	}
37351c30844dSMel Gorman 
37362a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
373793781325SOmar Sandoval 	__fs_reclaim_release();
3738eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
37391732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3740e5ca8071SYafang Shao 
37410abdee2bSMel Gorman 	/*
37421d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
37431d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
37441d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
37451d82de61SMel Gorman 	 * remain at the higher level.
37460abdee2bSMel Gorman 	 */
37471d82de61SMel Gorman 	return sc.order;
37481da177e4SLinus Torvalds }
37491da177e4SLinus Torvalds 
3750e716f2ebSMel Gorman /*
3751dffcac2cSShakeel Butt  * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3752dffcac2cSShakeel Butt  * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3753dffcac2cSShakeel Butt  * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3754dffcac2cSShakeel Butt  * after previous reclaim attempt (node is still unbalanced). In that case
3755dffcac2cSShakeel Butt  * return the zone index of the previous kswapd reclaim cycle.
3756e716f2ebSMel Gorman  */
3757e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3758dffcac2cSShakeel Butt 					   enum zone_type prev_classzone_idx)
3759e716f2ebSMel Gorman {
3760e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3761dffcac2cSShakeel Butt 		return prev_classzone_idx;
3762dffcac2cSShakeel Butt 	return pgdat->kswapd_classzone_idx;
3763e716f2ebSMel Gorman }
3764e716f2ebSMel Gorman 
376538087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
376638087d9bSMel Gorman 				unsigned int classzone_idx)
3767f0bc0a60SKOSAKI Motohiro {
3768f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3769f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3770f0bc0a60SKOSAKI Motohiro 
3771f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3772f0bc0a60SKOSAKI Motohiro 		return;
3773f0bc0a60SKOSAKI Motohiro 
3774f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3775f0bc0a60SKOSAKI Motohiro 
3776333b0a45SShantanu Goel 	/*
3777333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3778333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3779333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3780333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3781333b0a45SShantanu Goel 	 * succeed.
3782333b0a45SShantanu Goel 	 */
3783d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3784fd901c95SVlastimil Babka 		/*
3785fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3786fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3787fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3788fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3789fd901c95SVlastimil Babka 		 */
3790fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3791fd901c95SVlastimil Babka 
3792fd901c95SVlastimil Babka 		/*
3793fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3794fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3795fd901c95SVlastimil Babka 		 */
379638087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3797fd901c95SVlastimil Babka 
3798f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
379938087d9bSMel Gorman 
380038087d9bSMel Gorman 		/*
380138087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
380238087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
380338087d9bSMel Gorman 		 * the previous request that slept prematurely.
380438087d9bSMel Gorman 		 */
380538087d9bSMel Gorman 		if (remaining) {
3806e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
380738087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
380838087d9bSMel Gorman 		}
380938087d9bSMel Gorman 
3810f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3811f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3812f0bc0a60SKOSAKI Motohiro 	}
3813f0bc0a60SKOSAKI Motohiro 
3814f0bc0a60SKOSAKI Motohiro 	/*
3815f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3816f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3817f0bc0a60SKOSAKI Motohiro 	 */
3818d9f21d42SMel Gorman 	if (!remaining &&
3819d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3820f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3821f0bc0a60SKOSAKI Motohiro 
3822f0bc0a60SKOSAKI Motohiro 		/*
3823f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3824f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3825f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3826f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3827f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3828f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3829f0bc0a60SKOSAKI Motohiro 		 */
3830f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
38311c7e7f6cSAaditya Kumar 
38321c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3833f0bc0a60SKOSAKI Motohiro 			schedule();
38341c7e7f6cSAaditya Kumar 
3835f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3836f0bc0a60SKOSAKI Motohiro 	} else {
3837f0bc0a60SKOSAKI Motohiro 		if (remaining)
3838f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3839f0bc0a60SKOSAKI Motohiro 		else
3840f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3841f0bc0a60SKOSAKI Motohiro 	}
3842f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3843f0bc0a60SKOSAKI Motohiro }
3844f0bc0a60SKOSAKI Motohiro 
38451da177e4SLinus Torvalds /*
38461da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
38471da177e4SLinus Torvalds  * from the init process.
38481da177e4SLinus Torvalds  *
38491da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
38501da177e4SLinus Torvalds  * free memory available even if there is no other activity
38511da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
38521da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
38531da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
38541da177e4SLinus Torvalds  *
38551da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
38561da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
38571da177e4SLinus Torvalds  */
38581da177e4SLinus Torvalds static int kswapd(void *p)
38591da177e4SLinus Torvalds {
3860e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3861e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
38621da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
38631da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3864a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
38651da177e4SLinus Torvalds 
3866174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3867c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
38681da177e4SLinus Torvalds 
38691da177e4SLinus Torvalds 	/*
38701da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
38711da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
38721da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
38731da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
38741da177e4SLinus Torvalds 	 *
38751da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
38761da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
38771da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
38781da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
38791da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
38801da177e4SLinus Torvalds 	 */
3881930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
388283144186SRafael J. Wysocki 	set_freezable();
38831da177e4SLinus Torvalds 
3884e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3885e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
38861da177e4SLinus Torvalds 	for ( ; ; ) {
38876f6313d4SJeff Liu 		bool ret;
38883e1d1d28SChristoph Lameter 
3889e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3890e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3891e716f2ebSMel Gorman 
389238087d9bSMel Gorman kswapd_try_sleep:
389338087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
389438087d9bSMel Gorman 					classzone_idx);
3895215ddd66SMel Gorman 
389638087d9bSMel Gorman 		/* Read the new order and classzone_idx */
389738087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3898dffcac2cSShakeel Butt 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
389938087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3900e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
39011da177e4SLinus Torvalds 
39028fe23e05SDavid Rientjes 		ret = try_to_freeze();
39038fe23e05SDavid Rientjes 		if (kthread_should_stop())
39048fe23e05SDavid Rientjes 			break;
39058fe23e05SDavid Rientjes 
39068fe23e05SDavid Rientjes 		/*
39078fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
39088fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3909b1296cc4SRafael J. Wysocki 		 */
391038087d9bSMel Gorman 		if (ret)
391138087d9bSMel Gorman 			continue;
39121d82de61SMel Gorman 
391338087d9bSMel Gorman 		/*
391438087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
391538087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
391638087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
391738087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
391838087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
391938087d9bSMel Gorman 		 * request (alloc_order).
392038087d9bSMel Gorman 		 */
3921e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3922e5146b12SMel Gorman 						alloc_order);
392338087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
392438087d9bSMel Gorman 		if (reclaim_order < alloc_order)
392538087d9bSMel Gorman 			goto kswapd_try_sleep;
392633906bc5SMel Gorman 	}
3927b0a8cc58STakamori Yamaguchi 
392871abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
392971abdc15SJohannes Weiner 
39301da177e4SLinus Torvalds 	return 0;
39311da177e4SLinus Torvalds }
39321da177e4SLinus Torvalds 
39331da177e4SLinus Torvalds /*
39345ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
39355ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
39365ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
39375ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
39385ecd9d40SDavid Rientjes  * needed.
39391da177e4SLinus Torvalds  */
39405ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
39415ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
39421da177e4SLinus Torvalds {
39431da177e4SLinus Torvalds 	pg_data_t *pgdat;
39441da177e4SLinus Torvalds 
39456aa303deSMel Gorman 	if (!managed_zone(zone))
39461da177e4SLinus Torvalds 		return;
39471da177e4SLinus Torvalds 
39485ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
39491da177e4SLinus Torvalds 		return;
395088f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3951dffcac2cSShakeel Butt 
3952dffcac2cSShakeel Butt 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3953dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = classzone_idx;
3954dffcac2cSShakeel Butt 	else
3955dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3956e716f2ebSMel Gorman 						  classzone_idx);
395738087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
39588d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
39591da177e4SLinus Torvalds 		return;
3960e1a55637SMel Gorman 
39615ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
39625ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
39631c30844dSMel Gorman 	    (pgdat_balanced(pgdat, order, classzone_idx) &&
39641c30844dSMel Gorman 	     !pgdat_watermark_boosted(pgdat, classzone_idx))) {
39655ecd9d40SDavid Rientjes 		/*
39665ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
39675ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
39685ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
39695ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
39705ecd9d40SDavid Rientjes 		 * ratelimit its work.
39715ecd9d40SDavid Rientjes 		 */
39725ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
39735ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3974c73322d0SJohannes Weiner 		return;
39755ecd9d40SDavid Rientjes 	}
3976c73322d0SJohannes Weiner 
39775ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
39785ecd9d40SDavid Rientjes 				      gfp_flags);
39798d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
39801da177e4SLinus Torvalds }
39811da177e4SLinus Torvalds 
3982c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
39831da177e4SLinus Torvalds /*
39847b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3985d6277db4SRafael J. Wysocki  * freed pages.
3986d6277db4SRafael J. Wysocki  *
3987d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3988d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3989d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
39901da177e4SLinus Torvalds  */
39917b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
39921da177e4SLinus Torvalds {
3993d6277db4SRafael J. Wysocki 	struct scan_control sc = {
39947b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3995ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3996b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
39979e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3998ee814fe2SJohannes Weiner 		.may_writepage = 1,
3999ee814fe2SJohannes Weiner 		.may_unmap = 1,
4000ee814fe2SJohannes Weiner 		.may_swap = 1,
4001ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
40021da177e4SLinus Torvalds 	};
40037b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
40047b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4005499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
40061da177e4SLinus Torvalds 
4007d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
400893781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
40091732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4010d6277db4SRafael J. Wysocki 
40113115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4012d6277db4SRafael J. Wysocki 
40131732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4014499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
401593781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4016d6277db4SRafael J. Wysocki 
40177b51755cSKOSAKI Motohiro 	return nr_reclaimed;
40181da177e4SLinus Torvalds }
4019c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
40201da177e4SLinus Torvalds 
40211da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
40221da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
40231da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
40241da177e4SLinus Torvalds    restore their cpu bindings. */
4025517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
40261da177e4SLinus Torvalds {
402758c0a4a7SYasunori Goto 	int nid;
40281da177e4SLinus Torvalds 
402948fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
4030c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
4031a70f7302SRusty Russell 		const struct cpumask *mask;
4032a70f7302SRusty Russell 
4033a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
4034c5f59f08SMike Travis 
40353e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
40361da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
4037c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
40381da177e4SLinus Torvalds 	}
4039517bbed9SSebastian Andrzej Siewior 	return 0;
40401da177e4SLinus Torvalds }
40411da177e4SLinus Torvalds 
40423218ae14SYasunori Goto /*
40433218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
40443218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
40453218ae14SYasunori Goto  */
40463218ae14SYasunori Goto int kswapd_run(int nid)
40473218ae14SYasunori Goto {
40483218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
40493218ae14SYasunori Goto 	int ret = 0;
40503218ae14SYasunori Goto 
40513218ae14SYasunori Goto 	if (pgdat->kswapd)
40523218ae14SYasunori Goto 		return 0;
40533218ae14SYasunori Goto 
40543218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
40553218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
40563218ae14SYasunori Goto 		/* failure at boot is fatal */
4057c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4058d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4059d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4060d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
40613218ae14SYasunori Goto 	}
40623218ae14SYasunori Goto 	return ret;
40633218ae14SYasunori Goto }
40643218ae14SYasunori Goto 
40658fe23e05SDavid Rientjes /*
4066d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4067bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
40688fe23e05SDavid Rientjes  */
40698fe23e05SDavid Rientjes void kswapd_stop(int nid)
40708fe23e05SDavid Rientjes {
40718fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
40728fe23e05SDavid Rientjes 
4073d8adde17SJiang Liu 	if (kswapd) {
40748fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4075d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4076d8adde17SJiang Liu 	}
40778fe23e05SDavid Rientjes }
40788fe23e05SDavid Rientjes 
40791da177e4SLinus Torvalds static int __init kswapd_init(void)
40801da177e4SLinus Torvalds {
4081517bbed9SSebastian Andrzej Siewior 	int nid, ret;
408269e05944SAndrew Morton 
40831da177e4SLinus Torvalds 	swap_setup();
408448fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
40853218ae14SYasunori Goto  		kswapd_run(nid);
4086517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4087517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
4088517bbed9SSebastian Andrzej Siewior 					NULL);
4089517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
40901da177e4SLinus Torvalds 	return 0;
40911da177e4SLinus Torvalds }
40921da177e4SLinus Torvalds 
40931da177e4SLinus Torvalds module_init(kswapd_init)
40949eeff239SChristoph Lameter 
40959eeff239SChristoph Lameter #ifdef CONFIG_NUMA
40969eeff239SChristoph Lameter /*
4097a5f5f91dSMel Gorman  * Node reclaim mode
40989eeff239SChristoph Lameter  *
4099a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
41009eeff239SChristoph Lameter  * the watermarks.
41019eeff239SChristoph Lameter  */
4102a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
41039eeff239SChristoph Lameter 
41041b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
41057d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
41061b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
410795bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
41081b2ffb78SChristoph Lameter 
41099eeff239SChristoph Lameter /*
4110a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4111a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4112a92f7126SChristoph Lameter  * a zone.
4113a92f7126SChristoph Lameter  */
4114a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4115a92f7126SChristoph Lameter 
41169eeff239SChristoph Lameter /*
4117a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
41189614634fSChristoph Lameter  * occur.
41199614634fSChristoph Lameter  */
41209614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
41219614634fSChristoph Lameter 
41229614634fSChristoph Lameter /*
41230ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
41240ff38490SChristoph Lameter  * slab reclaim needs to occur.
41250ff38490SChristoph Lameter  */
41260ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
41270ff38490SChristoph Lameter 
412811fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
412990afa5deSMel Gorman {
413011fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
413111fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
413211fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
413390afa5deSMel Gorman 
413490afa5deSMel Gorman 	/*
413590afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
413690afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
413790afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
413890afa5deSMel Gorman 	 */
413990afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
414090afa5deSMel Gorman }
414190afa5deSMel Gorman 
414290afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4143a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
414490afa5deSMel Gorman {
4145d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4146d031a157SAlexandru Moise 	unsigned long delta = 0;
414790afa5deSMel Gorman 
414890afa5deSMel Gorman 	/*
414995bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
415090afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
415111fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
415290afa5deSMel Gorman 	 * a better estimate
415390afa5deSMel Gorman 	 */
4154a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4155a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
415690afa5deSMel Gorman 	else
4157a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
415890afa5deSMel Gorman 
415990afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4160a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4161a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
416290afa5deSMel Gorman 
416390afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
416490afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
416590afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
416690afa5deSMel Gorman 
416790afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
416890afa5deSMel Gorman }
416990afa5deSMel Gorman 
41700ff38490SChristoph Lameter /*
4171a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
41729eeff239SChristoph Lameter  */
4173a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
41749eeff239SChristoph Lameter {
41757fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
417669e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
41779eeff239SChristoph Lameter 	struct task_struct *p = current;
4178499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4179179e9639SAndrew Morton 	struct scan_control sc = {
418062b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4181f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4182bd2f6199SJohannes Weiner 		.order = order,
4183a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4184a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4185a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4186ee814fe2SJohannes Weiner 		.may_swap = 1,
4187f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4188179e9639SAndrew Morton 	};
41899eeff239SChristoph Lameter 
4190132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4191132bb8cfSYafang Shao 					   sc.gfp_mask);
4192132bb8cfSYafang Shao 
41939eeff239SChristoph Lameter 	cond_resched();
419493781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4195d4f7796eSChristoph Lameter 	/*
419695bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4197d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
419895bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4199d4f7796eSChristoph Lameter 	 */
4200499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4201499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
42021732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4203c84db23cSChristoph Lameter 
4204a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4205a92f7126SChristoph Lameter 		/*
4206894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
42070ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4208a92f7126SChristoph Lameter 		 */
4209a92f7126SChristoph Lameter 		do {
4210970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
42119e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
42120ff38490SChristoph Lameter 	}
4213a92f7126SChristoph Lameter 
42141732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4215499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4216499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
421793781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4218132bb8cfSYafang Shao 
4219132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4220132bb8cfSYafang Shao 
4221a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
42229eeff239SChristoph Lameter }
4223179e9639SAndrew Morton 
4224a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4225179e9639SAndrew Morton {
4226d773ed6bSDavid Rientjes 	int ret;
4227179e9639SAndrew Morton 
4228179e9639SAndrew Morton 	/*
4229a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
42300ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
423134aa1330SChristoph Lameter 	 *
42329614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
42339614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4234a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4235a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
42369614634fSChristoph Lameter 	 * unmapped file backed pages.
4237179e9639SAndrew Morton 	 */
4238a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4239385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4240a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4241179e9639SAndrew Morton 
4242179e9639SAndrew Morton 	/*
4243d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4244179e9639SAndrew Morton 	 */
4245d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4246a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4247179e9639SAndrew Morton 
4248179e9639SAndrew Morton 	/*
4249a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4250179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4251179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4252179e9639SAndrew Morton 	 * as wide as possible.
4253179e9639SAndrew Morton 	 */
4254a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4255a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4256d773ed6bSDavid Rientjes 
4257a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4258a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4259fa5e084eSMel Gorman 
4260a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4261a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4262d773ed6bSDavid Rientjes 
426324cf7251SMel Gorman 	if (!ret)
426424cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
426524cf7251SMel Gorman 
4266d773ed6bSDavid Rientjes 	return ret;
4267179e9639SAndrew Morton }
42689eeff239SChristoph Lameter #endif
4269894bc310SLee Schermerhorn 
4270894bc310SLee Schermerhorn /*
4271894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4272894bc310SLee Schermerhorn  * @page: the page to test
4273894bc310SLee Schermerhorn  *
4274894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
427539b5f29aSHugh Dickins  * lists vs unevictable list.
4276894bc310SLee Schermerhorn  *
4277894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4278ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4279b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4280ba9ddf49SLee Schermerhorn  *
4281894bc310SLee Schermerhorn  */
428239b5f29aSHugh Dickins int page_evictable(struct page *page)
4283894bc310SLee Schermerhorn {
4284e92bb4ddSHuang Ying 	int ret;
4285e92bb4ddSHuang Ying 
4286e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4287e92bb4ddSHuang Ying 	rcu_read_lock();
4288e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4289e92bb4ddSHuang Ying 	rcu_read_unlock();
4290e92bb4ddSHuang Ying 	return ret;
4291894bc310SLee Schermerhorn }
429289e004eaSLee Schermerhorn 
429389e004eaSLee Schermerhorn /**
429464e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
429564e3d12fSKuo-Hsin Yang  * appropriate zone lru list
429664e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
429789e004eaSLee Schermerhorn  *
429864e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
429964e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
430064e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
430189e004eaSLee Schermerhorn  */
430264e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
430389e004eaSLee Schermerhorn {
4304925b7673SJohannes Weiner 	struct lruvec *lruvec;
4305785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
430624513264SHugh Dickins 	int pgscanned = 0;
430724513264SHugh Dickins 	int pgrescued = 0;
430889e004eaSLee Schermerhorn 	int i;
430989e004eaSLee Schermerhorn 
431064e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
431164e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4312785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
431389e004eaSLee Schermerhorn 
431424513264SHugh Dickins 		pgscanned++;
4315785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4316785b99feSMel Gorman 			if (pgdat)
4317785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4318785b99feSMel Gorman 			pgdat = pagepgdat;
4319785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
432089e004eaSLee Schermerhorn 		}
4321785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
432289e004eaSLee Schermerhorn 
432324513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
432424513264SHugh Dickins 			continue;
432589e004eaSLee Schermerhorn 
432639b5f29aSHugh Dickins 		if (page_evictable(page)) {
432724513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
432824513264SHugh Dickins 
4329309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
433024513264SHugh Dickins 			ClearPageUnevictable(page);
4331fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4332fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
433324513264SHugh Dickins 			pgrescued++;
433489e004eaSLee Schermerhorn 		}
433589e004eaSLee Schermerhorn 	}
433624513264SHugh Dickins 
4337785b99feSMel Gorman 	if (pgdat) {
433824513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
433924513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4340785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
434124513264SHugh Dickins 	}
434285046579SHugh Dickins }
434364e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4344