xref: /openbmc/linux/mm/vmscan.c (revision aeed1d325d429ac9699c4bf62d17156d60905519)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/vmscan.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
81da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
91da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
101da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
111da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
121da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16b1de0d13SMitchel Humpherys 
171da177e4SLinus Torvalds #include <linux/mm.h>
185b3cc15aSIngo Molnar #include <linux/sched/mm.h>
191da177e4SLinus Torvalds #include <linux/module.h>
205a0e3ad6STejun Heo #include <linux/gfp.h>
211da177e4SLinus Torvalds #include <linux/kernel_stat.h>
221da177e4SLinus Torvalds #include <linux/swap.h>
231da177e4SLinus Torvalds #include <linux/pagemap.h>
241da177e4SLinus Torvalds #include <linux/init.h>
251da177e4SLinus Torvalds #include <linux/highmem.h>
2670ddf637SAnton Vorontsov #include <linux/vmpressure.h>
27e129b5c2SAndrew Morton #include <linux/vmstat.h>
281da177e4SLinus Torvalds #include <linux/file.h>
291da177e4SLinus Torvalds #include <linux/writeback.h>
301da177e4SLinus Torvalds #include <linux/blkdev.h>
311da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
321da177e4SLinus Torvalds 					buffer_heads_over_limit */
331da177e4SLinus Torvalds #include <linux/mm_inline.h>
341da177e4SLinus Torvalds #include <linux/backing-dev.h>
351da177e4SLinus Torvalds #include <linux/rmap.h>
361da177e4SLinus Torvalds #include <linux/topology.h>
371da177e4SLinus Torvalds #include <linux/cpu.h>
381da177e4SLinus Torvalds #include <linux/cpuset.h>
393e7d3449SMel Gorman #include <linux/compaction.h>
401da177e4SLinus Torvalds #include <linux/notifier.h>
411da177e4SLinus Torvalds #include <linux/rwsem.h>
42248a0301SRafael J. Wysocki #include <linux/delay.h>
433218ae14SYasunori Goto #include <linux/kthread.h>
447dfb7103SNigel Cunningham #include <linux/freezer.h>
4566e1707bSBalbir Singh #include <linux/memcontrol.h>
46873b4771SKeika Kobayashi #include <linux/delayacct.h>
47af936a16SLee Schermerhorn #include <linux/sysctl.h>
48929bea7cSKOSAKI Motohiro #include <linux/oom.h>
49268bb0ceSLinus Torvalds #include <linux/prefetch.h>
50b1de0d13SMitchel Humpherys #include <linux/printk.h>
51f9fe48beSRoss Zwisler #include <linux/dax.h>
521da177e4SLinus Torvalds 
531da177e4SLinus Torvalds #include <asm/tlbflush.h>
541da177e4SLinus Torvalds #include <asm/div64.h>
551da177e4SLinus Torvalds 
561da177e4SLinus Torvalds #include <linux/swapops.h>
57117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
581da177e4SLinus Torvalds 
590f8053a5SNick Piggin #include "internal.h"
600f8053a5SNick Piggin 
6133906bc5SMel Gorman #define CREATE_TRACE_POINTS
6233906bc5SMel Gorman #include <trace/events/vmscan.h>
6333906bc5SMel Gorman 
641da177e4SLinus Torvalds struct scan_control {
6522fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6622fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6722fba335SKOSAKI Motohiro 
68ee814fe2SJohannes Weiner 	/*
69ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
70ee814fe2SJohannes Weiner 	 * are scanned.
71ee814fe2SJohannes Weiner 	 */
72ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
739e3b2f8cSKonstantin Khlebnikov 
745f53e762SKOSAKI Motohiro 	/*
75f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
76f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
77f16015fbSJohannes Weiner 	 */
78f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
7966e1707bSBalbir Singh 
801276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
81ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
82ee814fe2SJohannes Weiner 
83ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
84ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
85ee814fe2SJohannes Weiner 
86ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
87ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
88ee814fe2SJohannes Weiner 
89d6622f63SYisheng Xie 	/*
90d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
91d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
92d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
93d6622f63SYisheng Xie 	 */
94d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
95d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
96241994edSJohannes Weiner 
97ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
98ee814fe2SJohannes Weiner 
99ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
100ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
101ee814fe2SJohannes Weiner 
102bb451fdfSGreg Thelen 	/* Allocation order */
103bb451fdfSGreg Thelen 	s8 order;
104bb451fdfSGreg Thelen 
105bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
106bb451fdfSGreg Thelen 	s8 priority;
107bb451fdfSGreg Thelen 
108bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
109bb451fdfSGreg Thelen 	s8 reclaim_idx;
110bb451fdfSGreg Thelen 
111bb451fdfSGreg Thelen 	/* This context's GFP mask */
112bb451fdfSGreg Thelen 	gfp_t gfp_mask;
113bb451fdfSGreg Thelen 
114ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
115ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
116ee814fe2SJohannes Weiner 
117ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
118ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
119d108c772SAndrey Ryabinin 
120d108c772SAndrey Ryabinin 	struct {
121d108c772SAndrey Ryabinin 		unsigned int dirty;
122d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
123d108c772SAndrey Ryabinin 		unsigned int congested;
124d108c772SAndrey Ryabinin 		unsigned int writeback;
125d108c772SAndrey Ryabinin 		unsigned int immediate;
126d108c772SAndrey Ryabinin 		unsigned int file_taken;
127d108c772SAndrey Ryabinin 		unsigned int taken;
128d108c772SAndrey Ryabinin 	} nr;
1291da177e4SLinus Torvalds };
1301da177e4SLinus Torvalds 
1311da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1321da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1331da177e4SLinus Torvalds 	do {								\
1341da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1351da177e4SLinus Torvalds 			struct page *prev;				\
1361da177e4SLinus Torvalds 									\
1371da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1381da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1391da177e4SLinus Torvalds 		}							\
1401da177e4SLinus Torvalds 	} while (0)
1411da177e4SLinus Torvalds #else
1421da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1431da177e4SLinus Torvalds #endif
1441da177e4SLinus Torvalds 
1451da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1461da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1471da177e4SLinus Torvalds 	do {								\
1481da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1491da177e4SLinus Torvalds 			struct page *prev;				\
1501da177e4SLinus Torvalds 									\
1511da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1521da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1531da177e4SLinus Torvalds 		}							\
1541da177e4SLinus Torvalds 	} while (0)
1551da177e4SLinus Torvalds #else
1561da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1571da177e4SLinus Torvalds #endif
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds /*
1601da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1611da177e4SLinus Torvalds  */
1621da177e4SLinus Torvalds int vm_swappiness = 60;
163d0480be4SWang Sheng-Hui /*
164d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
165d0480be4SWang Sheng-Hui  * zones.
166d0480be4SWang Sheng-Hui  */
167d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1681da177e4SLinus Torvalds 
1691da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1701da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1711da177e4SLinus Torvalds 
172b4c2b231SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
173b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
174b4c2b231SKirill Tkhai static int shrinker_nr_max;
175b4c2b231SKirill Tkhai 
176b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
177b4c2b231SKirill Tkhai {
178b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
179b4c2b231SKirill Tkhai 
180b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
181b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
182b4c2b231SKirill Tkhai 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
183b4c2b231SKirill Tkhai 	if (id < 0)
184b4c2b231SKirill Tkhai 		goto unlock;
185b4c2b231SKirill Tkhai 
1860a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
1870a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
1880a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
1890a4465d3SKirill Tkhai 			goto unlock;
1900a4465d3SKirill Tkhai 		}
1910a4465d3SKirill Tkhai 
192b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
1930a4465d3SKirill Tkhai 	}
194b4c2b231SKirill Tkhai 	shrinker->id = id;
195b4c2b231SKirill Tkhai 	ret = 0;
196b4c2b231SKirill Tkhai unlock:
197b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
198b4c2b231SKirill Tkhai 	return ret;
199b4c2b231SKirill Tkhai }
200b4c2b231SKirill Tkhai 
201b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
202b4c2b231SKirill Tkhai {
203b4c2b231SKirill Tkhai 	int id = shrinker->id;
204b4c2b231SKirill Tkhai 
205b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
206b4c2b231SKirill Tkhai 
207b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
208b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
209b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
210b4c2b231SKirill Tkhai }
211b4c2b231SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
212b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
213b4c2b231SKirill Tkhai {
214b4c2b231SKirill Tkhai 	return 0;
215b4c2b231SKirill Tkhai }
216b4c2b231SKirill Tkhai 
217b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
218b4c2b231SKirill Tkhai {
219b4c2b231SKirill Tkhai }
220b4c2b231SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
221b4c2b231SKirill Tkhai 
222c255a458SAndrew Morton #ifdef CONFIG_MEMCG
22389b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
22489b5fae5SJohannes Weiner {
225f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
22689b5fae5SJohannes Weiner }
22797c9341fSTejun Heo 
22897c9341fSTejun Heo /**
22997c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
23097c9341fSTejun Heo  * @sc: scan_control in question
23197c9341fSTejun Heo  *
23297c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
23397c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
23497c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
23597c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
23697c9341fSTejun Heo  * allocation and configurability.
23797c9341fSTejun Heo  *
23897c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
23997c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
24097c9341fSTejun Heo  */
24197c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
24297c9341fSTejun Heo {
24397c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
24497c9341fSTejun Heo 
24597c9341fSTejun Heo 	if (!memcg)
24697c9341fSTejun Heo 		return true;
24797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
24869234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
24997c9341fSTejun Heo 		return true;
25097c9341fSTejun Heo #endif
25197c9341fSTejun Heo 	return false;
25297c9341fSTejun Heo }
253e3c1ac58SAndrey Ryabinin 
254e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
255e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
256e3c1ac58SAndrey Ryabinin 				bool congested)
257e3c1ac58SAndrey Ryabinin {
258e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
259e3c1ac58SAndrey Ryabinin 
260e3c1ac58SAndrey Ryabinin 	if (!memcg)
261e3c1ac58SAndrey Ryabinin 		return;
262e3c1ac58SAndrey Ryabinin 
263e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
264e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
265e3c1ac58SAndrey Ryabinin }
266e3c1ac58SAndrey Ryabinin 
267e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
268e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
269e3c1ac58SAndrey Ryabinin {
270e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
271e3c1ac58SAndrey Ryabinin 
272e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
273e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
274e3c1ac58SAndrey Ryabinin 
275e3c1ac58SAndrey Ryabinin }
27691a45470SKAMEZAWA Hiroyuki #else
27789b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
27889b5fae5SJohannes Weiner {
27989b5fae5SJohannes Weiner 	return true;
28089b5fae5SJohannes Weiner }
28197c9341fSTejun Heo 
28297c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
28397c9341fSTejun Heo {
28497c9341fSTejun Heo 	return true;
28597c9341fSTejun Heo }
286e3c1ac58SAndrey Ryabinin 
287e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
288e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
289e3c1ac58SAndrey Ryabinin {
290e3c1ac58SAndrey Ryabinin }
291e3c1ac58SAndrey Ryabinin 
292e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
293e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
294e3c1ac58SAndrey Ryabinin {
295e3c1ac58SAndrey Ryabinin 	return false;
296e3c1ac58SAndrey Ryabinin 
297e3c1ac58SAndrey Ryabinin }
29891a45470SKAMEZAWA Hiroyuki #endif
29991a45470SKAMEZAWA Hiroyuki 
3005a1c84b4SMel Gorman /*
3015a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3025a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3035a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3045a1c84b4SMel Gorman  */
3055a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3065a1c84b4SMel Gorman {
3075a1c84b4SMel Gorman 	unsigned long nr;
3085a1c84b4SMel Gorman 
3095a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3105a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3115a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3125a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3135a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3145a1c84b4SMel Gorman 
3155a1c84b4SMel Gorman 	return nr;
3165a1c84b4SMel Gorman }
3175a1c84b4SMel Gorman 
318fd538803SMichal Hocko /**
319fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
320fd538803SMichal Hocko  * @lruvec: lru vector
321fd538803SMichal Hocko  * @lru: lru to use
322fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
323fd538803SMichal Hocko  */
324fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
325c9f299d9SKOSAKI Motohiro {
326fd538803SMichal Hocko 	unsigned long lru_size;
327fd538803SMichal Hocko 	int zid;
328a3d8e054SKOSAKI Motohiro 
329fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
330fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
331fd538803SMichal Hocko 	else
332fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
333fd538803SMichal Hocko 
334fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
335fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
336fd538803SMichal Hocko 		unsigned long size;
337fd538803SMichal Hocko 
338fd538803SMichal Hocko 		if (!managed_zone(zone))
339fd538803SMichal Hocko 			continue;
340fd538803SMichal Hocko 
341fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
342fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
343fd538803SMichal Hocko 		else
344fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
345fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
346fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
347c9f299d9SKOSAKI Motohiro 	}
348c9f299d9SKOSAKI Motohiro 
349fd538803SMichal Hocko 	return lru_size;
350b4536f0cSMichal Hocko 
351b4536f0cSMichal Hocko }
352b4536f0cSMichal Hocko 
3531da177e4SLinus Torvalds /*
3541d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3551da177e4SLinus Torvalds  */
3568e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3571da177e4SLinus Torvalds {
3581d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
3591d3d4437SGlauber Costa 
3601d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3611d3d4437SGlauber Costa 		size *= nr_node_ids;
3621d3d4437SGlauber Costa 
3631d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3641d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3651d3d4437SGlauber Costa 		return -ENOMEM;
366b4c2b231SKirill Tkhai 
367b0dedc49SKirill Tkhai 	/*
368b0dedc49SKirill Tkhai 	 * There is a window between prealloc_shrinker()
369b0dedc49SKirill Tkhai 	 * and register_shrinker_prepared(). We don't want
370b0dedc49SKirill Tkhai 	 * to clear bit of a shrinker in such the state
371b0dedc49SKirill Tkhai 	 * in shrink_slab_memcg(), since this will impose
372b0dedc49SKirill Tkhai 	 * restrictions on a code registering a shrinker
373b0dedc49SKirill Tkhai 	 * (they would have to guarantee, their LRU lists
374b0dedc49SKirill Tkhai 	 * are empty till shrinker is completely registered).
375b0dedc49SKirill Tkhai 	 * So, we differ the situation, when 1)a shrinker
376b0dedc49SKirill Tkhai 	 * is semi-registered (id is assigned, but it has
377b0dedc49SKirill Tkhai 	 * not yet linked to shrinker_list) and 2)shrinker
378b0dedc49SKirill Tkhai 	 * is not registered (id is not assigned).
379b0dedc49SKirill Tkhai 	 */
380b0dedc49SKirill Tkhai 	INIT_LIST_HEAD(&shrinker->list);
381b0dedc49SKirill Tkhai 
382b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
383b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
384b4c2b231SKirill Tkhai 			goto free_deferred;
385b4c2b231SKirill Tkhai 	}
386b4c2b231SKirill Tkhai 
3878e04944fSTetsuo Handa 	return 0;
388b4c2b231SKirill Tkhai 
389b4c2b231SKirill Tkhai free_deferred:
390b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
391b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
392b4c2b231SKirill Tkhai 	return -ENOMEM;
3938e04944fSTetsuo Handa }
3941d3d4437SGlauber Costa 
3958e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3968e04944fSTetsuo Handa {
397b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
398b4c2b231SKirill Tkhai 		return;
399b4c2b231SKirill Tkhai 
400b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
401b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
402b4c2b231SKirill Tkhai 
4038e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
4048e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
4058e04944fSTetsuo Handa }
4068e04944fSTetsuo Handa 
4078e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
4088e04944fSTetsuo Handa {
4091da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4101da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
4111da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
4128e04944fSTetsuo Handa }
4138e04944fSTetsuo Handa 
4148e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
4158e04944fSTetsuo Handa {
4168e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4178e04944fSTetsuo Handa 
4188e04944fSTetsuo Handa 	if (err)
4198e04944fSTetsuo Handa 		return err;
4208e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4211d3d4437SGlauber Costa 	return 0;
4221da177e4SLinus Torvalds }
4238e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4241da177e4SLinus Torvalds 
4251da177e4SLinus Torvalds /*
4261da177e4SLinus Torvalds  * Remove one
4271da177e4SLinus Torvalds  */
4288e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4291da177e4SLinus Torvalds {
430bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
431bb422a73STetsuo Handa 		return;
432b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
433b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4341da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4351da177e4SLinus Torvalds 	list_del(&shrinker->list);
4361da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
437ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
438bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4391da177e4SLinus Torvalds }
4408e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4411da177e4SLinus Torvalds 
4421da177e4SLinus Torvalds #define SHRINK_BATCH 128
4431d3d4437SGlauber Costa 
444cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4459092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4461da177e4SLinus Torvalds {
44724f7c6b9SDave Chinner 	unsigned long freed = 0;
4481da177e4SLinus Torvalds 	unsigned long long delta;
449635697c6SKonstantin Khlebnikov 	long total_scan;
450d5bc5fd3SVladimir Davydov 	long freeable;
451acf92b48SDave Chinner 	long nr;
452acf92b48SDave Chinner 	long new_nr;
4531d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
454e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
455e9299f50SDave Chinner 					  : SHRINK_BATCH;
4565f33a080SShaohua Li 	long scanned = 0, next_deferred;
4571da177e4SLinus Torvalds 
458d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
459d5bc5fd3SVladimir Davydov 	if (freeable == 0)
4601d3d4437SGlauber Costa 		return 0;
461635697c6SKonstantin Khlebnikov 
462acf92b48SDave Chinner 	/*
463acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
464acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
465acf92b48SDave Chinner 	 * don't also do this scanning work.
466acf92b48SDave Chinner 	 */
4671d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
468acf92b48SDave Chinner 
469acf92b48SDave Chinner 	total_scan = nr;
4709092c71bSJosef Bacik 	delta = freeable >> priority;
4719092c71bSJosef Bacik 	delta *= 4;
4729092c71bSJosef Bacik 	do_div(delta, shrinker->seeks);
473acf92b48SDave Chinner 	total_scan += delta;
474acf92b48SDave Chinner 	if (total_scan < 0) {
4758612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
476a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
477d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4785f33a080SShaohua Li 		next_deferred = nr;
4795f33a080SShaohua Li 	} else
4805f33a080SShaohua Li 		next_deferred = total_scan;
481ea164d73SAndrea Arcangeli 
482ea164d73SAndrea Arcangeli 	/*
4833567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
4843567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
4853567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
4863567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
4873567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
488d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
4893567b59aSDave Chinner 	 * memory.
4903567b59aSDave Chinner 	 *
4913567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
4923567b59aSDave Chinner 	 * a large delta change is calculated directly.
4933567b59aSDave Chinner 	 */
494d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
495d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
4963567b59aSDave Chinner 
4973567b59aSDave Chinner 	/*
498ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
499ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
500ea164d73SAndrea Arcangeli 	 * freeable entries.
501ea164d73SAndrea Arcangeli 	 */
502d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
503d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5041da177e4SLinus Torvalds 
50524f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5069092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
50709576073SDave Chinner 
5080b1fb40aSVladimir Davydov 	/*
5090b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5100b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5110b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5120b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5130b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5140b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5150b1fb40aSVladimir Davydov 	 * batch_size.
5160b1fb40aSVladimir Davydov 	 *
5170b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5180b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
519d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5200b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5210b1fb40aSVladimir Davydov 	 * possible.
5220b1fb40aSVladimir Davydov 	 */
5230b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
524d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
52524f7c6b9SDave Chinner 		unsigned long ret;
5260b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5271da177e4SLinus Torvalds 
5280b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
529d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
53024f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
53124f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5321da177e4SLinus Torvalds 			break;
53324f7c6b9SDave Chinner 		freed += ret;
53424f7c6b9SDave Chinner 
535d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
536d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
537d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5381da177e4SLinus Torvalds 
5391da177e4SLinus Torvalds 		cond_resched();
5401da177e4SLinus Torvalds 	}
5411da177e4SLinus Torvalds 
5425f33a080SShaohua Li 	if (next_deferred >= scanned)
5435f33a080SShaohua Li 		next_deferred -= scanned;
5445f33a080SShaohua Li 	else
5455f33a080SShaohua Li 		next_deferred = 0;
546acf92b48SDave Chinner 	/*
547acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
548acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
549acf92b48SDave Chinner 	 * scan, there is no need to do an update.
550acf92b48SDave Chinner 	 */
5515f33a080SShaohua Li 	if (next_deferred > 0)
5525f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5531d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
55483aeeadaSKonstantin Khlebnikov 	else
5551d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
556acf92b48SDave Chinner 
557df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5581d3d4437SGlauber Costa 	return freed;
5591d3d4437SGlauber Costa }
5601d3d4437SGlauber Costa 
561b0dedc49SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
562b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
563b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
564b0dedc49SKirill Tkhai {
565b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
566b0dedc49SKirill Tkhai 	unsigned long freed = 0;
567b0dedc49SKirill Tkhai 	int ret, i;
568b0dedc49SKirill Tkhai 
569b0dedc49SKirill Tkhai 	if (!memcg_kmem_enabled() || !mem_cgroup_online(memcg))
570b0dedc49SKirill Tkhai 		return 0;
571b0dedc49SKirill Tkhai 
572b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
573b0dedc49SKirill Tkhai 		return 0;
574b0dedc49SKirill Tkhai 
575b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
576b0dedc49SKirill Tkhai 					true);
577b0dedc49SKirill Tkhai 	if (unlikely(!map))
578b0dedc49SKirill Tkhai 		goto unlock;
579b0dedc49SKirill Tkhai 
580b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
581b0dedc49SKirill Tkhai 		struct shrink_control sc = {
582b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
583b0dedc49SKirill Tkhai 			.nid = nid,
584b0dedc49SKirill Tkhai 			.memcg = memcg,
585b0dedc49SKirill Tkhai 		};
586b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
587b0dedc49SKirill Tkhai 
588b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
589b0dedc49SKirill Tkhai 		if (unlikely(!shrinker)) {
590b0dedc49SKirill Tkhai 			clear_bit(i, map->map);
591b0dedc49SKirill Tkhai 			continue;
592b0dedc49SKirill Tkhai 		}
593b0dedc49SKirill Tkhai 
594b0dedc49SKirill Tkhai 		/* See comment in prealloc_shrinker() */
595b0dedc49SKirill Tkhai 		if (unlikely(list_empty(&shrinker->list)))
596b0dedc49SKirill Tkhai 			continue;
597b0dedc49SKirill Tkhai 
598b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
599b0dedc49SKirill Tkhai 		freed += ret;
600b0dedc49SKirill Tkhai 
601b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
602b0dedc49SKirill Tkhai 			freed = freed ? : 1;
603b0dedc49SKirill Tkhai 			break;
604b0dedc49SKirill Tkhai 		}
605b0dedc49SKirill Tkhai 	}
606b0dedc49SKirill Tkhai unlock:
607b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
608b0dedc49SKirill Tkhai 	return freed;
609b0dedc49SKirill Tkhai }
610b0dedc49SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
611b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
612b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
613b0dedc49SKirill Tkhai {
614b0dedc49SKirill Tkhai 	return 0;
615b0dedc49SKirill Tkhai }
616b0dedc49SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
617b0dedc49SKirill Tkhai 
6186b4f7799SJohannes Weiner /**
619cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6206b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6216b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
622cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6239092c71bSJosef Bacik  * @priority: the reclaim priority
6241d3d4437SGlauber Costa  *
6256b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6261d3d4437SGlauber Costa  *
6276b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6286b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6291d3d4437SGlauber Costa  *
630*aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
631*aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
632cb731d6cSVladimir Davydov  *
6339092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6349092c71bSJosef Bacik  * in order to get the scan target.
6351d3d4437SGlauber Costa  *
6366b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6371d3d4437SGlauber Costa  */
638cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
639cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6409092c71bSJosef Bacik 				 int priority)
6411d3d4437SGlauber Costa {
6421d3d4437SGlauber Costa 	struct shrinker *shrinker;
6431d3d4437SGlauber Costa 	unsigned long freed = 0;
6441d3d4437SGlauber Costa 
645*aeed1d32SVladimir Davydov 	if (!mem_cgroup_is_root(memcg))
646b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
647cb731d6cSVladimir Davydov 
648e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6491d3d4437SGlauber Costa 		goto out;
6501d3d4437SGlauber Costa 
6511d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
6526b4f7799SJohannes Weiner 		struct shrink_control sc = {
6536b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
6546b4f7799SJohannes Weiner 			.nid = nid,
655cb731d6cSVladimir Davydov 			.memcg = memcg,
6566b4f7799SJohannes Weiner 		};
6576b4f7799SJohannes Weiner 
6586b4f7799SJohannes Weiner 		if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
6596b4f7799SJohannes Weiner 			sc.nid = 0;
6606b4f7799SJohannes Weiner 
6619092c71bSJosef Bacik 		freed += do_shrink_slab(&sc, shrinker, priority);
662e496612cSMinchan Kim 		/*
663e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
664e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
665e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
666e496612cSMinchan Kim 		 */
667e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
668e496612cSMinchan Kim 			freed = freed ? : 1;
669e496612cSMinchan Kim 			break;
670e496612cSMinchan Kim 		}
671ec97097bSVladimir Davydov 	}
6721d3d4437SGlauber Costa 
6731da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
674f06590bdSMinchan Kim out:
675f06590bdSMinchan Kim 	cond_resched();
67624f7c6b9SDave Chinner 	return freed;
6771da177e4SLinus Torvalds }
6781da177e4SLinus Torvalds 
679cb731d6cSVladimir Davydov void drop_slab_node(int nid)
680cb731d6cSVladimir Davydov {
681cb731d6cSVladimir Davydov 	unsigned long freed;
682cb731d6cSVladimir Davydov 
683cb731d6cSVladimir Davydov 	do {
684cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
685cb731d6cSVladimir Davydov 
686cb731d6cSVladimir Davydov 		freed = 0;
687*aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
688cb731d6cSVladimir Davydov 		do {
6899092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
690cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
691cb731d6cSVladimir Davydov 	} while (freed > 10);
692cb731d6cSVladimir Davydov }
693cb731d6cSVladimir Davydov 
694cb731d6cSVladimir Davydov void drop_slab(void)
695cb731d6cSVladimir Davydov {
696cb731d6cSVladimir Davydov 	int nid;
697cb731d6cSVladimir Davydov 
698cb731d6cSVladimir Davydov 	for_each_online_node(nid)
699cb731d6cSVladimir Davydov 		drop_slab_node(nid);
700cb731d6cSVladimir Davydov }
701cb731d6cSVladimir Davydov 
7021da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7031da177e4SLinus Torvalds {
704ceddc3a5SJohannes Weiner 	/*
705ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
706ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
707ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
708ceddc3a5SJohannes Weiner 	 */
709bd4c82c2SHuang Ying 	int radix_pins = PageTransHuge(page) && PageSwapCache(page) ?
710bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
711bd4c82c2SHuang Ying 	return page_count(page) - page_has_private(page) == 1 + radix_pins;
7121da177e4SLinus Torvalds }
7131da177e4SLinus Torvalds 
714703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
7151da177e4SLinus Torvalds {
716930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7171da177e4SLinus Torvalds 		return 1;
718703c2708STejun Heo 	if (!inode_write_congested(inode))
7191da177e4SLinus Torvalds 		return 1;
720703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7211da177e4SLinus Torvalds 		return 1;
7221da177e4SLinus Torvalds 	return 0;
7231da177e4SLinus Torvalds }
7241da177e4SLinus Torvalds 
7251da177e4SLinus Torvalds /*
7261da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7271da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7281da177e4SLinus Torvalds  * fsync(), msync() or close().
7291da177e4SLinus Torvalds  *
7301da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7311da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7321da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7331da177e4SLinus Torvalds  *
7341da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7351da177e4SLinus Torvalds  * __GFP_FS.
7361da177e4SLinus Torvalds  */
7371da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7381da177e4SLinus Torvalds 				struct page *page, int error)
7391da177e4SLinus Torvalds {
7407eaceaccSJens Axboe 	lock_page(page);
7413e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7423e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7431da177e4SLinus Torvalds 	unlock_page(page);
7441da177e4SLinus Torvalds }
7451da177e4SLinus Torvalds 
74604e62a29SChristoph Lameter /* possible outcome of pageout() */
74704e62a29SChristoph Lameter typedef enum {
74804e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
74904e62a29SChristoph Lameter 	PAGE_KEEP,
75004e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
75104e62a29SChristoph Lameter 	PAGE_ACTIVATE,
75204e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
75304e62a29SChristoph Lameter 	PAGE_SUCCESS,
75404e62a29SChristoph Lameter 	/* page is clean and locked */
75504e62a29SChristoph Lameter 	PAGE_CLEAN,
75604e62a29SChristoph Lameter } pageout_t;
75704e62a29SChristoph Lameter 
7581da177e4SLinus Torvalds /*
7591742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
7601742f19fSAndrew Morton  * Calls ->writepage().
7611da177e4SLinus Torvalds  */
762c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
7637d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
7641da177e4SLinus Torvalds {
7651da177e4SLinus Torvalds 	/*
7661da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
7671da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
7681da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
7691da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
7701da177e4SLinus Torvalds 	 * PagePrivate for that.
7711da177e4SLinus Torvalds 	 *
7728174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
7731da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
7741da177e4SLinus Torvalds 	 * will block.
7751da177e4SLinus Torvalds 	 *
7761da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
7771da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
7781da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
7791da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
7801da177e4SLinus Torvalds 	 */
7811da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
7821da177e4SLinus Torvalds 		return PAGE_KEEP;
7831da177e4SLinus Torvalds 	if (!mapping) {
7841da177e4SLinus Torvalds 		/*
7851da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
7861da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
7871da177e4SLinus Torvalds 		 */
788266cf658SDavid Howells 		if (page_has_private(page)) {
7891da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
7901da177e4SLinus Torvalds 				ClearPageDirty(page);
791b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
7921da177e4SLinus Torvalds 				return PAGE_CLEAN;
7931da177e4SLinus Torvalds 			}
7941da177e4SLinus Torvalds 		}
7951da177e4SLinus Torvalds 		return PAGE_KEEP;
7961da177e4SLinus Torvalds 	}
7971da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
7981da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
799703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
8001da177e4SLinus Torvalds 		return PAGE_KEEP;
8011da177e4SLinus Torvalds 
8021da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8031da177e4SLinus Torvalds 		int res;
8041da177e4SLinus Torvalds 		struct writeback_control wbc = {
8051da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8061da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
807111ebb6eSOGAWA Hirofumi 			.range_start = 0,
808111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8091da177e4SLinus Torvalds 			.for_reclaim = 1,
8101da177e4SLinus Torvalds 		};
8111da177e4SLinus Torvalds 
8121da177e4SLinus Torvalds 		SetPageReclaim(page);
8131da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8141da177e4SLinus Torvalds 		if (res < 0)
8151da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
816994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8171da177e4SLinus Torvalds 			ClearPageReclaim(page);
8181da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8191da177e4SLinus Torvalds 		}
820c661b078SAndy Whitcroft 
8211da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8221da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8231da177e4SLinus Torvalds 			ClearPageReclaim(page);
8241da177e4SLinus Torvalds 		}
8253aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
826c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8271da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8281da177e4SLinus Torvalds 	}
8291da177e4SLinus Torvalds 
8301da177e4SLinus Torvalds 	return PAGE_CLEAN;
8311da177e4SLinus Torvalds }
8321da177e4SLinus Torvalds 
833a649fd92SAndrew Morton /*
834e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
835e286781dSNick Piggin  * gets returned with a refcount of 0.
836a649fd92SAndrew Morton  */
837a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
838a528910eSJohannes Weiner 			    bool reclaimed)
83949d2e9ccSChristoph Lameter {
840c4843a75SGreg Thelen 	unsigned long flags;
841bd4c82c2SHuang Ying 	int refcount;
842c4843a75SGreg Thelen 
84328e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
84428e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
84549d2e9ccSChristoph Lameter 
846b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
84749d2e9ccSChristoph Lameter 	/*
8480fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8490fd0e6b0SNick Piggin 	 *
8500fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8510fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
8520fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
8530fd0e6b0SNick Piggin 	 * here, then the following race may occur:
8540fd0e6b0SNick Piggin 	 *
8550fd0e6b0SNick Piggin 	 * get_user_pages(&page);
8560fd0e6b0SNick Piggin 	 * [user mapping goes away]
8570fd0e6b0SNick Piggin 	 * write_to(page);
8580fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
8590fd0e6b0SNick Piggin 	 * SetPageDirty(page);
8600fd0e6b0SNick Piggin 	 * put_page(page);
8610fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
8620fd0e6b0SNick Piggin 	 *
8630fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
8640fd0e6b0SNick Piggin 	 *
8650fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
8660fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
8670139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
8680fd0e6b0SNick Piggin 	 *
8690fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
870b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
87149d2e9ccSChristoph Lameter 	 */
872bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
873bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
874bd4c82c2SHuang Ying 	else
875bd4c82c2SHuang Ying 		refcount = 2;
876bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
87749d2e9ccSChristoph Lameter 		goto cannot_free;
878e286781dSNick Piggin 	/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
879e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
880bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
88149d2e9ccSChristoph Lameter 		goto cannot_free;
882e286781dSNick Piggin 	}
88349d2e9ccSChristoph Lameter 
88449d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
88549d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
8860a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
88749d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
888b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
88975f6d6d2SMinchan Kim 		put_swap_page(page, swap);
890e286781dSNick Piggin 	} else {
8916072d13cSLinus Torvalds 		void (*freepage)(struct page *);
892a528910eSJohannes Weiner 		void *shadow = NULL;
8936072d13cSLinus Torvalds 
8946072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
895a528910eSJohannes Weiner 		/*
896a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
897a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
898a528910eSJohannes Weiner 		 *
899a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
900a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
901a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
902a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
903a528910eSJohannes Weiner 		 * back.
904f9fe48beSRoss Zwisler 		 *
905f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
906f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
907f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
908f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
909b93b0163SMatthew Wilcox 		 * same address_space.
910a528910eSJohannes Weiner 		 */
911a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
912f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
913a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
91462cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
915b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9166072d13cSLinus Torvalds 
9176072d13cSLinus Torvalds 		if (freepage != NULL)
9186072d13cSLinus Torvalds 			freepage(page);
919e286781dSNick Piggin 	}
920e286781dSNick Piggin 
92149d2e9ccSChristoph Lameter 	return 1;
92249d2e9ccSChristoph Lameter 
92349d2e9ccSChristoph Lameter cannot_free:
924b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
92549d2e9ccSChristoph Lameter 	return 0;
92649d2e9ccSChristoph Lameter }
92749d2e9ccSChristoph Lameter 
9281da177e4SLinus Torvalds /*
929e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
930e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
931e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
932e286781dSNick Piggin  * this page.
933e286781dSNick Piggin  */
934e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
935e286781dSNick Piggin {
936a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
937e286781dSNick Piggin 		/*
938e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
939e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
940e286781dSNick Piggin 		 * atomic operation.
941e286781dSNick Piggin 		 */
942fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
943e286781dSNick Piggin 		return 1;
944e286781dSNick Piggin 	}
945e286781dSNick Piggin 	return 0;
946e286781dSNick Piggin }
947e286781dSNick Piggin 
948894bc310SLee Schermerhorn /**
949894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
950894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
951894bc310SLee Schermerhorn  *
952894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
953894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
954894bc310SLee Schermerhorn  *
955894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
956894bc310SLee Schermerhorn  */
957894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
958894bc310SLee Schermerhorn {
959c53954a0SMel Gorman 	lru_cache_add(page);
960894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
961894bc310SLee Schermerhorn }
962894bc310SLee Schermerhorn 
963dfc8d636SJohannes Weiner enum page_references {
964dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
965dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
96664574746SJohannes Weiner 	PAGEREF_KEEP,
967dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
968dfc8d636SJohannes Weiner };
969dfc8d636SJohannes Weiner 
970dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
971dfc8d636SJohannes Weiner 						  struct scan_control *sc)
972dfc8d636SJohannes Weiner {
97364574746SJohannes Weiner 	int referenced_ptes, referenced_page;
974dfc8d636SJohannes Weiner 	unsigned long vm_flags;
975dfc8d636SJohannes Weiner 
976c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
977c3ac9a8aSJohannes Weiner 					  &vm_flags);
97864574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
979dfc8d636SJohannes Weiner 
980dfc8d636SJohannes Weiner 	/*
981dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
982dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
983dfc8d636SJohannes Weiner 	 */
984dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
985dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
986dfc8d636SJohannes Weiner 
98764574746SJohannes Weiner 	if (referenced_ptes) {
988e4898273SMichal Hocko 		if (PageSwapBacked(page))
98964574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
99064574746SJohannes Weiner 		/*
99164574746SJohannes Weiner 		 * All mapped pages start out with page table
99264574746SJohannes Weiner 		 * references from the instantiating fault, so we need
99364574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
99464574746SJohannes Weiner 		 * than once.
99564574746SJohannes Weiner 		 *
99664574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
99764574746SJohannes Weiner 		 * inactive list.  Another page table reference will
99864574746SJohannes Weiner 		 * lead to its activation.
99964574746SJohannes Weiner 		 *
100064574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
100164574746SJohannes Weiner 		 * so that recently deactivated but used pages are
100264574746SJohannes Weiner 		 * quickly recovered.
100364574746SJohannes Weiner 		 */
100464574746SJohannes Weiner 		SetPageReferenced(page);
100564574746SJohannes Weiner 
100634dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1007dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1008dfc8d636SJohannes Weiner 
1009c909e993SKonstantin Khlebnikov 		/*
1010c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1011c909e993SKonstantin Khlebnikov 		 */
1012c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1013c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1014c909e993SKonstantin Khlebnikov 
101564574746SJohannes Weiner 		return PAGEREF_KEEP;
101664574746SJohannes Weiner 	}
101764574746SJohannes Weiner 
1018dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10192e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1020dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
102164574746SJohannes Weiner 
102264574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1023dfc8d636SJohannes Weiner }
1024dfc8d636SJohannes Weiner 
1025e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1026e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1027e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1028e2be15f6SMel Gorman {
1029b4597226SMel Gorman 	struct address_space *mapping;
1030b4597226SMel Gorman 
1031e2be15f6SMel Gorman 	/*
1032e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1033e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1034e2be15f6SMel Gorman 	 */
1035802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1036802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1037e2be15f6SMel Gorman 		*dirty = false;
1038e2be15f6SMel Gorman 		*writeback = false;
1039e2be15f6SMel Gorman 		return;
1040e2be15f6SMel Gorman 	}
1041e2be15f6SMel Gorman 
1042e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1043e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1044e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1045b4597226SMel Gorman 
1046b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1047b4597226SMel Gorman 	if (!page_has_private(page))
1048b4597226SMel Gorman 		return;
1049b4597226SMel Gorman 
1050b4597226SMel Gorman 	mapping = page_mapping(page);
1051b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1052b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1053e2be15f6SMel Gorman }
1054e2be15f6SMel Gorman 
1055e286781dSNick Piggin /*
10561742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
10571da177e4SLinus Torvalds  */
10581742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1059599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1060f84f6e2bSMel Gorman 				      struct scan_control *sc,
106102c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
10623c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
106302c6de8dSMinchan Kim 				      bool force_reclaim)
10641da177e4SLinus Torvalds {
10651da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1066abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
10671da177e4SLinus Torvalds 	int pgactivate = 0;
10683c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
10693c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
10703c710c1aSMichal Hocko 	unsigned nr_congested = 0;
10713c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
10723c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
10733c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
10745bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
10755bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
10761da177e4SLinus Torvalds 
10771da177e4SLinus Torvalds 	cond_resched();
10781da177e4SLinus Torvalds 
10791da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
10801da177e4SLinus Torvalds 		struct address_space *mapping;
10811da177e4SLinus Torvalds 		struct page *page;
10821da177e4SLinus Torvalds 		int may_enter_fs;
108302c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
1084e2be15f6SMel Gorman 		bool dirty, writeback;
10851da177e4SLinus Torvalds 
10861da177e4SLinus Torvalds 		cond_resched();
10871da177e4SLinus Torvalds 
10881da177e4SLinus Torvalds 		page = lru_to_page(page_list);
10891da177e4SLinus Torvalds 		list_del(&page->lru);
10901da177e4SLinus Torvalds 
1091529ae9aaSNick Piggin 		if (!trylock_page(page))
10921da177e4SLinus Torvalds 			goto keep;
10931da177e4SLinus Torvalds 
1094309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
10951da177e4SLinus Torvalds 
10961da177e4SLinus Torvalds 		sc->nr_scanned++;
109780e43426SChristoph Lameter 
109839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1099ad6b6704SMinchan Kim 			goto activate_locked;
1100894bc310SLee Schermerhorn 
1101a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
110280e43426SChristoph Lameter 			goto keep_locked;
110380e43426SChristoph Lameter 
11041da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
1105802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
1106802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
11071da177e4SLinus Torvalds 			sc->nr_scanned++;
11081da177e4SLinus Torvalds 
1109c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1110c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1111c661b078SAndy Whitcroft 
1112e62e384eSMichal Hocko 		/*
1113894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1114e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1115e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1116e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1117e2be15f6SMel Gorman 		 */
1118e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1119e2be15f6SMel Gorman 		if (dirty || writeback)
1120e2be15f6SMel Gorman 			nr_dirty++;
1121e2be15f6SMel Gorman 
1122e2be15f6SMel Gorman 		if (dirty && !writeback)
1123e2be15f6SMel Gorman 			nr_unqueued_dirty++;
1124e2be15f6SMel Gorman 
1125d04e8acdSMel Gorman 		/*
1126d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1127d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1128d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1129d04e8acdSMel Gorman 		 * end of the LRU a second time.
1130d04e8acdSMel Gorman 		 */
1131e2be15f6SMel Gorman 		mapping = page_mapping(page);
11321da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1133703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1134d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1135e2be15f6SMel Gorman 			nr_congested++;
1136e2be15f6SMel Gorman 
1137e2be15f6SMel Gorman 		/*
1138283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1139283aba9fSMel Gorman 		 * are three cases to consider.
1140e62e384eSMichal Hocko 		 *
1141283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1142283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1143283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1144283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1145283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1146283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1147283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1148b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1149b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1150c3b94f44SHugh Dickins 		 *
115197c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1152ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1153ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1154ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
115597c9341fSTejun Heo 		 *    reclaim and continue scanning.
1156283aba9fSMel Gorman 		 *
1157ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1158ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1159283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1160283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1161283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1162283aba9fSMel Gorman 		 *    would probably show more reasons.
1163283aba9fSMel Gorman 		 *
11647fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1165283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1166283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1167283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1168283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1169c55e8d03SJohannes Weiner 		 *
1170c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1171c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1172c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1173c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1174c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1175c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1176c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1177c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1178e62e384eSMichal Hocko 		 */
1179283aba9fSMel Gorman 		if (PageWriteback(page)) {
1180283aba9fSMel Gorman 			/* Case 1 above */
1181283aba9fSMel Gorman 			if (current_is_kswapd() &&
1182283aba9fSMel Gorman 			    PageReclaim(page) &&
1183599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1184b1a6f21eSMel Gorman 				nr_immediate++;
1185c55e8d03SJohannes Weiner 				goto activate_locked;
1186283aba9fSMel Gorman 
1187283aba9fSMel Gorman 			/* Case 2 above */
118897c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1189ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1190c3b94f44SHugh Dickins 				/*
1191c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1192c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1193c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1194c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1195c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1196c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1197c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1198c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1199c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1200c3b94f44SHugh Dickins 				 */
1201c3b94f44SHugh Dickins 				SetPageReclaim(page);
120292df3a72SMel Gorman 				nr_writeback++;
1203c55e8d03SJohannes Weiner 				goto activate_locked;
1204283aba9fSMel Gorman 
1205283aba9fSMel Gorman 			/* Case 3 above */
1206283aba9fSMel Gorman 			} else {
12077fadc820SHugh Dickins 				unlock_page(page);
1208c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12097fadc820SHugh Dickins 				/* then go back and try same page again */
12107fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12117fadc820SHugh Dickins 				continue;
1212e62e384eSMichal Hocko 			}
1213283aba9fSMel Gorman 		}
12141da177e4SLinus Torvalds 
121502c6de8dSMinchan Kim 		if (!force_reclaim)
12166a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
121702c6de8dSMinchan Kim 
1218dfc8d636SJohannes Weiner 		switch (references) {
1219dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12201da177e4SLinus Torvalds 			goto activate_locked;
122164574746SJohannes Weiner 		case PAGEREF_KEEP:
12225bccd166SMichal Hocko 			nr_ref_keep++;
122364574746SJohannes Weiner 			goto keep_locked;
1224dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1225dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1226dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1227dfc8d636SJohannes Weiner 		}
12281da177e4SLinus Torvalds 
12291da177e4SLinus Torvalds 		/*
12301da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12311da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1232802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12331da177e4SLinus Torvalds 		 */
1234bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1235bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
123663eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
123763eb6b93SHugh Dickins 					goto keep_locked;
1238747552b1SHuang Ying 				if (PageTransHuge(page)) {
1239b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1240747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1241b8f593cdSHuang Ying 						goto activate_locked;
1242747552b1SHuang Ying 					/*
1243747552b1SHuang Ying 					 * Split pages without a PMD map right
1244747552b1SHuang Ying 					 * away. Chances are some or all of the
1245747552b1SHuang Ying 					 * tail pages can be freed without IO.
1246747552b1SHuang Ying 					 */
1247747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1248bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1249bd4c82c2SHuang Ying 								    page_list))
1250747552b1SHuang Ying 						goto activate_locked;
1251747552b1SHuang Ying 				}
12520f074658SMinchan Kim 				if (!add_to_swap(page)) {
12530f074658SMinchan Kim 					if (!PageTransHuge(page))
12541da177e4SLinus Torvalds 						goto activate_locked;
1255bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1256bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1257bd4c82c2SHuang Ying 								    page_list))
12580f074658SMinchan Kim 						goto activate_locked;
1259fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1260fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1261fe490cc0SHuang Ying #endif
12620f074658SMinchan Kim 					if (!add_to_swap(page))
12630f074658SMinchan Kim 						goto activate_locked;
12640f074658SMinchan Kim 				}
12650f074658SMinchan Kim 
126663eb6b93SHugh Dickins 				may_enter_fs = 1;
12671da177e4SLinus Torvalds 
1268e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
12691da177e4SLinus Torvalds 				mapping = page_mapping(page);
1270bd4c82c2SHuang Ying 			}
12717751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
12727751b2daSKirill A. Shutemov 			/* Split file THP */
12737751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
12747751b2daSKirill A. Shutemov 				goto keep_locked;
1275e2be15f6SMel Gorman 		}
12761da177e4SLinus Torvalds 
12771da177e4SLinus Torvalds 		/*
12781da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
12791da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
12801da177e4SLinus Torvalds 		 */
1281802a3a92SShaohua Li 		if (page_mapped(page)) {
1282bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1283bd4c82c2SHuang Ying 
1284bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1285bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1286bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
12875bccd166SMichal Hocko 				nr_unmap_fail++;
12881da177e4SLinus Torvalds 				goto activate_locked;
12891da177e4SLinus Torvalds 			}
12901da177e4SLinus Torvalds 		}
12911da177e4SLinus Torvalds 
12921da177e4SLinus Torvalds 		if (PageDirty(page)) {
1293ee72886dSMel Gorman 			/*
12944eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
12954eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
12964eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
12974eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
12984eda4823SJohannes Weiner 			 * write pages when we've encountered many
12994eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13004eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13014eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1302ee72886dSMel Gorman 			 */
1303f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13044eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1305599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
130649ea7eb6SMel Gorman 				/*
130749ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
130849ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
130949ea7eb6SMel Gorman 				 * except we already have the page isolated
131049ea7eb6SMel Gorman 				 * and know it's dirty
131149ea7eb6SMel Gorman 				 */
1312c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
131349ea7eb6SMel Gorman 				SetPageReclaim(page);
131449ea7eb6SMel Gorman 
1315c55e8d03SJohannes Weiner 				goto activate_locked;
1316ee72886dSMel Gorman 			}
1317ee72886dSMel Gorman 
1318dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13191da177e4SLinus Torvalds 				goto keep_locked;
13204dd4b920SAndrew Morton 			if (!may_enter_fs)
13211da177e4SLinus Torvalds 				goto keep_locked;
132252a8363eSChristoph Lameter 			if (!sc->may_writepage)
13231da177e4SLinus Torvalds 				goto keep_locked;
13241da177e4SLinus Torvalds 
1325d950c947SMel Gorman 			/*
1326d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1327d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1328d950c947SMel Gorman 			 * starts and then write it out here.
1329d950c947SMel Gorman 			 */
1330d950c947SMel Gorman 			try_to_unmap_flush_dirty();
13317d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
13321da177e4SLinus Torvalds 			case PAGE_KEEP:
13331da177e4SLinus Torvalds 				goto keep_locked;
13341da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13351da177e4SLinus Torvalds 				goto activate_locked;
13361da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13377d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
133841ac1999SMel Gorman 					goto keep;
13397d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13401da177e4SLinus Torvalds 					goto keep;
13417d3579e8SKOSAKI Motohiro 
13421da177e4SLinus Torvalds 				/*
13431da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13441da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13451da177e4SLinus Torvalds 				 */
1346529ae9aaSNick Piggin 				if (!trylock_page(page))
13471da177e4SLinus Torvalds 					goto keep;
13481da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13491da177e4SLinus Torvalds 					goto keep_locked;
13501da177e4SLinus Torvalds 				mapping = page_mapping(page);
13511da177e4SLinus Torvalds 			case PAGE_CLEAN:
13521da177e4SLinus Torvalds 				; /* try to free the page below */
13531da177e4SLinus Torvalds 			}
13541da177e4SLinus Torvalds 		}
13551da177e4SLinus Torvalds 
13561da177e4SLinus Torvalds 		/*
13571da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
13581da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
13591da177e4SLinus Torvalds 		 * the page as well.
13601da177e4SLinus Torvalds 		 *
13611da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
13621da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
13631da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
13641da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
13651da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
13661da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
13671da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
13681da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
13691da177e4SLinus Torvalds 		 *
13701da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
13711da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
13721da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
13731da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
13741da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
13751da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
13761da177e4SLinus Torvalds 		 */
1377266cf658SDavid Howells 		if (page_has_private(page)) {
13781da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
13791da177e4SLinus Torvalds 				goto activate_locked;
1380e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1381e286781dSNick Piggin 				unlock_page(page);
1382e286781dSNick Piggin 				if (put_page_testzero(page))
13831da177e4SLinus Torvalds 					goto free_it;
1384e286781dSNick Piggin 				else {
1385e286781dSNick Piggin 					/*
1386e286781dSNick Piggin 					 * rare race with speculative reference.
1387e286781dSNick Piggin 					 * the speculative reference will free
1388e286781dSNick Piggin 					 * this page shortly, so we may
1389e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1390e286781dSNick Piggin 					 * leave it off the LRU).
1391e286781dSNick Piggin 					 */
1392e286781dSNick Piggin 					nr_reclaimed++;
1393e286781dSNick Piggin 					continue;
1394e286781dSNick Piggin 				}
1395e286781dSNick Piggin 			}
13961da177e4SLinus Torvalds 		}
13971da177e4SLinus Torvalds 
1398802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1399802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1400802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
140149d2e9ccSChristoph Lameter 				goto keep_locked;
1402802a3a92SShaohua Li 			if (PageDirty(page)) {
1403802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1404802a3a92SShaohua Li 				goto keep_locked;
1405802a3a92SShaohua Li 			}
14061da177e4SLinus Torvalds 
1407802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14082262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1409802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1410802a3a92SShaohua Li 			goto keep_locked;
1411a978d6f5SNick Piggin 		/*
1412a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1413a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1414a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1415a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1416a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1417a978d6f5SNick Piggin 		 */
141848c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1419e286781dSNick Piggin free_it:
142005ff5137SAndrew Morton 		nr_reclaimed++;
1421abe4c3b5SMel Gorman 
1422abe4c3b5SMel Gorman 		/*
1423abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1424abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1425abe4c3b5SMel Gorman 		 */
1426bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1427bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1428bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1429bd4c82c2SHuang Ying 		} else
1430abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14311da177e4SLinus Torvalds 		continue;
14321da177e4SLinus Torvalds 
14331da177e4SLinus Torvalds activate_locked:
143468a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1435ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1436ad6b6704SMinchan Kim 						PageMlocked(page)))
1437a2c43eedSHugh Dickins 			try_to_free_swap(page);
1438309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1439ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
14401da177e4SLinus Torvalds 			SetPageActive(page);
14411da177e4SLinus Torvalds 			pgactivate++;
14422262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1443ad6b6704SMinchan Kim 		}
14441da177e4SLinus Torvalds keep_locked:
14451da177e4SLinus Torvalds 		unlock_page(page);
14461da177e4SLinus Torvalds keep:
14471da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1448309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14491da177e4SLinus Torvalds 	}
1450abe4c3b5SMel Gorman 
1451747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
145272b252aeSMel Gorman 	try_to_unmap_flush();
14532d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1454abe4c3b5SMel Gorman 
14551da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1456f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
14570a31bc97SJohannes Weiner 
14583c710c1aSMichal Hocko 	if (stat) {
14593c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
14603c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
14613c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
14623c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
14633c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
14645bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
14655bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
14665bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
14673c710c1aSMichal Hocko 	}
146805ff5137SAndrew Morton 	return nr_reclaimed;
14691da177e4SLinus Torvalds }
14701da177e4SLinus Torvalds 
147102c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
147202c6de8dSMinchan Kim 					    struct list_head *page_list)
147302c6de8dSMinchan Kim {
147402c6de8dSMinchan Kim 	struct scan_control sc = {
147502c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
147602c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
147702c6de8dSMinchan Kim 		.may_unmap = 1,
147802c6de8dSMinchan Kim 	};
14793c710c1aSMichal Hocko 	unsigned long ret;
148002c6de8dSMinchan Kim 	struct page *page, *next;
148102c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
148202c6de8dSMinchan Kim 
148302c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1484117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1485b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
148602c6de8dSMinchan Kim 			ClearPageActive(page);
148702c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
148802c6de8dSMinchan Kim 		}
148902c6de8dSMinchan Kim 	}
149002c6de8dSMinchan Kim 
1491599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1492a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
149302c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1494599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
149502c6de8dSMinchan Kim 	return ret;
149602c6de8dSMinchan Kim }
149702c6de8dSMinchan Kim 
14985ad333ebSAndy Whitcroft /*
14995ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15005ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15015ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15025ad333ebSAndy Whitcroft  *
15035ad333ebSAndy Whitcroft  * page:	page to consider
15045ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15055ad333ebSAndy Whitcroft  *
15065ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15075ad333ebSAndy Whitcroft  */
1508f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15095ad333ebSAndy Whitcroft {
15105ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15115ad333ebSAndy Whitcroft 
15125ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15135ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15145ad333ebSAndy Whitcroft 		return ret;
15155ad333ebSAndy Whitcroft 
1516e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1517e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1518894bc310SLee Schermerhorn 		return ret;
1519894bc310SLee Schermerhorn 
15205ad333ebSAndy Whitcroft 	ret = -EBUSY;
152108e552c6SKAMEZAWA Hiroyuki 
1522c8244935SMel Gorman 	/*
1523c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1524c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1525c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1526c8244935SMel Gorman 	 *
1527c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1528c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1529c8244935SMel Gorman 	 */
15301276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1531c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1532c8244935SMel Gorman 		if (PageWriteback(page))
153339deaf85SMinchan Kim 			return ret;
153439deaf85SMinchan Kim 
1535c8244935SMel Gorman 		if (PageDirty(page)) {
1536c8244935SMel Gorman 			struct address_space *mapping;
153769d763fcSMel Gorman 			bool migrate_dirty;
1538c8244935SMel Gorman 
1539c8244935SMel Gorman 			/*
1540c8244935SMel Gorman 			 * Only pages without mappings or that have a
1541c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
154269d763fcSMel Gorman 			 * without blocking. However, we can be racing with
154369d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
154469d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
154569d763fcSMel Gorman 			 * the page lock until after the page is removed
154669d763fcSMel Gorman 			 * from the page cache.
1547c8244935SMel Gorman 			 */
154869d763fcSMel Gorman 			if (!trylock_page(page))
154969d763fcSMel Gorman 				return ret;
155069d763fcSMel Gorman 
1551c8244935SMel Gorman 			mapping = page_mapping(page);
1552145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
155369d763fcSMel Gorman 			unlock_page(page);
155469d763fcSMel Gorman 			if (!migrate_dirty)
1555c8244935SMel Gorman 				return ret;
1556c8244935SMel Gorman 		}
1557c8244935SMel Gorman 	}
1558c8244935SMel Gorman 
1559f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1560f80c0673SMinchan Kim 		return ret;
1561f80c0673SMinchan Kim 
15625ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
15635ad333ebSAndy Whitcroft 		/*
15645ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
15655ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
15665ad333ebSAndy Whitcroft 		 * page release code relies on it.
15675ad333ebSAndy Whitcroft 		 */
15685ad333ebSAndy Whitcroft 		ClearPageLRU(page);
15695ad333ebSAndy Whitcroft 		ret = 0;
15705ad333ebSAndy Whitcroft 	}
15715ad333ebSAndy Whitcroft 
15725ad333ebSAndy Whitcroft 	return ret;
15735ad333ebSAndy Whitcroft }
15745ad333ebSAndy Whitcroft 
15757ee36a14SMel Gorman 
15767ee36a14SMel Gorman /*
15777ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
15787ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
15797ee36a14SMel Gorman  */
15807ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1581b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
15827ee36a14SMel Gorman {
15837ee36a14SMel Gorman 	int zid;
15847ee36a14SMel Gorman 
15857ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
15867ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
15877ee36a14SMel Gorman 			continue;
15887ee36a14SMel Gorman 
15897ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1590b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1591b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1592b4536f0cSMichal Hocko #endif
15937ee36a14SMel Gorman 	}
15947ee36a14SMel Gorman 
15957ee36a14SMel Gorman }
15967ee36a14SMel Gorman 
159749d2e9ccSChristoph Lameter /*
1598a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
15991da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16001da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16011da177e4SLinus Torvalds  *
16021da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16031da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16041da177e4SLinus Torvalds  *
16051da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16061da177e4SLinus Torvalds  *
1607791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16085dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16091da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1610f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1611fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16125ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16133cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16141da177e4SLinus Torvalds  *
16151da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16161da177e4SLinus Torvalds  */
161769e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16185dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1619fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
16203cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
16211da177e4SLinus Torvalds {
162275b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
162369e05944SAndrew Morton 	unsigned long nr_taken = 0;
1624599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16257cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16263db65812SJohannes Weiner 	unsigned long skipped = 0;
1627791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1628b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
16291da177e4SLinus Torvalds 
1630791b48b6SMinchan Kim 	scan = 0;
1631791b48b6SMinchan Kim 	for (total_scan = 0;
1632791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1633791b48b6SMinchan Kim 	     total_scan++) {
16345ad333ebSAndy Whitcroft 		struct page *page;
16355ad333ebSAndy Whitcroft 
16361da177e4SLinus Torvalds 		page = lru_to_page(src);
16371da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16381da177e4SLinus Torvalds 
1639309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16408d438f96SNick Piggin 
1641b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1642b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
16437cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1644b2e18757SMel Gorman 			continue;
1645b2e18757SMel Gorman 		}
1646b2e18757SMel Gorman 
1647791b48b6SMinchan Kim 		/*
1648791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1649791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1650791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1651791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1652791b48b6SMinchan Kim 		 */
1653791b48b6SMinchan Kim 		scan++;
1654f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
16555ad333ebSAndy Whitcroft 		case 0:
1656599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1657599d0c95SMel Gorman 			nr_taken += nr_pages;
1658599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
16595ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
16605ad333ebSAndy Whitcroft 			break;
16617c8ee9a8SNick Piggin 
16625ad333ebSAndy Whitcroft 		case -EBUSY:
16635ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
16645ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
16655ad333ebSAndy Whitcroft 			continue;
16665ad333ebSAndy Whitcroft 
16675ad333ebSAndy Whitcroft 		default:
16685ad333ebSAndy Whitcroft 			BUG();
16695ad333ebSAndy Whitcroft 		}
16705ad333ebSAndy Whitcroft 	}
16711da177e4SLinus Torvalds 
1672b2e18757SMel Gorman 	/*
1673b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1674b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1675b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1676b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1677b2e18757SMel Gorman 	 * system at risk of premature OOM.
1678b2e18757SMel Gorman 	 */
16797cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
16807cc30fcfSMel Gorman 		int zid;
16817cc30fcfSMel Gorman 
16823db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
16837cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16847cc30fcfSMel Gorman 			if (!nr_skipped[zid])
16857cc30fcfSMel Gorman 				continue;
16867cc30fcfSMel Gorman 
16877cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
16881265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
16897cc30fcfSMel Gorman 		}
16907cc30fcfSMel Gorman 	}
1691791b48b6SMinchan Kim 	*nr_scanned = total_scan;
16921265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1693791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1694b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
16951da177e4SLinus Torvalds 	return nr_taken;
16961da177e4SLinus Torvalds }
16971da177e4SLinus Torvalds 
169862695a84SNick Piggin /**
169962695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
170062695a84SNick Piggin  * @page: page to isolate from its LRU list
170162695a84SNick Piggin  *
170262695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
170362695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
170462695a84SNick Piggin  *
170562695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
170662695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
170762695a84SNick Piggin  *
170862695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1709894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1710894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1711894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
171262695a84SNick Piggin  *
171362695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
171462695a84SNick Piggin  * found will be decremented.
171562695a84SNick Piggin  *
171662695a84SNick Piggin  * Restrictions:
1717a5d09bedSMike Rapoport  *
171862695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
171962695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
172062695a84SNick Piggin  *     without a stable reference).
172162695a84SNick Piggin  * (2) the lru_lock must not be held.
172262695a84SNick Piggin  * (3) interrupts must be enabled.
172362695a84SNick Piggin  */
172462695a84SNick Piggin int isolate_lru_page(struct page *page)
172562695a84SNick Piggin {
172662695a84SNick Piggin 	int ret = -EBUSY;
172762695a84SNick Piggin 
1728309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1729cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17300c917313SKonstantin Khlebnikov 
173162695a84SNick Piggin 	if (PageLRU(page)) {
173262695a84SNick Piggin 		struct zone *zone = page_zone(page);
1733fa9add64SHugh Dickins 		struct lruvec *lruvec;
173462695a84SNick Piggin 
1735a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1736599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
17370c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1738894bc310SLee Schermerhorn 			int lru = page_lru(page);
17390c917313SKonstantin Khlebnikov 			get_page(page);
174062695a84SNick Piggin 			ClearPageLRU(page);
1741fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1742fa9add64SHugh Dickins 			ret = 0;
174362695a84SNick Piggin 		}
1744a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
174562695a84SNick Piggin 	}
174662695a84SNick Piggin 	return ret;
174762695a84SNick Piggin }
174862695a84SNick Piggin 
17495ad333ebSAndy Whitcroft /*
1750d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1751d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1752d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1753d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1754d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
175535cd7815SRik van Riel  */
1756599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
175735cd7815SRik van Riel 		struct scan_control *sc)
175835cd7815SRik van Riel {
175935cd7815SRik van Riel 	unsigned long inactive, isolated;
176035cd7815SRik van Riel 
176135cd7815SRik van Riel 	if (current_is_kswapd())
176235cd7815SRik van Riel 		return 0;
176335cd7815SRik van Riel 
176497c9341fSTejun Heo 	if (!sane_reclaim(sc))
176535cd7815SRik van Riel 		return 0;
176635cd7815SRik van Riel 
176735cd7815SRik van Riel 	if (file) {
1768599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1769599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
177035cd7815SRik van Riel 	} else {
1771599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1772599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
177335cd7815SRik van Riel 	}
177435cd7815SRik van Riel 
17753cf23841SFengguang Wu 	/*
17763cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
17773cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
17783cf23841SFengguang Wu 	 * deadlock.
17793cf23841SFengguang Wu 	 */
1780d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
17813cf23841SFengguang Wu 		inactive >>= 3;
17823cf23841SFengguang Wu 
178335cd7815SRik van Riel 	return isolated > inactive;
178435cd7815SRik van Riel }
178535cd7815SRik van Riel 
178666635629SMel Gorman static noinline_for_stack void
178775b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
178866635629SMel Gorman {
178927ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1790599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
17913f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
179266635629SMel Gorman 
179366635629SMel Gorman 	/*
179466635629SMel Gorman 	 * Put back any unfreeable pages.
179566635629SMel Gorman 	 */
179666635629SMel Gorman 	while (!list_empty(page_list)) {
17973f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
179866635629SMel Gorman 		int lru;
17993f79768fSHugh Dickins 
1800309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
180166635629SMel Gorman 		list_del(&page->lru);
180239b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1803599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
180466635629SMel Gorman 			putback_lru_page(page);
1805599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
180666635629SMel Gorman 			continue;
180766635629SMel Gorman 		}
1808fa9add64SHugh Dickins 
1809599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1810fa9add64SHugh Dickins 
18117a608572SLinus Torvalds 		SetPageLRU(page);
181266635629SMel Gorman 		lru = page_lru(page);
1813fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1814fa9add64SHugh Dickins 
181566635629SMel Gorman 		if (is_active_lru(lru)) {
181666635629SMel Gorman 			int file = is_file_lru(lru);
18179992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
18189992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
181966635629SMel Gorman 		}
18202bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18212bcf8879SHugh Dickins 			__ClearPageLRU(page);
18222bcf8879SHugh Dickins 			__ClearPageActive(page);
1823fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18242bcf8879SHugh Dickins 
18252bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1826599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1827747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18282bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1829599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18302bcf8879SHugh Dickins 			} else
18312bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
183266635629SMel Gorman 		}
183366635629SMel Gorman 	}
183466635629SMel Gorman 
18353f79768fSHugh Dickins 	/*
18363f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
18373f79768fSHugh Dickins 	 */
18383f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
183966635629SMel Gorman }
184066635629SMel Gorman 
184166635629SMel Gorman /*
1842399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1843399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1844399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1845399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1846399ba0b9SNeilBrown  */
1847399ba0b9SNeilBrown static int current_may_throttle(void)
1848399ba0b9SNeilBrown {
1849399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1850399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1851399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1852399ba0b9SNeilBrown }
1853399ba0b9SNeilBrown 
1854399ba0b9SNeilBrown /*
1855b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
18561742f19fSAndrew Morton  * of reclaimed pages
18571da177e4SLinus Torvalds  */
185866635629SMel Gorman static noinline_for_stack unsigned long
18591a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
18609e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
18611da177e4SLinus Torvalds {
18621da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1863e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
186405ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1865e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
18663c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1867f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
18683cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1869599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18701a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1871db73ee0dSMichal Hocko 	bool stalled = false;
187278dc583dSKOSAKI Motohiro 
1873599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1874db73ee0dSMichal Hocko 		if (stalled)
1875db73ee0dSMichal Hocko 			return 0;
1876db73ee0dSMichal Hocko 
1877db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1878db73ee0dSMichal Hocko 		msleep(100);
1879db73ee0dSMichal Hocko 		stalled = true;
188035cd7815SRik van Riel 
188135cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
188235cd7815SRik van Riel 		if (fatal_signal_pending(current))
188335cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
188435cd7815SRik van Riel 	}
188535cd7815SRik van Riel 
18861da177e4SLinus Torvalds 	lru_add_drain();
1887f80c0673SMinchan Kim 
1888f80c0673SMinchan Kim 	if (!sc->may_unmap)
188961317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1890f80c0673SMinchan Kim 
1891599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
18921da177e4SLinus Torvalds 
18935dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
18945dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
189595d918fcSKonstantin Khlebnikov 
1896599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
18979d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
189895d918fcSKonstantin Khlebnikov 
18992262185cSRoman Gushchin 	if (current_is_kswapd()) {
19002262185cSRoman Gushchin 		if (global_reclaim(sc))
1901599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
19022262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
19032262185cSRoman Gushchin 				   nr_scanned);
19042262185cSRoman Gushchin 	} else {
19052262185cSRoman Gushchin 		if (global_reclaim(sc))
1906599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
19072262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
19082262185cSRoman Gushchin 				   nr_scanned);
1909b35ea17bSKOSAKI Motohiro 	}
1910599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1911d563c050SHillf Danton 
1912d563c050SHillf Danton 	if (nr_taken == 0)
191366635629SMel Gorman 		return 0;
1914b35ea17bSKOSAKI Motohiro 
1915a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19163c710c1aSMichal Hocko 				&stat, false);
1917c661b078SAndy Whitcroft 
1918599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19193f79768fSHugh Dickins 
19202262185cSRoman Gushchin 	if (current_is_kswapd()) {
19212262185cSRoman Gushchin 		if (global_reclaim(sc))
1922599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
19232262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
19242262185cSRoman Gushchin 				   nr_reclaimed);
19252262185cSRoman Gushchin 	} else {
19262262185cSRoman Gushchin 		if (global_reclaim(sc))
1927599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
19282262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
19292262185cSRoman Gushchin 				   nr_reclaimed);
1930904249aaSYing Han 	}
1931a74609faSNick Piggin 
193227ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
19333f79768fSHugh Dickins 
1934599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19353f79768fSHugh Dickins 
1936599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19373f79768fSHugh Dickins 
1938747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19392d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1940e11da5b4SMel Gorman 
194192df3a72SMel Gorman 	/*
19421c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19431c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19441c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19451c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19461c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19471c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
19481c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
19491c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
19501c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
19511c610d5fSAndrey Ryabinin 	 */
19521c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
19531c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
19541c610d5fSAndrey Ryabinin 
1955d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
1956d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
1957d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1958d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
1959d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
1960d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
1961d108c772SAndrey Ryabinin 	if (file)
1962d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
19638e950282SMel Gorman 
1964599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
1965d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
196605ff5137SAndrew Morton 	return nr_reclaimed;
19671da177e4SLinus Torvalds }
19681da177e4SLinus Torvalds 
19693bb1a852SMartin Bligh /*
19701cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
19711cfb419bSKAMEZAWA Hiroyuki  *
19721cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
19731cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
19741cfb419bSKAMEZAWA Hiroyuki  *
19751cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
1976a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
19771cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
1978a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
19791cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
19801cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
19811cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
19821cfb419bSKAMEZAWA Hiroyuki  *
19830139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
19841cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
19859d998b4fSMichal Hocko  *
19869d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
19871cfb419bSKAMEZAWA Hiroyuki  */
19881cfb419bSKAMEZAWA Hiroyuki 
19899d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
19903eb4140fSWu Fengguang 				     struct list_head *list,
19912bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
19923eb4140fSWu Fengguang 				     enum lru_list lru)
19933eb4140fSWu Fengguang {
1994599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19953eb4140fSWu Fengguang 	struct page *page;
1996fa9add64SHugh Dickins 	int nr_pages;
19979d998b4fSMichal Hocko 	int nr_moved = 0;
19983eb4140fSWu Fengguang 
19993eb4140fSWu Fengguang 	while (!list_empty(list)) {
20003eb4140fSWu Fengguang 		page = lru_to_page(list);
2001599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
20023eb4140fSWu Fengguang 
2003309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
20043eb4140fSWu Fengguang 		SetPageLRU(page);
20053eb4140fSWu Fengguang 
2006fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
2007599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
2008925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
20093eb4140fSWu Fengguang 
20102bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
20112bcf8879SHugh Dickins 			__ClearPageLRU(page);
20122bcf8879SHugh Dickins 			__ClearPageActive(page);
2013fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
20142bcf8879SHugh Dickins 
20152bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
2016599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
2017747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
20182bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
2019599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
20202bcf8879SHugh Dickins 			} else
20212bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
20229d998b4fSMichal Hocko 		} else {
20239d998b4fSMichal Hocko 			nr_moved += nr_pages;
20243eb4140fSWu Fengguang 		}
20253eb4140fSWu Fengguang 	}
20269d5e6a9fSHugh Dickins 
20272262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
2028f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
20292262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
20302262185cSRoman Gushchin 				   nr_moved);
20312262185cSRoman Gushchin 	}
20329d998b4fSMichal Hocko 
20339d998b4fSMichal Hocko 	return nr_moved;
20343eb4140fSWu Fengguang }
20351cfb419bSKAMEZAWA Hiroyuki 
2036f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20371a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2038f16015fbSJohannes Weiner 			       struct scan_control *sc,
20399e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20401cfb419bSKAMEZAWA Hiroyuki {
204144c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2042f626012dSHugh Dickins 	unsigned long nr_scanned;
20436fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20441cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20458cab4754SWu Fengguang 	LIST_HEAD(l_active);
2046b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20471cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20481a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20499d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20509d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
2051f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
20523cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2053599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20541cfb419bSKAMEZAWA Hiroyuki 
20551da177e4SLinus Torvalds 	lru_add_drain();
2056f80c0673SMinchan Kim 
2057f80c0673SMinchan Kim 	if (!sc->may_unmap)
205861317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
2059f80c0673SMinchan Kim 
2060599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2061925b7673SJohannes Weiner 
20625dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
20635dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
206489b5fae5SJohannes Weiner 
2065599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2066b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20671cfb419bSKAMEZAWA Hiroyuki 
2068599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20692262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20709d5e6a9fSHugh Dickins 
2071599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20721da177e4SLinus Torvalds 
20731da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20741da177e4SLinus Torvalds 		cond_resched();
20751da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20761da177e4SLinus Torvalds 		list_del(&page->lru);
20777e9cd484SRik van Riel 
207839b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2079894bc310SLee Schermerhorn 			putback_lru_page(page);
2080894bc310SLee Schermerhorn 			continue;
2081894bc310SLee Schermerhorn 		}
2082894bc310SLee Schermerhorn 
2083cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2084cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2085cc715d99SMel Gorman 				if (page_has_private(page))
2086cc715d99SMel Gorman 					try_to_release_page(page, 0);
2087cc715d99SMel Gorman 				unlock_page(page);
2088cc715d99SMel Gorman 			}
2089cc715d99SMel Gorman 		}
2090cc715d99SMel Gorman 
2091c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2092c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20939992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20948cab4754SWu Fengguang 			/*
20958cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20968cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20978cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20988cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20998cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
21008cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
21018cab4754SWu Fengguang 			 * so we ignore them here.
21028cab4754SWu Fengguang 			 */
210341e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
21048cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
21058cab4754SWu Fengguang 				continue;
21068cab4754SWu Fengguang 			}
21078cab4754SWu Fengguang 		}
21087e9cd484SRik van Riel 
21095205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
21101da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
21111da177e4SLinus Torvalds 	}
21121da177e4SLinus Torvalds 
2113b555749aSAndrew Morton 	/*
21148cab4754SWu Fengguang 	 * Move pages back to the lru list.
2115b555749aSAndrew Morton 	 */
2116599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
21174f98a2feSRik van Riel 	/*
21188cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
21198cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
21208cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
21217c0db9e9SJerome Marchand 	 * get_scan_count.
2122556adecbSRik van Riel 	 */
2123b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2124556adecbSRik van Riel 
21259d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
21269d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
2127599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2128599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21292bcf8879SHugh Dickins 
2130747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
21312d4894b5SMel Gorman 	free_unref_page_list(&l_hold);
21329d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21339d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21341da177e4SLinus Torvalds }
21351da177e4SLinus Torvalds 
213659dc76b0SRik van Riel /*
213759dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
213859dc76b0SRik van Riel  * to do too much work.
213914797e23SKOSAKI Motohiro  *
214059dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
214159dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
214259dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
214359dc76b0SRik van Riel  *
214459dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
214559dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
214659dc76b0SRik van Riel  *
21472a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21482a2e4885SJohannes Weiner  *
214959dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21503a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
215159dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
215259dc76b0SRik van Riel  *
215359dc76b0SRik van Riel  * total     target    max
215459dc76b0SRik van Riel  * memory    ratio     inactive
215559dc76b0SRik van Riel  * -------------------------------------
215659dc76b0SRik van Riel  *   10MB       1         5MB
215759dc76b0SRik van Riel  *  100MB       1        50MB
215859dc76b0SRik van Riel  *    1GB       3       250MB
215959dc76b0SRik van Riel  *   10GB      10       0.9GB
216059dc76b0SRik van Riel  *  100GB      31         3GB
216159dc76b0SRik van Riel  *    1TB     101        10GB
216259dc76b0SRik van Riel  *   10TB     320        32GB
216314797e23SKOSAKI Motohiro  */
2164f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
21652a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
21662a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
216714797e23SKOSAKI Motohiro {
2168fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
21692a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21702a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
21712a2e4885SJohannes Weiner 	unsigned long inactive, active;
21722a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
21732a2e4885SJohannes Weiner 	unsigned long refaults;
217459dc76b0SRik van Riel 	unsigned long gb;
217559dc76b0SRik van Riel 
217674e3f3c3SMinchan Kim 	/*
217774e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
217874e3f3c3SMinchan Kim 	 * is pointless.
217974e3f3c3SMinchan Kim 	 */
218059dc76b0SRik van Riel 	if (!file && !total_swap_pages)
218142e2e457SYaowei Bai 		return false;
218274e3f3c3SMinchan Kim 
2183fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2184fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2185f8d1a311SMel Gorman 
21862a2e4885SJohannes Weiner 	if (memcg)
2187ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
21882a2e4885SJohannes Weiner 	else
21892a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
21902a2e4885SJohannes Weiner 
21912a2e4885SJohannes Weiner 	/*
21922a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
21932a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
21942a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
21952a2e4885SJohannes Weiner 	 */
21962a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
21972a2e4885SJohannes Weiner 		inactive_ratio = 0;
21982a2e4885SJohannes Weiner 	} else {
219959dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
220059dc76b0SRik van Riel 		if (gb)
220159dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2202b39415b2SRik van Riel 		else
220359dc76b0SRik van Riel 			inactive_ratio = 1;
22042a2e4885SJohannes Weiner 	}
220559dc76b0SRik van Riel 
22062a2e4885SJohannes Weiner 	if (actual_reclaim)
22072a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2208fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2209fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2210fd538803SMichal Hocko 			inactive_ratio, file);
2211fd538803SMichal Hocko 
221259dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2213b39415b2SRik van Riel }
2214b39415b2SRik van Riel 
22154f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
22162a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
22172a2e4885SJohannes Weiner 				 struct scan_control *sc)
2218b69408e8SChristoph Lameter {
2219b39415b2SRik van Riel 	if (is_active_lru(lru)) {
22202a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
22212a2e4885SJohannes Weiner 					 memcg, sc, true))
22221a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2223556adecbSRik van Riel 		return 0;
2224556adecbSRik van Riel 	}
2225556adecbSRik van Riel 
22261a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2227b69408e8SChristoph Lameter }
2228b69408e8SChristoph Lameter 
22299a265114SJohannes Weiner enum scan_balance {
22309a265114SJohannes Weiner 	SCAN_EQUAL,
22319a265114SJohannes Weiner 	SCAN_FRACT,
22329a265114SJohannes Weiner 	SCAN_ANON,
22339a265114SJohannes Weiner 	SCAN_FILE,
22349a265114SJohannes Weiner };
22359a265114SJohannes Weiner 
22361da177e4SLinus Torvalds /*
22374f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22384f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22394f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22404f98a2feSRik van Riel  * onto the active list instead of evict.
22414f98a2feSRik van Riel  *
2242be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2243be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22444f98a2feSRik van Riel  */
224533377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
22466b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
22476b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
22484f98a2feSRik van Riel {
224933377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
225090126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
22519a265114SJohannes Weiner 	u64 fraction[2];
22529a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2253599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22549a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
22559a265114SJohannes Weiner 	enum scan_balance scan_balance;
22560bf1457fSJohannes Weiner 	unsigned long anon, file;
22579a265114SJohannes Weiner 	unsigned long ap, fp;
22589a265114SJohannes Weiner 	enum lru_list lru;
225976a33fc3SShaohua Li 
226076a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2261d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22629a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
226376a33fc3SShaohua Li 		goto out;
226476a33fc3SShaohua Li 	}
22654f98a2feSRik van Riel 
226610316b31SJohannes Weiner 	/*
226710316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
226810316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
226910316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
227010316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
227110316b31SJohannes Weiner 	 * too expensive.
227210316b31SJohannes Weiner 	 */
227302695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
22749a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
227510316b31SJohannes Weiner 		goto out;
227610316b31SJohannes Weiner 	}
227710316b31SJohannes Weiner 
227810316b31SJohannes Weiner 	/*
227910316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
228010316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
228110316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
228210316b31SJohannes Weiner 	 */
228302695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22849a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
228510316b31SJohannes Weiner 		goto out;
228610316b31SJohannes Weiner 	}
228710316b31SJohannes Weiner 
228811d16c25SJohannes Weiner 	/*
228962376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
229062376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
229162376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
229262376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
229362376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
229462376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
229562376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
229662376251SJohannes Weiner 	 */
229762376251SJohannes Weiner 	if (global_reclaim(sc)) {
2298599d0c95SMel Gorman 		unsigned long pgdatfile;
2299599d0c95SMel Gorman 		unsigned long pgdatfree;
2300599d0c95SMel Gorman 		int z;
2301599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
230262376251SJohannes Weiner 
2303599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2304599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2305599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
23062ab051e1SJerome Marchand 
2307599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2308599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
23096aa303deSMel Gorman 			if (!managed_zone(zone))
2310599d0c95SMel Gorman 				continue;
2311599d0c95SMel Gorman 
2312599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2313599d0c95SMel Gorman 		}
2314599d0c95SMel Gorman 
2315599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
231606226226SDavid Rientjes 			/*
231706226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
231806226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
231906226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
232006226226SDavid Rientjes 			 */
232106226226SDavid Rientjes 			if (!inactive_list_is_low(lruvec, false, memcg, sc, false) &&
232206226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
232306226226SDavid Rientjes 					>> sc->priority) {
232462376251SJohannes Weiner 				scan_balance = SCAN_ANON;
232562376251SJohannes Weiner 				goto out;
232662376251SJohannes Weiner 			}
232762376251SJohannes Weiner 		}
232806226226SDavid Rientjes 	}
232962376251SJohannes Weiner 
233062376251SJohannes Weiner 	/*
2331316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2332316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2333316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2334316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2335316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2336316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2337316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2338e9868505SRik van Riel 	 */
23392a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
234071ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
23419a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2342e9868505SRik van Riel 		goto out;
23434f98a2feSRik van Riel 	}
23444f98a2feSRik van Riel 
23459a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23469a265114SJohannes Weiner 
23474f98a2feSRik van Riel 	/*
234858c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
234958c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
235058c37f6eSKOSAKI Motohiro 	 */
235102695175SJohannes Weiner 	anon_prio = swappiness;
235275b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
235358c37f6eSKOSAKI Motohiro 
235458c37f6eSKOSAKI Motohiro 	/*
23554f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
23564f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
23574f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
23584f98a2feSRik van Riel 	 *
23594f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
23604f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
23614f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
23624f98a2feSRik van Riel 	 *
23634f98a2feSRik van Riel 	 * anon in [0], file in [1]
23644f98a2feSRik van Riel 	 */
23652ab051e1SJerome Marchand 
2366fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2367fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2368fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2369fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
23702ab051e1SJerome Marchand 
2371599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
237258c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
23736e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
23746e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
23754f98a2feSRik van Riel 	}
23764f98a2feSRik van Riel 
23776e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
23786e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
23796e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
23804f98a2feSRik van Riel 	}
23814f98a2feSRik van Riel 
23824f98a2feSRik van Riel 	/*
238300d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
238400d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
238500d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
23864f98a2feSRik van Riel 	 */
2387fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
23886e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
23894f98a2feSRik van Riel 
2390fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
23916e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2392599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
23934f98a2feSRik van Riel 
239476a33fc3SShaohua Li 	fraction[0] = ap;
239576a33fc3SShaohua Li 	fraction[1] = fp;
239676a33fc3SShaohua Li 	denominator = ap + fp + 1;
239776a33fc3SShaohua Li out:
23986b4f7799SJohannes Weiner 	*lru_pages = 0;
23994111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24004111304dSHugh Dickins 		int file = is_file_lru(lru);
2401d778df51SJohannes Weiner 		unsigned long size;
240276a33fc3SShaohua Li 		unsigned long scan;
240376a33fc3SShaohua Li 
240471ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2405d778df51SJohannes Weiner 		scan = size >> sc->priority;
2406688035f7SJohannes Weiner 		/*
2407688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2408688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2409688035f7SJohannes Weiner 		 */
2410688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2411d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
24129a265114SJohannes Weiner 
24139a265114SJohannes Weiner 		switch (scan_balance) {
24149a265114SJohannes Weiner 		case SCAN_EQUAL:
24159a265114SJohannes Weiner 			/* Scan lists relative to size */
24169a265114SJohannes Weiner 			break;
24179a265114SJohannes Weiner 		case SCAN_FRACT:
24189a265114SJohannes Weiner 			/*
24199a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
24209a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
24219a265114SJohannes Weiner 			 */
24226f04f48dSSuleiman Souhlal 			scan = div64_u64(scan * fraction[file],
24236f04f48dSSuleiman Souhlal 					 denominator);
24249a265114SJohannes Weiner 			break;
24259a265114SJohannes Weiner 		case SCAN_FILE:
24269a265114SJohannes Weiner 		case SCAN_ANON:
24279a265114SJohannes Weiner 			/* Scan one type exclusively */
24286b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
24296b4f7799SJohannes Weiner 				size = 0;
24309a265114SJohannes Weiner 				scan = 0;
24316b4f7799SJohannes Weiner 			}
24329a265114SJohannes Weiner 			break;
24339a265114SJohannes Weiner 		default:
24349a265114SJohannes Weiner 			/* Look ma, no brain */
24359a265114SJohannes Weiner 			BUG();
24369a265114SJohannes Weiner 		}
24376b4f7799SJohannes Weiner 
24386b4f7799SJohannes Weiner 		*lru_pages += size;
24394111304dSHugh Dickins 		nr[lru] = scan;
244076a33fc3SShaohua Li 	}
24416e08a369SWu Fengguang }
24424f98a2feSRik van Riel 
24439b4f98cdSJohannes Weiner /*
2444a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
24459b4f98cdSJohannes Weiner  */
2446a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
24476b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
24489b4f98cdSJohannes Weiner {
2449ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
24509b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2451e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
24529b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
24539b4f98cdSJohannes Weiner 	enum lru_list lru;
24549b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
24559b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
24569b4f98cdSJohannes Weiner 	struct blk_plug plug;
24571a501907SMel Gorman 	bool scan_adjusted;
24589b4f98cdSJohannes Weiner 
245933377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
24609b4f98cdSJohannes Weiner 
2461e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2462e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2463e82e0561SMel Gorman 
24641a501907SMel Gorman 	/*
24651a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
24661a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
24671a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
24681a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
24691a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
24701a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
24711a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
24721a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
24731a501907SMel Gorman 	 * dropped to zero at the first pass.
24741a501907SMel Gorman 	 */
24751a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
24761a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
24771a501907SMel Gorman 
24789b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
24799b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
24809b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2481e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2482e82e0561SMel Gorman 		unsigned long nr_scanned;
2483e82e0561SMel Gorman 
24849b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
24859b4f98cdSJohannes Weiner 			if (nr[lru]) {
24869b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
24879b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
24889b4f98cdSJohannes Weiner 
24899b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
24902a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
24919b4f98cdSJohannes Weiner 			}
24929b4f98cdSJohannes Weiner 		}
2493e82e0561SMel Gorman 
2494bd041733SMichal Hocko 		cond_resched();
2495bd041733SMichal Hocko 
2496e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2497e82e0561SMel Gorman 			continue;
2498e82e0561SMel Gorman 
24999b4f98cdSJohannes Weiner 		/*
2500e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25011a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2502e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2503e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2504e82e0561SMel Gorman 		 * proportional to the original scan target.
2505e82e0561SMel Gorman 		 */
2506e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2507e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2508e82e0561SMel Gorman 
25091a501907SMel Gorman 		/*
25101a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
25111a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
25121a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
25131a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
25141a501907SMel Gorman 		 */
25151a501907SMel Gorman 		if (!nr_file || !nr_anon)
25161a501907SMel Gorman 			break;
25171a501907SMel Gorman 
2518e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2519e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2520e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2521e82e0561SMel Gorman 			lru = LRU_BASE;
2522e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2523e82e0561SMel Gorman 		} else {
2524e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2525e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2526e82e0561SMel Gorman 			lru = LRU_FILE;
2527e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2528e82e0561SMel Gorman 		}
2529e82e0561SMel Gorman 
2530e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2531e82e0561SMel Gorman 		nr[lru] = 0;
2532e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2533e82e0561SMel Gorman 
2534e82e0561SMel Gorman 		/*
2535e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2536e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2537e82e0561SMel Gorman 		 */
2538e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2539e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2540e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2541e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2542e82e0561SMel Gorman 
2543e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2544e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2545e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2546e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2547e82e0561SMel Gorman 
2548e82e0561SMel Gorman 		scan_adjusted = true;
25499b4f98cdSJohannes Weiner 	}
25509b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
25519b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
25529b4f98cdSJohannes Weiner 
25539b4f98cdSJohannes Weiner 	/*
25549b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
25559b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
25569b4f98cdSJohannes Weiner 	 */
25572a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
25589b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25599b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
25609b4f98cdSJohannes Weiner }
25619b4f98cdSJohannes Weiner 
256223b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
25639e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
256423b9da55SMel Gorman {
2565d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
256623b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
25679e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
256823b9da55SMel Gorman 		return true;
256923b9da55SMel Gorman 
257023b9da55SMel Gorman 	return false;
257123b9da55SMel Gorman }
257223b9da55SMel Gorman 
25734f98a2feSRik van Riel /*
257423b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
257523b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
257623b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
257723b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
257823b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
25793e7d3449SMel Gorman  */
2580a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
25813e7d3449SMel Gorman 					unsigned long nr_reclaimed,
25823e7d3449SMel Gorman 					unsigned long nr_scanned,
25833e7d3449SMel Gorman 					struct scan_control *sc)
25843e7d3449SMel Gorman {
25853e7d3449SMel Gorman 	unsigned long pages_for_compaction;
25863e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2587a9dd0a83SMel Gorman 	int z;
25883e7d3449SMel Gorman 
25893e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
25909e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
25913e7d3449SMel Gorman 		return false;
25923e7d3449SMel Gorman 
25932876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2594dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
25953e7d3449SMel Gorman 		/*
2596dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
25972876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
25982876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2599dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
26003e7d3449SMel Gorman 		 */
26013e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
26023e7d3449SMel Gorman 			return false;
26032876592fSMel Gorman 	} else {
26042876592fSMel Gorman 		/*
2605dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
26062876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
26072876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
26082876592fSMel Gorman 		 * pages that were scanned. This will return to the
26092876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
26102876592fSMel Gorman 		 * the resulting allocation attempt fails
26112876592fSMel Gorman 		 */
26122876592fSMel Gorman 		if (!nr_reclaimed)
26132876592fSMel Gorman 			return false;
26142876592fSMel Gorman 	}
26153e7d3449SMel Gorman 
26163e7d3449SMel Gorman 	/*
26173e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
26183e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
26193e7d3449SMel Gorman 	 */
26209861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2621a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2622ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2623a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
26243e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
26253e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
26263e7d3449SMel Gorman 		return true;
26273e7d3449SMel Gorman 
26283e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2629a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2630a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
26316aa303deSMel Gorman 		if (!managed_zone(zone))
2632a9dd0a83SMel Gorman 			continue;
2633a9dd0a83SMel Gorman 
2634a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2635cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
26363e7d3449SMel Gorman 		case COMPACT_CONTINUE:
26373e7d3449SMel Gorman 			return false;
26383e7d3449SMel Gorman 		default:
2639a9dd0a83SMel Gorman 			/* check next zone */
2640a9dd0a83SMel Gorman 			;
26413e7d3449SMel Gorman 		}
26423e7d3449SMel Gorman 	}
2643a9dd0a83SMel Gorman 	return true;
2644a9dd0a83SMel Gorman }
26453e7d3449SMel Gorman 
2646e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2647e3c1ac58SAndrey Ryabinin {
2648e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2649e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2650e3c1ac58SAndrey Ryabinin }
2651e3c1ac58SAndrey Ryabinin 
2652970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2653f16015fbSJohannes Weiner {
2654cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
26559b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
26562344d7e4SJohannes Weiner 	bool reclaimable = false;
26579b4f98cdSJohannes Weiner 
26589b4f98cdSJohannes Weiner 	do {
26595660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
26605660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2661ef8f2327SMel Gorman 			.pgdat = pgdat,
26629e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
26635660048cSJohannes Weiner 		};
2664a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2665694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
26665660048cSJohannes Weiner 
2667d108c772SAndrey Ryabinin 		memset(&sc->nr, 0, sizeof(sc->nr));
2668d108c772SAndrey Ryabinin 
26699b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
26709b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
26719b4f98cdSJohannes Weiner 
2672694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2673694fbc0fSAndrew Morton 		do {
26746b4f7799SJohannes Weiner 			unsigned long lru_pages;
26758e8ae645SJohannes Weiner 			unsigned long reclaimed;
2676cb731d6cSVladimir Davydov 			unsigned long scanned;
26779b4f98cdSJohannes Weiner 
2678bf8d5d52SRoman Gushchin 			switch (mem_cgroup_protected(root, memcg)) {
2679bf8d5d52SRoman Gushchin 			case MEMCG_PROT_MIN:
2680bf8d5d52SRoman Gushchin 				/*
2681bf8d5d52SRoman Gushchin 				 * Hard protection.
2682bf8d5d52SRoman Gushchin 				 * If there is no reclaimable memory, OOM.
2683bf8d5d52SRoman Gushchin 				 */
2684bf8d5d52SRoman Gushchin 				continue;
2685bf8d5d52SRoman Gushchin 			case MEMCG_PROT_LOW:
2686bf8d5d52SRoman Gushchin 				/*
2687bf8d5d52SRoman Gushchin 				 * Soft protection.
2688bf8d5d52SRoman Gushchin 				 * Respect the protection only as long as
2689bf8d5d52SRoman Gushchin 				 * there is an unprotected supply
2690bf8d5d52SRoman Gushchin 				 * of reclaimable memory from other cgroups.
2691bf8d5d52SRoman Gushchin 				 */
2692d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2693d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2694241994edSJohannes Weiner 					continue;
2695d6622f63SYisheng Xie 				}
2696e27be240SJohannes Weiner 				memcg_memory_event(memcg, MEMCG_LOW);
2697bf8d5d52SRoman Gushchin 				break;
2698bf8d5d52SRoman Gushchin 			case MEMCG_PROT_NONE:
2699bf8d5d52SRoman Gushchin 				break;
2700241994edSJohannes Weiner 			}
2701241994edSJohannes Weiner 
27028e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2703cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2704a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2705a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2706f9be23d6SKonstantin Khlebnikov 
2707a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id,
27089092c71bSJosef Bacik 				    memcg, sc->priority);
2709cb731d6cSVladimir Davydov 
27108e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
27118e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
27128e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
27138e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
27148e8ae645SJohannes Weiner 
27155660048cSJohannes Weiner 			/*
2716a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2717a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2718a9dd0a83SMel Gorman 			 * node.
2719a394cb8eSMichal Hocko 			 *
2720a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2721a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2722a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2723a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
27245660048cSJohannes Weiner 			 */
2725a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2726a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
27275660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
27285660048cSJohannes Weiner 				break;
27295660048cSJohannes Weiner 			}
2730241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
273170ddf637SAnton Vorontsov 
27326b4f7799SJohannes Weiner 		if (reclaim_state) {
2733cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27346b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
27356b4f7799SJohannes Weiner 		}
27366b4f7799SJohannes Weiner 
27378e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
27388e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
273970ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
274070ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
274170ddf637SAnton Vorontsov 
27422344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
27432344d7e4SJohannes Weiner 			reclaimable = true;
27442344d7e4SJohannes Weiner 
2745e3c1ac58SAndrey Ryabinin 		if (current_is_kswapd()) {
2746d108c772SAndrey Ryabinin 			/*
2747e3c1ac58SAndrey Ryabinin 			 * If reclaim is isolating dirty pages under writeback,
2748e3c1ac58SAndrey Ryabinin 			 * it implies that the long-lived page allocation rate
2749e3c1ac58SAndrey Ryabinin 			 * is exceeding the page laundering rate. Either the
2750e3c1ac58SAndrey Ryabinin 			 * global limits are not being effective at throttling
2751e3c1ac58SAndrey Ryabinin 			 * processes due to the page distribution throughout
2752e3c1ac58SAndrey Ryabinin 			 * zones or there is heavy usage of a slow backing
2753e3c1ac58SAndrey Ryabinin 			 * device. The only option is to throttle from reclaim
2754e3c1ac58SAndrey Ryabinin 			 * context which is not ideal as there is no guarantee
2755d108c772SAndrey Ryabinin 			 * the dirtying process is throttled in the same way
2756d108c772SAndrey Ryabinin 			 * balance_dirty_pages() manages.
2757d108c772SAndrey Ryabinin 			 *
2758e3c1ac58SAndrey Ryabinin 			 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2759e3c1ac58SAndrey Ryabinin 			 * count the number of pages under pages flagged for
2760e3c1ac58SAndrey Ryabinin 			 * immediate reclaim and stall if any are encountered
2761e3c1ac58SAndrey Ryabinin 			 * in the nr_immediate check below.
2762d108c772SAndrey Ryabinin 			 */
2763d108c772SAndrey Ryabinin 			if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2764d108c772SAndrey Ryabinin 				set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2765d108c772SAndrey Ryabinin 
2766d108c772SAndrey Ryabinin 			/*
2767d108c772SAndrey Ryabinin 			 * Tag a node as congested if all the dirty pages
2768d108c772SAndrey Ryabinin 			 * scanned were backed by a congested BDI and
2769d108c772SAndrey Ryabinin 			 * wait_iff_congested will stall.
2770d108c772SAndrey Ryabinin 			 */
2771d108c772SAndrey Ryabinin 			if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2772d108c772SAndrey Ryabinin 				set_bit(PGDAT_CONGESTED, &pgdat->flags);
2773d108c772SAndrey Ryabinin 
2774d108c772SAndrey Ryabinin 			/* Allow kswapd to start writing pages during reclaim.*/
2775d108c772SAndrey Ryabinin 			if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2776d108c772SAndrey Ryabinin 				set_bit(PGDAT_DIRTY, &pgdat->flags);
2777d108c772SAndrey Ryabinin 
2778d108c772SAndrey Ryabinin 			/*
2779d108c772SAndrey Ryabinin 			 * If kswapd scans pages marked marked for immediate
2780d108c772SAndrey Ryabinin 			 * reclaim and under writeback (nr_immediate), it
2781d108c772SAndrey Ryabinin 			 * implies that pages are cycling through the LRU
2782d108c772SAndrey Ryabinin 			 * faster than they are written so also forcibly stall.
2783d108c772SAndrey Ryabinin 			 */
2784d108c772SAndrey Ryabinin 			if (sc->nr.immediate)
2785d108c772SAndrey Ryabinin 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2786d108c772SAndrey Ryabinin 		}
2787d108c772SAndrey Ryabinin 
2788d108c772SAndrey Ryabinin 		/*
2789e3c1ac58SAndrey Ryabinin 		 * Legacy memcg will stall in page writeback so avoid forcibly
2790e3c1ac58SAndrey Ryabinin 		 * stalling in wait_iff_congested().
2791e3c1ac58SAndrey Ryabinin 		 */
2792e3c1ac58SAndrey Ryabinin 		if (!global_reclaim(sc) && sane_reclaim(sc) &&
2793e3c1ac58SAndrey Ryabinin 		    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2794e3c1ac58SAndrey Ryabinin 			set_memcg_congestion(pgdat, root, true);
2795e3c1ac58SAndrey Ryabinin 
2796e3c1ac58SAndrey Ryabinin 		/*
2797d108c772SAndrey Ryabinin 		 * Stall direct reclaim for IO completions if underlying BDIs
2798d108c772SAndrey Ryabinin 		 * and node is congested. Allow kswapd to continue until it
2799d108c772SAndrey Ryabinin 		 * starts encountering unqueued dirty pages or cycling through
2800d108c772SAndrey Ryabinin 		 * the LRU too quickly.
2801d108c772SAndrey Ryabinin 		 */
2802d108c772SAndrey Ryabinin 		if (!sc->hibernation_mode && !current_is_kswapd() &&
2803e3c1ac58SAndrey Ryabinin 		   current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2804e3c1ac58SAndrey Ryabinin 			wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2805d108c772SAndrey Ryabinin 
2806a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
28079b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
28082344d7e4SJohannes Weiner 
2809c73322d0SJohannes Weiner 	/*
2810c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2811c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2812c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2813c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2814c73322d0SJohannes Weiner 	 */
2815c73322d0SJohannes Weiner 	if (reclaimable)
2816c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2817c73322d0SJohannes Weiner 
28182344d7e4SJohannes Weiner 	return reclaimable;
2819f16015fbSJohannes Weiner }
2820f16015fbSJohannes Weiner 
282153853e2dSVlastimil Babka /*
2822fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2823fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2824fdd4c614SVlastimil Babka  * should reclaim first.
282553853e2dSVlastimil Babka  */
28264f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2827fe4b1b24SMel Gorman {
282831483b6aSMel Gorman 	unsigned long watermark;
2829fdd4c614SVlastimil Babka 	enum compact_result suitable;
2830fe4b1b24SMel Gorman 
2831fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2832fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2833fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2834fdd4c614SVlastimil Babka 		return true;
2835fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2836fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2837fe4b1b24SMel Gorman 		return false;
2838fe4b1b24SMel Gorman 
2839fdd4c614SVlastimil Babka 	/*
2840fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2841fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2842fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2843fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2844fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2845fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2846fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2847fdd4c614SVlastimil Babka 	 */
2848fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2849fdd4c614SVlastimil Babka 
2850fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2851fe4b1b24SMel Gorman }
2852fe4b1b24SMel Gorman 
28531da177e4SLinus Torvalds /*
28541da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
28551da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
28561da177e4SLinus Torvalds  * request.
28571da177e4SLinus Torvalds  *
28581da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
28591da177e4SLinus Torvalds  * scan then give up on it.
28601da177e4SLinus Torvalds  */
28610a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
28621da177e4SLinus Torvalds {
2863dd1a239fSMel Gorman 	struct zoneref *z;
286454a6eb5cSMel Gorman 	struct zone *zone;
28650608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
28660608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2867619d0d76SWeijie Yang 	gfp_t orig_mask;
286879dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
28691cfb419bSKAMEZAWA Hiroyuki 
2870cc715d99SMel Gorman 	/*
2871cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2872cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2873cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2874cc715d99SMel Gorman 	 */
2875619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2876b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2877cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
28784f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2879b2e18757SMel Gorman 	}
2880cc715d99SMel Gorman 
2881d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2882b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2883b2e18757SMel Gorman 		/*
28841cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
28851cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
28861cfb419bSKAMEZAWA Hiroyuki 		 */
288789b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2888344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2889344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
28901da177e4SLinus Torvalds 				continue;
289165ec02cbSVladimir Davydov 
2892e0887c19SRik van Riel 			/*
2893e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2894e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2895e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2896e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2897e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2898c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2899c7cfa37bSCopot Alexandru 			 * page allocations.
2900e0887c19SRik van Riel 			 */
29010b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29020b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29034f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29040b06496aSJohannes Weiner 				sc->compaction_ready = true;
2905e0887c19SRik van Riel 				continue;
2906e0887c19SRik van Riel 			}
29070b06496aSJohannes Weiner 
29080608f43dSAndrew Morton 			/*
290979dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
291079dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
291179dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
291279dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
291379dafcdcSMel Gorman 			 */
291479dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
291579dafcdcSMel Gorman 				continue;
291679dafcdcSMel Gorman 
291779dafcdcSMel Gorman 			/*
29180608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29190608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29200608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29210608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29220608f43dSAndrew Morton 			 */
29230608f43dSAndrew Morton 			nr_soft_scanned = 0;
2924ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29250608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29260608f43dSAndrew Morton 						&nr_soft_scanned);
29270608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29280608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2929ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2930ac34a1a3SKAMEZAWA Hiroyuki 		}
2931d149e3b2SYing Han 
293279dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
293379dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
293479dafcdcSMel Gorman 			continue;
293579dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2936970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29371da177e4SLinus Torvalds 	}
2938e0c23279SMel Gorman 
293965ec02cbSVladimir Davydov 	/*
2940619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2941619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2942619d0d76SWeijie Yang 	 */
2943619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
29441da177e4SLinus Torvalds }
29451da177e4SLinus Torvalds 
29462a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
29472a2e4885SJohannes Weiner {
29482a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
29492a2e4885SJohannes Weiner 
29502a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
29512a2e4885SJohannes Weiner 	do {
29522a2e4885SJohannes Weiner 		unsigned long refaults;
29532a2e4885SJohannes Weiner 		struct lruvec *lruvec;
29542a2e4885SJohannes Weiner 
29552a2e4885SJohannes Weiner 		if (memcg)
2956ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
29572a2e4885SJohannes Weiner 		else
29582a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
29592a2e4885SJohannes Weiner 
29602a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
29612a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
29622a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
29632a2e4885SJohannes Weiner }
29642a2e4885SJohannes Weiner 
29651da177e4SLinus Torvalds /*
29661da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
29671da177e4SLinus Torvalds  *
29681da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
29691da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
29701da177e4SLinus Torvalds  *
29711da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
29721da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
29735b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
29745b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
29755b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
29765b0830cbSJens Axboe  * work, and the allocation attempt will fail.
2977a41f24eaSNishanth Aravamudan  *
2978a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
2979a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
29801da177e4SLinus Torvalds  */
2981dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
29823115cd91SVladimir Davydov 					  struct scan_control *sc)
29831da177e4SLinus Torvalds {
2984241994edSJohannes Weiner 	int initial_priority = sc->priority;
29852a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
29862a2e4885SJohannes Weiner 	struct zoneref *z;
29872a2e4885SJohannes Weiner 	struct zone *zone;
2988241994edSJohannes Weiner retry:
2989873b4771SKeika Kobayashi 	delayacct_freepages_start();
2990873b4771SKeika Kobayashi 
299189b5fae5SJohannes Weiner 	if (global_reclaim(sc))
29927cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
29931da177e4SLinus Torvalds 
29949e3b2f8cSKonstantin Khlebnikov 	do {
299570ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
299670ddf637SAnton Vorontsov 				sc->priority);
299766e1707bSBalbir Singh 		sc->nr_scanned = 0;
29980a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
2999e0c23279SMel Gorman 
3000bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30010b06496aSJohannes Weiner 			break;
30020b06496aSJohannes Weiner 
30030b06496aSJohannes Weiner 		if (sc->compaction_ready)
30040b06496aSJohannes Weiner 			break;
30051da177e4SLinus Torvalds 
30061da177e4SLinus Torvalds 		/*
30070e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30080e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30090e50ce3bSMinchan Kim 		 */
30100e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30110e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30120b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3013bb21c7ceSKOSAKI Motohiro 
30142a2e4885SJohannes Weiner 	last_pgdat = NULL;
30152a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30162a2e4885SJohannes Weiner 					sc->nodemask) {
30172a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30182a2e4885SJohannes Weiner 			continue;
30192a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
30202a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3021e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
30222a2e4885SJohannes Weiner 	}
30232a2e4885SJohannes Weiner 
3024873b4771SKeika Kobayashi 	delayacct_freepages_end();
3025873b4771SKeika Kobayashi 
3026bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3027bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3028bb21c7ceSKOSAKI Motohiro 
30290cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30300b06496aSJohannes Weiner 	if (sc->compaction_ready)
30317335084dSMel Gorman 		return 1;
30327335084dSMel Gorman 
3033241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3034d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3035241994edSJohannes Weiner 		sc->priority = initial_priority;
3036d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3037d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3038241994edSJohannes Weiner 		goto retry;
3039241994edSJohannes Weiner 	}
3040241994edSJohannes Weiner 
3041bb21c7ceSKOSAKI Motohiro 	return 0;
30421da177e4SLinus Torvalds }
30431da177e4SLinus Torvalds 
3044c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
30455515061dSMel Gorman {
30465515061dSMel Gorman 	struct zone *zone;
30475515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
30485515061dSMel Gorman 	unsigned long free_pages = 0;
30495515061dSMel Gorman 	int i;
30505515061dSMel Gorman 	bool wmark_ok;
30515515061dSMel Gorman 
3052c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3053c73322d0SJohannes Weiner 		return true;
3054c73322d0SJohannes Weiner 
30555515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
30565515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3057d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3058d450abd8SJohannes Weiner 			continue;
3059d450abd8SJohannes Weiner 
3060d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3061675becceSMel Gorman 			continue;
3062675becceSMel Gorman 
30635515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
30645515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
30655515061dSMel Gorman 	}
30665515061dSMel Gorman 
3067675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3068675becceSMel Gorman 	if (!pfmemalloc_reserve)
3069675becceSMel Gorman 		return true;
3070675becceSMel Gorman 
30715515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
30725515061dSMel Gorman 
30735515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
30745515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
307538087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
30765515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
30775515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
30785515061dSMel Gorman 	}
30795515061dSMel Gorman 
30805515061dSMel Gorman 	return wmark_ok;
30815515061dSMel Gorman }
30825515061dSMel Gorman 
30835515061dSMel Gorman /*
30845515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
30855515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
30865515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
308750694c28SMel Gorman  * when the low watermark is reached.
308850694c28SMel Gorman  *
308950694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
309050694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
30915515061dSMel Gorman  */
309250694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
30935515061dSMel Gorman 					nodemask_t *nodemask)
30945515061dSMel Gorman {
3095675becceSMel Gorman 	struct zoneref *z;
30965515061dSMel Gorman 	struct zone *zone;
3097675becceSMel Gorman 	pg_data_t *pgdat = NULL;
30985515061dSMel Gorman 
30995515061dSMel Gorman 	/*
31005515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31015515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31025515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31035515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31045515061dSMel Gorman 	 * processes to block on log_wait_commit().
31055515061dSMel Gorman 	 */
31065515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
310750694c28SMel Gorman 		goto out;
310850694c28SMel Gorman 
310950694c28SMel Gorman 	/*
311050694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
311150694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
311250694c28SMel Gorman 	 */
311350694c28SMel Gorman 	if (fatal_signal_pending(current))
311450694c28SMel Gorman 		goto out;
31155515061dSMel Gorman 
3116675becceSMel Gorman 	/*
3117675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3118675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3119675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3120675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3121675becceSMel Gorman 	 *
3122675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3123675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3124675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3125675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3126675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3127675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3128675becceSMel Gorman 	 * should make reasonable progress.
3129675becceSMel Gorman 	 */
3130675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
313117636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3132675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3133675becceSMel Gorman 			continue;
3134675becceSMel Gorman 
3135675becceSMel Gorman 		/* Throttle based on the first usable node */
31365515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3137c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
313850694c28SMel Gorman 			goto out;
3139675becceSMel Gorman 		break;
3140675becceSMel Gorman 	}
3141675becceSMel Gorman 
3142675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3143675becceSMel Gorman 	if (!pgdat)
3144675becceSMel Gorman 		goto out;
31455515061dSMel Gorman 
314668243e76SMel Gorman 	/* Account for the throttling */
314768243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
314868243e76SMel Gorman 
31495515061dSMel Gorman 	/*
31505515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
31515515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
31525515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
31535515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
31545515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
31555515061dSMel Gorman 	 * second before continuing.
31565515061dSMel Gorman 	 */
31575515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
31585515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3159c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
316050694c28SMel Gorman 
316150694c28SMel Gorman 		goto check_pending;
31625515061dSMel Gorman 	}
31635515061dSMel Gorman 
31645515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
31655515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3166c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
316750694c28SMel Gorman 
316850694c28SMel Gorman check_pending:
316950694c28SMel Gorman 	if (fatal_signal_pending(current))
317050694c28SMel Gorman 		return true;
317150694c28SMel Gorman 
317250694c28SMel Gorman out:
317350694c28SMel Gorman 	return false;
31745515061dSMel Gorman }
31755515061dSMel Gorman 
3176dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3177327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
317866e1707bSBalbir Singh {
317933906bc5SMel Gorman 	unsigned long nr_reclaimed;
318066e1707bSBalbir Singh 	struct scan_control sc = {
318122fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3182f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3183b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3184ee814fe2SJohannes Weiner 		.order = order,
3185ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3186ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3187ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3188a6dc60f8SJohannes Weiner 		.may_unmap = 1,
31892e2e4259SKOSAKI Motohiro 		.may_swap = 1,
319066e1707bSBalbir Singh 	};
319166e1707bSBalbir Singh 
31925515061dSMel Gorman 	/*
3193bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3194bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3195bb451fdfSGreg Thelen 	 */
3196bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3197bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3198bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3199bb451fdfSGreg Thelen 
3200bb451fdfSGreg Thelen 	/*
320150694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
320250694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
320350694c28SMel Gorman 	 * point.
32045515061dSMel Gorman 	 */
3205f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32065515061dSMel Gorman 		return 1;
32075515061dSMel Gorman 
320833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
320933906bc5SMel Gorman 				sc.may_writepage,
3210f2f43e56SNick Desaulniers 				sc.gfp_mask,
3211e5146b12SMel Gorman 				sc.reclaim_idx);
321233906bc5SMel Gorman 
32133115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
321433906bc5SMel Gorman 
321533906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
321633906bc5SMel Gorman 
321733906bc5SMel Gorman 	return nr_reclaimed;
321866e1707bSBalbir Singh }
321966e1707bSBalbir Singh 
3220c255a458SAndrew Morton #ifdef CONFIG_MEMCG
322166e1707bSBalbir Singh 
3222a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32234e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3224ef8f2327SMel Gorman 						pg_data_t *pgdat,
32250ae5e89cSYing Han 						unsigned long *nr_scanned)
32264e416953SBalbir Singh {
32274e416953SBalbir Singh 	struct scan_control sc = {
3228b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3229ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
32304e416953SBalbir Singh 		.may_writepage = !laptop_mode,
32314e416953SBalbir Singh 		.may_unmap = 1,
3232b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
32334e416953SBalbir Singh 		.may_swap = !noswap,
32344e416953SBalbir Singh 	};
32356b4f7799SJohannes Weiner 	unsigned long lru_pages;
32360ae5e89cSYing Han 
32374e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
32384e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3239bdce6d9eSKOSAKI Motohiro 
32409e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3241bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3242e5146b12SMel Gorman 						      sc.gfp_mask,
3243e5146b12SMel Gorman 						      sc.reclaim_idx);
3244bdce6d9eSKOSAKI Motohiro 
32454e416953SBalbir Singh 	/*
32464e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
32474e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3248a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
32494e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
32504e416953SBalbir Singh 	 * the priority and make it zero.
32514e416953SBalbir Singh 	 */
3252ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3253bdce6d9eSKOSAKI Motohiro 
3254bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3255bdce6d9eSKOSAKI Motohiro 
32560ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
32574e416953SBalbir Singh 	return sc.nr_reclaimed;
32584e416953SBalbir Singh }
32594e416953SBalbir Singh 
326072835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3261b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
32628c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3263b70a2a21SJohannes Weiner 					   bool may_swap)
326466e1707bSBalbir Singh {
32654e416953SBalbir Singh 	struct zonelist *zonelist;
3266bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3267889976dbSYing Han 	int nid;
3268499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
326966e1707bSBalbir Singh 	struct scan_control sc = {
3270b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
32717dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3272ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3273b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3274ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3275ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
327666e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3277a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3278b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3279a09ed5e0SYing Han 	};
328066e1707bSBalbir Singh 
3281889976dbSYing Han 	/*
3282889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3283889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3284889976dbSYing Han 	 * scan does not need to be the current node.
3285889976dbSYing Han 	 */
328672835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3287889976dbSYing Han 
3288c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3289bdce6d9eSKOSAKI Motohiro 
3290bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3291bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3292e5146b12SMel Gorman 					    sc.gfp_mask,
3293e5146b12SMel Gorman 					    sc.reclaim_idx);
3294bdce6d9eSKOSAKI Motohiro 
3295499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
32963115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3297499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3298bdce6d9eSKOSAKI Motohiro 
3299bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3300bdce6d9eSKOSAKI Motohiro 
3301bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
330266e1707bSBalbir Singh }
330366e1707bSBalbir Singh #endif
330466e1707bSBalbir Singh 
33051d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3306ef8f2327SMel Gorman 				struct scan_control *sc)
3307f16015fbSJohannes Weiner {
3308b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3309b95a2f2dSJohannes Weiner 
3310b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3311b95a2f2dSJohannes Weiner 		return;
3312b95a2f2dSJohannes Weiner 
3313b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3314b95a2f2dSJohannes Weiner 	do {
3315ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3316f16015fbSJohannes Weiner 
33172a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
33181a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33199e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3320b95a2f2dSJohannes Weiner 
3321b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3322b95a2f2dSJohannes Weiner 	} while (memcg);
3323f16015fbSJohannes Weiner }
3324f16015fbSJohannes Weiner 
3325e716f2ebSMel Gorman /*
3326e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3327e716f2ebSMel Gorman  * and classzone_idx
3328e716f2ebSMel Gorman  */
3329e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
333060cefed4SJohannes Weiner {
3331e716f2ebSMel Gorman 	int i;
3332e716f2ebSMel Gorman 	unsigned long mark = -1;
3333e716f2ebSMel Gorman 	struct zone *zone;
333460cefed4SJohannes Weiner 
3335e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3336e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
33376256c6b4SMel Gorman 
3338e716f2ebSMel Gorman 		if (!managed_zone(zone))
3339e716f2ebSMel Gorman 			continue;
3340e716f2ebSMel Gorman 
3341e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3342e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
33436256c6b4SMel Gorman 			return true;
334460cefed4SJohannes Weiner 	}
334560cefed4SJohannes Weiner 
3346e716f2ebSMel Gorman 	/*
3347e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3348e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3349e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3350e716f2ebSMel Gorman 	 */
3351e716f2ebSMel Gorman 	if (mark == -1)
3352e716f2ebSMel Gorman 		return true;
3353e716f2ebSMel Gorman 
3354e716f2ebSMel Gorman 	return false;
3355e716f2ebSMel Gorman }
3356e716f2ebSMel Gorman 
3357631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3358631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3359631b6e08SMel Gorman {
3360631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3361631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3362631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3363631b6e08SMel Gorman }
3364631b6e08SMel Gorman 
33651741c877SMel Gorman /*
33665515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
33675515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
33685515061dSMel Gorman  *
33695515061dSMel Gorman  * Returns true if kswapd is ready to sleep
33705515061dSMel Gorman  */
3371d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3372f50de2d3SMel Gorman {
33735515061dSMel Gorman 	/*
33749e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3375c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
33769e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
33779e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
33789e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
33799e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
33809e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
33819e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
33829e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
33839e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
33849e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
33855515061dSMel Gorman 	 */
33869e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
33879e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3388f50de2d3SMel Gorman 
3389c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3390c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3391c73322d0SJohannes Weiner 		return true;
3392c73322d0SJohannes Weiner 
3393e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3394631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3395333b0a45SShantanu Goel 		return true;
33961d82de61SMel Gorman 	}
33971d82de61SMel Gorman 
3398333b0a45SShantanu Goel 	return false;
3399f50de2d3SMel Gorman }
3400f50de2d3SMel Gorman 
34011da177e4SLinus Torvalds /*
34021d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
34031d82de61SMel Gorman  * zone that is currently unbalanced.
3404b8e83b94SMel Gorman  *
3405b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3406283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3407283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
340875485363SMel Gorman  */
34091d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3410accf6242SVlastimil Babka 			       struct scan_control *sc)
341175485363SMel Gorman {
34121d82de61SMel Gorman 	struct zone *zone;
34131d82de61SMel Gorman 	int z;
341475485363SMel Gorman 
34151d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
34161d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3417970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
34181d82de61SMel Gorman 		zone = pgdat->node_zones + z;
34196aa303deSMel Gorman 		if (!managed_zone(zone))
34201d82de61SMel Gorman 			continue;
34217c954f6dSMel Gorman 
34221d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
34237c954f6dSMel Gorman 	}
34247c954f6dSMel Gorman 
34251d82de61SMel Gorman 	/*
34261d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
34271d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
34281d82de61SMel Gorman 	 */
3429970a39a3SMel Gorman 	shrink_node(pgdat, sc);
34301d82de61SMel Gorman 
34311d82de61SMel Gorman 	/*
34321d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
34331d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
34341d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
34351d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
34361d82de61SMel Gorman 	 * can direct reclaim/compact.
34371d82de61SMel Gorman 	 */
34389861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
34391d82de61SMel Gorman 		sc->order = 0;
34401d82de61SMel Gorman 
3441b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
344275485363SMel Gorman }
344375485363SMel Gorman 
344475485363SMel Gorman /*
34451d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
34461d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
34471d82de61SMel Gorman  * balanced.
34481da177e4SLinus Torvalds  *
34491d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
34501da177e4SLinus Torvalds  *
34511da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
345241858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
34531d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
34541d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
34551d82de61SMel Gorman  * balanced.
34561da177e4SLinus Torvalds  */
3457accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
34581da177e4SLinus Torvalds {
34591da177e4SLinus Torvalds 	int i;
34600608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
34610608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
34621d82de61SMel Gorman 	struct zone *zone;
3463179e9639SAndrew Morton 	struct scan_control sc = {
3464179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3465ee814fe2SJohannes Weiner 		.order = order,
3466b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3467ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3468a6dc60f8SJohannes Weiner 		.may_unmap = 1,
34692e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3470179e9639SAndrew Morton 	};
347193781325SOmar Sandoval 
347293781325SOmar Sandoval 	__fs_reclaim_acquire();
347393781325SOmar Sandoval 
3474f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
34751da177e4SLinus Torvalds 
34769e3b2f8cSKonstantin Khlebnikov 	do {
3477c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3478b8e83b94SMel Gorman 		bool raise_priority = true;
347993781325SOmar Sandoval 		bool ret;
3480b8e83b94SMel Gorman 
348184c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
34821da177e4SLinus Torvalds 
348386c79f6bSMel Gorman 		/*
348484c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
348584c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
348684c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
348784c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
348884c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
348984c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
349084c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
349184c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
349286c79f6bSMel Gorman 		 */
349386c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
349486c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
349586c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
34966aa303deSMel Gorman 				if (!managed_zone(zone))
349786c79f6bSMel Gorman 					continue;
349886c79f6bSMel Gorman 
3499970a39a3SMel Gorman 				sc.reclaim_idx = i;
350086c79f6bSMel Gorman 				break;
350186c79f6bSMel Gorman 			}
350286c79f6bSMel Gorman 		}
350386c79f6bSMel Gorman 
350486c79f6bSMel Gorman 		/*
3505e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3506e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3507e716f2ebSMel Gorman 		 * have adjusted it.
350886c79f6bSMel Gorman 		 */
3509e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
35101da177e4SLinus Torvalds 			goto out;
3511e1dbeda6SAndrew Morton 
35121da177e4SLinus Torvalds 		/*
35131d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
35141d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
35151d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
35161d82de61SMel Gorman 		 * about consistent aging.
35171d82de61SMel Gorman 		 */
3518ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
35191d82de61SMel Gorman 
35201d82de61SMel Gorman 		/*
3521b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3522b7ea3c41SMel Gorman 		 * even in laptop mode.
3523b7ea3c41SMel Gorman 		 */
3524047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3525b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3526b7ea3c41SMel Gorman 
35271d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
35281da177e4SLinus Torvalds 		sc.nr_scanned = 0;
35290608f43dSAndrew Morton 		nr_soft_scanned = 0;
3530ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
35311d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
35320608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
35330608f43dSAndrew Morton 
353432a4330dSRik van Riel 		/*
35351d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
35361d82de61SMel Gorman 		 * enough pages are already being scanned that that high
35371d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
353832a4330dSRik van Riel 		 */
3539970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3540b8e83b94SMel Gorman 			raise_priority = false;
3541d7868daeSMel Gorman 
35425515061dSMel Gorman 		/*
35435515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
35445515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
35455515061dSMel Gorman 		 * able to safely make forward progress. Wake them
35465515061dSMel Gorman 		 */
35475515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3548c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3549cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
35505515061dSMel Gorman 
3551b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
355293781325SOmar Sandoval 		__fs_reclaim_release();
355393781325SOmar Sandoval 		ret = try_to_freeze();
355493781325SOmar Sandoval 		__fs_reclaim_acquire();
355593781325SOmar Sandoval 		if (ret || kthread_should_stop())
3556b8e83b94SMel Gorman 			break;
3557b8e83b94SMel Gorman 
3558b8e83b94SMel Gorman 		/*
3559b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3560b8e83b94SMel Gorman 		 * progress in reclaiming pages
3561b8e83b94SMel Gorman 		 */
3562c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3563c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3564b8e83b94SMel Gorman 			sc.priority--;
35651d82de61SMel Gorman 	} while (sc.priority >= 1);
35661da177e4SLinus Torvalds 
3567c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3568c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3569c73322d0SJohannes Weiner 
3570b8e83b94SMel Gorman out:
35712a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
357293781325SOmar Sandoval 	__fs_reclaim_release();
35730abdee2bSMel Gorman 	/*
35741d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
35751d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
35761d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
35771d82de61SMel Gorman 	 * remain at the higher level.
35780abdee2bSMel Gorman 	 */
35791d82de61SMel Gorman 	return sc.order;
35801da177e4SLinus Torvalds }
35811da177e4SLinus Torvalds 
3582e716f2ebSMel Gorman /*
3583e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3584e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3585e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3586e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3587e716f2ebSMel Gorman  * was recently woke for.
3588e716f2ebSMel Gorman  */
3589e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3590e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3591e716f2ebSMel Gorman {
3592e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3593e716f2ebSMel Gorman 		return classzone_idx;
3594e716f2ebSMel Gorman 
3595e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3596e716f2ebSMel Gorman }
3597e716f2ebSMel Gorman 
359838087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
359938087d9bSMel Gorman 				unsigned int classzone_idx)
3600f0bc0a60SKOSAKI Motohiro {
3601f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3602f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3603f0bc0a60SKOSAKI Motohiro 
3604f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3605f0bc0a60SKOSAKI Motohiro 		return;
3606f0bc0a60SKOSAKI Motohiro 
3607f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3608f0bc0a60SKOSAKI Motohiro 
3609333b0a45SShantanu Goel 	/*
3610333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3611333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3612333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3613333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3614333b0a45SShantanu Goel 	 * succeed.
3615333b0a45SShantanu Goel 	 */
3616d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3617fd901c95SVlastimil Babka 		/*
3618fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3619fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3620fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3621fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3622fd901c95SVlastimil Babka 		 */
3623fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3624fd901c95SVlastimil Babka 
3625fd901c95SVlastimil Babka 		/*
3626fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3627fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3628fd901c95SVlastimil Babka 		 */
362938087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3630fd901c95SVlastimil Babka 
3631f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
363238087d9bSMel Gorman 
363338087d9bSMel Gorman 		/*
363438087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
363538087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
363638087d9bSMel Gorman 		 * the previous request that slept prematurely.
363738087d9bSMel Gorman 		 */
363838087d9bSMel Gorman 		if (remaining) {
3639e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
364038087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
364138087d9bSMel Gorman 		}
364238087d9bSMel Gorman 
3643f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3644f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3645f0bc0a60SKOSAKI Motohiro 	}
3646f0bc0a60SKOSAKI Motohiro 
3647f0bc0a60SKOSAKI Motohiro 	/*
3648f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3649f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3650f0bc0a60SKOSAKI Motohiro 	 */
3651d9f21d42SMel Gorman 	if (!remaining &&
3652d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3653f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3654f0bc0a60SKOSAKI Motohiro 
3655f0bc0a60SKOSAKI Motohiro 		/*
3656f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3657f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3658f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3659f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3660f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3661f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3662f0bc0a60SKOSAKI Motohiro 		 */
3663f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
36641c7e7f6cSAaditya Kumar 
36651c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3666f0bc0a60SKOSAKI Motohiro 			schedule();
36671c7e7f6cSAaditya Kumar 
3668f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3669f0bc0a60SKOSAKI Motohiro 	} else {
3670f0bc0a60SKOSAKI Motohiro 		if (remaining)
3671f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3672f0bc0a60SKOSAKI Motohiro 		else
3673f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3674f0bc0a60SKOSAKI Motohiro 	}
3675f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3676f0bc0a60SKOSAKI Motohiro }
3677f0bc0a60SKOSAKI Motohiro 
36781da177e4SLinus Torvalds /*
36791da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
36801da177e4SLinus Torvalds  * from the init process.
36811da177e4SLinus Torvalds  *
36821da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
36831da177e4SLinus Torvalds  * free memory available even if there is no other activity
36841da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
36851da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
36861da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
36871da177e4SLinus Torvalds  *
36881da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
36891da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
36901da177e4SLinus Torvalds  */
36911da177e4SLinus Torvalds static int kswapd(void *p)
36921da177e4SLinus Torvalds {
3693e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3694e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
36951da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
36961da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3697f0bc0a60SKOSAKI Motohiro 
36981da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
36991da177e4SLinus Torvalds 		.reclaimed_slab = 0,
37001da177e4SLinus Torvalds 	};
3701a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
37021da177e4SLinus Torvalds 
3703174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3704c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
37051da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
37061da177e4SLinus Torvalds 
37071da177e4SLinus Torvalds 	/*
37081da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
37091da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
37101da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
37111da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
37121da177e4SLinus Torvalds 	 *
37131da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
37141da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
37151da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
37161da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
37171da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
37181da177e4SLinus Torvalds 	 */
3719930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
372083144186SRafael J. Wysocki 	set_freezable();
37211da177e4SLinus Torvalds 
3722e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3723e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
37241da177e4SLinus Torvalds 	for ( ; ; ) {
37256f6313d4SJeff Liu 		bool ret;
37263e1d1d28SChristoph Lameter 
3727e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3728e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3729e716f2ebSMel Gorman 
373038087d9bSMel Gorman kswapd_try_sleep:
373138087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
373238087d9bSMel Gorman 					classzone_idx);
3733215ddd66SMel Gorman 
373438087d9bSMel Gorman 		/* Read the new order and classzone_idx */
373538087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3736e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
373738087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3738e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
37391da177e4SLinus Torvalds 
37408fe23e05SDavid Rientjes 		ret = try_to_freeze();
37418fe23e05SDavid Rientjes 		if (kthread_should_stop())
37428fe23e05SDavid Rientjes 			break;
37438fe23e05SDavid Rientjes 
37448fe23e05SDavid Rientjes 		/*
37458fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
37468fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3747b1296cc4SRafael J. Wysocki 		 */
374838087d9bSMel Gorman 		if (ret)
374938087d9bSMel Gorman 			continue;
37501d82de61SMel Gorman 
375138087d9bSMel Gorman 		/*
375238087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
375338087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
375438087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
375538087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
375638087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
375738087d9bSMel Gorman 		 * request (alloc_order).
375838087d9bSMel Gorman 		 */
3759e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3760e5146b12SMel Gorman 						alloc_order);
376138087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
376238087d9bSMel Gorman 		if (reclaim_order < alloc_order)
376338087d9bSMel Gorman 			goto kswapd_try_sleep;
376433906bc5SMel Gorman 	}
3765b0a8cc58STakamori Yamaguchi 
376671abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3767b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
376871abdc15SJohannes Weiner 
37691da177e4SLinus Torvalds 	return 0;
37701da177e4SLinus Torvalds }
37711da177e4SLinus Torvalds 
37721da177e4SLinus Torvalds /*
37735ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
37745ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
37755ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
37765ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
37775ecd9d40SDavid Rientjes  * needed.
37781da177e4SLinus Torvalds  */
37795ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
37805ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
37811da177e4SLinus Torvalds {
37821da177e4SLinus Torvalds 	pg_data_t *pgdat;
37831da177e4SLinus Torvalds 
37846aa303deSMel Gorman 	if (!managed_zone(zone))
37851da177e4SLinus Torvalds 		return;
37861da177e4SLinus Torvalds 
37875ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
37881da177e4SLinus Torvalds 		return;
378988f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3790e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3791e716f2ebSMel Gorman 							   classzone_idx);
379238087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
37938d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
37941da177e4SLinus Torvalds 		return;
3795e1a55637SMel Gorman 
37965ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
37975ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
37985ecd9d40SDavid Rientjes 	    pgdat_balanced(pgdat, order, classzone_idx)) {
37995ecd9d40SDavid Rientjes 		/*
38005ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
38015ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
38025ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
38035ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
38045ecd9d40SDavid Rientjes 		 * ratelimit its work.
38055ecd9d40SDavid Rientjes 		 */
38065ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
38075ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3808c73322d0SJohannes Weiner 		return;
38095ecd9d40SDavid Rientjes 	}
3810c73322d0SJohannes Weiner 
38115ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
38125ecd9d40SDavid Rientjes 				      gfp_flags);
38138d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
38141da177e4SLinus Torvalds }
38151da177e4SLinus Torvalds 
3816c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
38171da177e4SLinus Torvalds /*
38187b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3819d6277db4SRafael J. Wysocki  * freed pages.
3820d6277db4SRafael J. Wysocki  *
3821d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3822d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3823d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
38241da177e4SLinus Torvalds  */
38257b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
38261da177e4SLinus Torvalds {
3827d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3828d6277db4SRafael J. Wysocki 	struct scan_control sc = {
38297b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3830ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3831b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
38329e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3833ee814fe2SJohannes Weiner 		.may_writepage = 1,
3834ee814fe2SJohannes Weiner 		.may_unmap = 1,
3835ee814fe2SJohannes Weiner 		.may_swap = 1,
3836ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
38371da177e4SLinus Torvalds 	};
38387b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
38397b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
38407b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3841499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
38421da177e4SLinus Torvalds 
3843d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
384493781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
3845d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
38467b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3847d6277db4SRafael J. Wysocki 
38483115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3849d6277db4SRafael J. Wysocki 
38507b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3851499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
385293781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
3853d6277db4SRafael J. Wysocki 
38547b51755cSKOSAKI Motohiro 	return nr_reclaimed;
38551da177e4SLinus Torvalds }
3856c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
38571da177e4SLinus Torvalds 
38581da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
38591da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
38601da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
38611da177e4SLinus Torvalds    restore their cpu bindings. */
3862517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
38631da177e4SLinus Torvalds {
386458c0a4a7SYasunori Goto 	int nid;
38651da177e4SLinus Torvalds 
386648fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3867c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3868a70f7302SRusty Russell 		const struct cpumask *mask;
3869a70f7302SRusty Russell 
3870a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3871c5f59f08SMike Travis 
38723e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
38731da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3874c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
38751da177e4SLinus Torvalds 	}
3876517bbed9SSebastian Andrzej Siewior 	return 0;
38771da177e4SLinus Torvalds }
38781da177e4SLinus Torvalds 
38793218ae14SYasunori Goto /*
38803218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
38813218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
38823218ae14SYasunori Goto  */
38833218ae14SYasunori Goto int kswapd_run(int nid)
38843218ae14SYasunori Goto {
38853218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
38863218ae14SYasunori Goto 	int ret = 0;
38873218ae14SYasunori Goto 
38883218ae14SYasunori Goto 	if (pgdat->kswapd)
38893218ae14SYasunori Goto 		return 0;
38903218ae14SYasunori Goto 
38913218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
38923218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
38933218ae14SYasunori Goto 		/* failure at boot is fatal */
3894c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3895d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3896d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3897d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
38983218ae14SYasunori Goto 	}
38993218ae14SYasunori Goto 	return ret;
39003218ae14SYasunori Goto }
39013218ae14SYasunori Goto 
39028fe23e05SDavid Rientjes /*
3903d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3904bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
39058fe23e05SDavid Rientjes  */
39068fe23e05SDavid Rientjes void kswapd_stop(int nid)
39078fe23e05SDavid Rientjes {
39088fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
39098fe23e05SDavid Rientjes 
3910d8adde17SJiang Liu 	if (kswapd) {
39118fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3912d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3913d8adde17SJiang Liu 	}
39148fe23e05SDavid Rientjes }
39158fe23e05SDavid Rientjes 
39161da177e4SLinus Torvalds static int __init kswapd_init(void)
39171da177e4SLinus Torvalds {
3918517bbed9SSebastian Andrzej Siewior 	int nid, ret;
391969e05944SAndrew Morton 
39201da177e4SLinus Torvalds 	swap_setup();
392148fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
39223218ae14SYasunori Goto  		kswapd_run(nid);
3923517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3924517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3925517bbed9SSebastian Andrzej Siewior 					NULL);
3926517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
39271da177e4SLinus Torvalds 	return 0;
39281da177e4SLinus Torvalds }
39291da177e4SLinus Torvalds 
39301da177e4SLinus Torvalds module_init(kswapd_init)
39319eeff239SChristoph Lameter 
39329eeff239SChristoph Lameter #ifdef CONFIG_NUMA
39339eeff239SChristoph Lameter /*
3934a5f5f91dSMel Gorman  * Node reclaim mode
39359eeff239SChristoph Lameter  *
3936a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
39379eeff239SChristoph Lameter  * the watermarks.
39389eeff239SChristoph Lameter  */
3939a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
39409eeff239SChristoph Lameter 
39411b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
39427d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
39431b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
394495bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
39451b2ffb78SChristoph Lameter 
39469eeff239SChristoph Lameter /*
3947a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
3948a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3949a92f7126SChristoph Lameter  * a zone.
3950a92f7126SChristoph Lameter  */
3951a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
3952a92f7126SChristoph Lameter 
39539eeff239SChristoph Lameter /*
3954a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
39559614634fSChristoph Lameter  * occur.
39569614634fSChristoph Lameter  */
39579614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
39589614634fSChristoph Lameter 
39599614634fSChristoph Lameter /*
39600ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
39610ff38490SChristoph Lameter  * slab reclaim needs to occur.
39620ff38490SChristoph Lameter  */
39630ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
39640ff38490SChristoph Lameter 
396511fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
396690afa5deSMel Gorman {
396711fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
396811fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
396911fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
397090afa5deSMel Gorman 
397190afa5deSMel Gorman 	/*
397290afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
397390afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
397490afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
397590afa5deSMel Gorman 	 */
397690afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
397790afa5deSMel Gorman }
397890afa5deSMel Gorman 
397990afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3980a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
398190afa5deSMel Gorman {
3982d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
3983d031a157SAlexandru Moise 	unsigned long delta = 0;
398490afa5deSMel Gorman 
398590afa5deSMel Gorman 	/*
398695bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
398790afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
398811fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
398990afa5deSMel Gorman 	 * a better estimate
399090afa5deSMel Gorman 	 */
3991a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
3992a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
399390afa5deSMel Gorman 	else
3994a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
399590afa5deSMel Gorman 
399690afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
3997a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
3998a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
399990afa5deSMel Gorman 
400090afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
400190afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
400290afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
400390afa5deSMel Gorman 
400490afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
400590afa5deSMel Gorman }
400690afa5deSMel Gorman 
40070ff38490SChristoph Lameter /*
4008a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
40099eeff239SChristoph Lameter  */
4010a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
40119eeff239SChristoph Lameter {
40127fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
401369e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
40149eeff239SChristoph Lameter 	struct task_struct *p = current;
40159eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
4016499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4017179e9639SAndrew Morton 	struct scan_control sc = {
401862b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4019f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4020bd2f6199SJohannes Weiner 		.order = order,
4021a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4022a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4023a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4024ee814fe2SJohannes Weiner 		.may_swap = 1,
4025f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4026179e9639SAndrew Morton 	};
40279eeff239SChristoph Lameter 
40289eeff239SChristoph Lameter 	cond_resched();
402993781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4030d4f7796eSChristoph Lameter 	/*
403195bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4032d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
403395bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4034d4f7796eSChristoph Lameter 	 */
4035499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4036499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
40379eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
40389eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
4039c84db23cSChristoph Lameter 
4040a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4041a92f7126SChristoph Lameter 		/*
4042894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
40430ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4044a92f7126SChristoph Lameter 		 */
4045a92f7126SChristoph Lameter 		do {
4046970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
40479e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
40480ff38490SChristoph Lameter 	}
4049a92f7126SChristoph Lameter 
40509eeff239SChristoph Lameter 	p->reclaim_state = NULL;
4051499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4052499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
405393781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4054a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
40559eeff239SChristoph Lameter }
4056179e9639SAndrew Morton 
4057a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4058179e9639SAndrew Morton {
4059d773ed6bSDavid Rientjes 	int ret;
4060179e9639SAndrew Morton 
4061179e9639SAndrew Morton 	/*
4062a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
40630ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
406434aa1330SChristoph Lameter 	 *
40659614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
40669614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4067a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4068a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
40699614634fSChristoph Lameter 	 * unmapped file backed pages.
4070179e9639SAndrew Morton 	 */
4071a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4072385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4073a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4074179e9639SAndrew Morton 
4075179e9639SAndrew Morton 	/*
4076d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4077179e9639SAndrew Morton 	 */
4078d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4079a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4080179e9639SAndrew Morton 
4081179e9639SAndrew Morton 	/*
4082a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4083179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4084179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4085179e9639SAndrew Morton 	 * as wide as possible.
4086179e9639SAndrew Morton 	 */
4087a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4088a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4089d773ed6bSDavid Rientjes 
4090a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4091a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4092fa5e084eSMel Gorman 
4093a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4094a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4095d773ed6bSDavid Rientjes 
409624cf7251SMel Gorman 	if (!ret)
409724cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
409824cf7251SMel Gorman 
4099d773ed6bSDavid Rientjes 	return ret;
4100179e9639SAndrew Morton }
41019eeff239SChristoph Lameter #endif
4102894bc310SLee Schermerhorn 
4103894bc310SLee Schermerhorn /*
4104894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4105894bc310SLee Schermerhorn  * @page: the page to test
4106894bc310SLee Schermerhorn  *
4107894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
410839b5f29aSHugh Dickins  * lists vs unevictable list.
4109894bc310SLee Schermerhorn  *
4110894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4111ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4112b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4113ba9ddf49SLee Schermerhorn  *
4114894bc310SLee Schermerhorn  */
411539b5f29aSHugh Dickins int page_evictable(struct page *page)
4116894bc310SLee Schermerhorn {
4117e92bb4ddSHuang Ying 	int ret;
4118e92bb4ddSHuang Ying 
4119e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4120e92bb4ddSHuang Ying 	rcu_read_lock();
4121e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4122e92bb4ddSHuang Ying 	rcu_read_unlock();
4123e92bb4ddSHuang Ying 	return ret;
4124894bc310SLee Schermerhorn }
412589e004eaSLee Schermerhorn 
412685046579SHugh Dickins #ifdef CONFIG_SHMEM
412789e004eaSLee Schermerhorn /**
412824513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
412924513264SHugh Dickins  * @pages:	array of pages to check
413024513264SHugh Dickins  * @nr_pages:	number of pages to check
413189e004eaSLee Schermerhorn  *
413224513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
413385046579SHugh Dickins  *
413485046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
413589e004eaSLee Schermerhorn  */
413624513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
413789e004eaSLee Schermerhorn {
4138925b7673SJohannes Weiner 	struct lruvec *lruvec;
4139785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
414024513264SHugh Dickins 	int pgscanned = 0;
414124513264SHugh Dickins 	int pgrescued = 0;
414289e004eaSLee Schermerhorn 	int i;
414389e004eaSLee Schermerhorn 
414424513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
414524513264SHugh Dickins 		struct page *page = pages[i];
4146785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
414789e004eaSLee Schermerhorn 
414824513264SHugh Dickins 		pgscanned++;
4149785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4150785b99feSMel Gorman 			if (pgdat)
4151785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4152785b99feSMel Gorman 			pgdat = pagepgdat;
4153785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
415489e004eaSLee Schermerhorn 		}
4155785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
415689e004eaSLee Schermerhorn 
415724513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
415824513264SHugh Dickins 			continue;
415989e004eaSLee Schermerhorn 
416039b5f29aSHugh Dickins 		if (page_evictable(page)) {
416124513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
416224513264SHugh Dickins 
4163309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
416424513264SHugh Dickins 			ClearPageUnevictable(page);
4165fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4166fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
416724513264SHugh Dickins 			pgrescued++;
416889e004eaSLee Schermerhorn 		}
416989e004eaSLee Schermerhorn 	}
417024513264SHugh Dickins 
4171785b99feSMel Gorman 	if (pgdat) {
417224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
417324513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4174785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
417524513264SHugh Dickins 	}
417685046579SHugh Dickins }
417785046579SHugh Dickins #endif /* CONFIG_SHMEM */
4178