xref: /openbmc/linux/mm/vmscan.c (revision 4b85afbdacd290c7a22c96df40a6433fdcacb509)
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>
52eb414681SJohannes Weiner #include <linux/psi.h>
531da177e4SLinus Torvalds 
541da177e4SLinus Torvalds #include <asm/tlbflush.h>
551da177e4SLinus Torvalds #include <asm/div64.h>
561da177e4SLinus Torvalds 
571da177e4SLinus Torvalds #include <linux/swapops.h>
58117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
591da177e4SLinus Torvalds 
600f8053a5SNick Piggin #include "internal.h"
610f8053a5SNick Piggin 
6233906bc5SMel Gorman #define CREATE_TRACE_POINTS
6333906bc5SMel Gorman #include <trace/events/vmscan.h>
6433906bc5SMel Gorman 
651da177e4SLinus Torvalds struct scan_control {
6622fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6722fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6822fba335SKOSAKI Motohiro 
69ee814fe2SJohannes Weiner 	/*
70ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
71ee814fe2SJohannes Weiner 	 * are scanned.
72ee814fe2SJohannes Weiner 	 */
73ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
749e3b2f8cSKonstantin Khlebnikov 
755f53e762SKOSAKI Motohiro 	/*
76f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
77f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
78f16015fbSJohannes Weiner 	 */
79f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8066e1707bSBalbir Singh 
811276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
82ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
83ee814fe2SJohannes Weiner 
84ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
85ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
86ee814fe2SJohannes Weiner 
87ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
88ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
89ee814fe2SJohannes Weiner 
90d6622f63SYisheng Xie 	/*
91d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
92d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
93d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
94d6622f63SYisheng Xie 	 */
95d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
96d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
97241994edSJohannes Weiner 
98ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
99ee814fe2SJohannes Weiner 
100ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
101ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
102ee814fe2SJohannes Weiner 
103bb451fdfSGreg Thelen 	/* Allocation order */
104bb451fdfSGreg Thelen 	s8 order;
105bb451fdfSGreg Thelen 
106bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
107bb451fdfSGreg Thelen 	s8 priority;
108bb451fdfSGreg Thelen 
109bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
110bb451fdfSGreg Thelen 	s8 reclaim_idx;
111bb451fdfSGreg Thelen 
112bb451fdfSGreg Thelen 	/* This context's GFP mask */
113bb451fdfSGreg Thelen 	gfp_t gfp_mask;
114bb451fdfSGreg Thelen 
115ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
116ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
117ee814fe2SJohannes Weiner 
118ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
119ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
120d108c772SAndrey Ryabinin 
121d108c772SAndrey Ryabinin 	struct {
122d108c772SAndrey Ryabinin 		unsigned int dirty;
123d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
124d108c772SAndrey Ryabinin 		unsigned int congested;
125d108c772SAndrey Ryabinin 		unsigned int writeback;
126d108c772SAndrey Ryabinin 		unsigned int immediate;
127d108c772SAndrey Ryabinin 		unsigned int file_taken;
128d108c772SAndrey Ryabinin 		unsigned int taken;
129d108c772SAndrey Ryabinin 	} nr;
1301da177e4SLinus Torvalds };
1311da177e4SLinus Torvalds 
1321da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1331da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1341da177e4SLinus Torvalds 	do {								\
1351da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1361da177e4SLinus Torvalds 			struct page *prev;				\
1371da177e4SLinus Torvalds 									\
1381da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1391da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1401da177e4SLinus Torvalds 		}							\
1411da177e4SLinus Torvalds 	} while (0)
1421da177e4SLinus Torvalds #else
1431da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1441da177e4SLinus Torvalds #endif
1451da177e4SLinus Torvalds 
1461da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1471da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1481da177e4SLinus Torvalds 	do {								\
1491da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1501da177e4SLinus Torvalds 			struct page *prev;				\
1511da177e4SLinus Torvalds 									\
1521da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1531da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1541da177e4SLinus Torvalds 		}							\
1551da177e4SLinus Torvalds 	} while (0)
1561da177e4SLinus Torvalds #else
1571da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1581da177e4SLinus Torvalds #endif
1591da177e4SLinus Torvalds 
1601da177e4SLinus Torvalds /*
1611da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1621da177e4SLinus Torvalds  */
1631da177e4SLinus Torvalds int vm_swappiness = 60;
164d0480be4SWang Sheng-Hui /*
165d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
166d0480be4SWang Sheng-Hui  * zones.
167d0480be4SWang Sheng-Hui  */
168d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1691da177e4SLinus Torvalds 
1701da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
1711da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
1721da177e4SLinus Torvalds 
173b4c2b231SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
1747e010df5SKirill Tkhai 
1757e010df5SKirill Tkhai /*
1767e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
1777e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
1787e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
1797e010df5SKirill Tkhai  * restrictions on their internal registration order.
1807e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
1817e010df5SKirill Tkhai  * bit is set in the shrinkers map.
1827e010df5SKirill Tkhai  *
1837e010df5SKirill Tkhai  * This value is used by the function to detect registering
1847e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
1857e010df5SKirill Tkhai  */
1867e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
1877e010df5SKirill Tkhai 
188b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
189b4c2b231SKirill Tkhai static int shrinker_nr_max;
190b4c2b231SKirill Tkhai 
191b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
192b4c2b231SKirill Tkhai {
193b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
194b4c2b231SKirill Tkhai 
195b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
196b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
1977e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
198b4c2b231SKirill Tkhai 	if (id < 0)
199b4c2b231SKirill Tkhai 		goto unlock;
200b4c2b231SKirill Tkhai 
2010a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2020a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2030a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2040a4465d3SKirill Tkhai 			goto unlock;
2050a4465d3SKirill Tkhai 		}
2060a4465d3SKirill Tkhai 
207b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2080a4465d3SKirill Tkhai 	}
209b4c2b231SKirill Tkhai 	shrinker->id = id;
210b4c2b231SKirill Tkhai 	ret = 0;
211b4c2b231SKirill Tkhai unlock:
212b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
213b4c2b231SKirill Tkhai 	return ret;
214b4c2b231SKirill Tkhai }
215b4c2b231SKirill Tkhai 
216b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
217b4c2b231SKirill Tkhai {
218b4c2b231SKirill Tkhai 	int id = shrinker->id;
219b4c2b231SKirill Tkhai 
220b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
221b4c2b231SKirill Tkhai 
222b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
223b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
224b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
225b4c2b231SKirill Tkhai }
226b4c2b231SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
227b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
228b4c2b231SKirill Tkhai {
229b4c2b231SKirill Tkhai 	return 0;
230b4c2b231SKirill Tkhai }
231b4c2b231SKirill Tkhai 
232b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
233b4c2b231SKirill Tkhai {
234b4c2b231SKirill Tkhai }
235b4c2b231SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
236b4c2b231SKirill Tkhai 
237c255a458SAndrew Morton #ifdef CONFIG_MEMCG
23889b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
23989b5fae5SJohannes Weiner {
240f16015fbSJohannes Weiner 	return !sc->target_mem_cgroup;
24189b5fae5SJohannes Weiner }
24297c9341fSTejun Heo 
24397c9341fSTejun Heo /**
24497c9341fSTejun Heo  * sane_reclaim - is the usual dirty throttling mechanism operational?
24597c9341fSTejun Heo  * @sc: scan_control in question
24697c9341fSTejun Heo  *
24797c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
24897c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
24997c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
25097c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
25197c9341fSTejun Heo  * allocation and configurability.
25297c9341fSTejun Heo  *
25397c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
25497c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
25597c9341fSTejun Heo  */
25697c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
25797c9341fSTejun Heo {
25897c9341fSTejun Heo 	struct mem_cgroup *memcg = sc->target_mem_cgroup;
25997c9341fSTejun Heo 
26097c9341fSTejun Heo 	if (!memcg)
26197c9341fSTejun Heo 		return true;
26297c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
26369234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
26497c9341fSTejun Heo 		return true;
26597c9341fSTejun Heo #endif
26697c9341fSTejun Heo 	return false;
26797c9341fSTejun Heo }
268e3c1ac58SAndrey Ryabinin 
269e3c1ac58SAndrey Ryabinin static void set_memcg_congestion(pg_data_t *pgdat,
270e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg,
271e3c1ac58SAndrey Ryabinin 				bool congested)
272e3c1ac58SAndrey Ryabinin {
273e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
274e3c1ac58SAndrey Ryabinin 
275e3c1ac58SAndrey Ryabinin 	if (!memcg)
276e3c1ac58SAndrey Ryabinin 		return;
277e3c1ac58SAndrey Ryabinin 
278e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
279e3c1ac58SAndrey Ryabinin 	WRITE_ONCE(mn->congested, congested);
280e3c1ac58SAndrey Ryabinin }
281e3c1ac58SAndrey Ryabinin 
282e3c1ac58SAndrey Ryabinin static bool memcg_congested(pg_data_t *pgdat,
283e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
284e3c1ac58SAndrey Ryabinin {
285e3c1ac58SAndrey Ryabinin 	struct mem_cgroup_per_node *mn;
286e3c1ac58SAndrey Ryabinin 
287e3c1ac58SAndrey Ryabinin 	mn = mem_cgroup_nodeinfo(memcg, pgdat->node_id);
288e3c1ac58SAndrey Ryabinin 	return READ_ONCE(mn->congested);
289e3c1ac58SAndrey Ryabinin 
290e3c1ac58SAndrey Ryabinin }
29191a45470SKAMEZAWA Hiroyuki #else
29289b5fae5SJohannes Weiner static bool global_reclaim(struct scan_control *sc)
29389b5fae5SJohannes Weiner {
29489b5fae5SJohannes Weiner 	return true;
29589b5fae5SJohannes Weiner }
29697c9341fSTejun Heo 
29797c9341fSTejun Heo static bool sane_reclaim(struct scan_control *sc)
29897c9341fSTejun Heo {
29997c9341fSTejun Heo 	return true;
30097c9341fSTejun Heo }
301e3c1ac58SAndrey Ryabinin 
302e3c1ac58SAndrey Ryabinin static inline void set_memcg_congestion(struct pglist_data *pgdat,
303e3c1ac58SAndrey Ryabinin 				struct mem_cgroup *memcg, bool congested)
304e3c1ac58SAndrey Ryabinin {
305e3c1ac58SAndrey Ryabinin }
306e3c1ac58SAndrey Ryabinin 
307e3c1ac58SAndrey Ryabinin static inline bool memcg_congested(struct pglist_data *pgdat,
308e3c1ac58SAndrey Ryabinin 			struct mem_cgroup *memcg)
309e3c1ac58SAndrey Ryabinin {
310e3c1ac58SAndrey Ryabinin 	return false;
311e3c1ac58SAndrey Ryabinin 
312e3c1ac58SAndrey Ryabinin }
31391a45470SKAMEZAWA Hiroyuki #endif
31491a45470SKAMEZAWA Hiroyuki 
3155a1c84b4SMel Gorman /*
3165a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3175a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3185a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3195a1c84b4SMel Gorman  */
3205a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3215a1c84b4SMel Gorman {
3225a1c84b4SMel Gorman 	unsigned long nr;
3235a1c84b4SMel Gorman 
3245a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3255a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3265a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3275a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3285a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3295a1c84b4SMel Gorman 
3305a1c84b4SMel Gorman 	return nr;
3315a1c84b4SMel Gorman }
3325a1c84b4SMel Gorman 
333fd538803SMichal Hocko /**
334fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
335fd538803SMichal Hocko  * @lruvec: lru vector
336fd538803SMichal Hocko  * @lru: lru to use
337fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
338fd538803SMichal Hocko  */
339fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
340c9f299d9SKOSAKI Motohiro {
341fd538803SMichal Hocko 	unsigned long lru_size;
342fd538803SMichal Hocko 	int zid;
343a3d8e054SKOSAKI Motohiro 
344fd538803SMichal Hocko 	if (!mem_cgroup_disabled())
345fd538803SMichal Hocko 		lru_size = mem_cgroup_get_lru_size(lruvec, lru);
346fd538803SMichal Hocko 	else
347fd538803SMichal Hocko 		lru_size = node_page_state(lruvec_pgdat(lruvec), NR_LRU_BASE + lru);
348fd538803SMichal Hocko 
349fd538803SMichal Hocko 	for (zid = zone_idx + 1; zid < MAX_NR_ZONES; zid++) {
350fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
351fd538803SMichal Hocko 		unsigned long size;
352fd538803SMichal Hocko 
353fd538803SMichal Hocko 		if (!managed_zone(zone))
354fd538803SMichal Hocko 			continue;
355fd538803SMichal Hocko 
356fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
357fd538803SMichal Hocko 			size = mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
358fd538803SMichal Hocko 		else
359fd538803SMichal Hocko 			size = zone_page_state(&lruvec_pgdat(lruvec)->node_zones[zid],
360fd538803SMichal Hocko 				       NR_ZONE_LRU_BASE + lru);
361fd538803SMichal Hocko 		lru_size -= min(size, lru_size);
362c9f299d9SKOSAKI Motohiro 	}
363c9f299d9SKOSAKI Motohiro 
364fd538803SMichal Hocko 	return lru_size;
365b4536f0cSMichal Hocko 
366b4536f0cSMichal Hocko }
367b4536f0cSMichal Hocko 
3681da177e4SLinus Torvalds /*
3691d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3701da177e4SLinus Torvalds  */
3718e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3721da177e4SLinus Torvalds {
3731d3d4437SGlauber Costa 	size_t size = sizeof(*shrinker->nr_deferred);
3741d3d4437SGlauber Costa 
3751d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3761d3d4437SGlauber Costa 		size *= nr_node_ids;
3771d3d4437SGlauber Costa 
3781d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3791d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3801d3d4437SGlauber Costa 		return -ENOMEM;
381b4c2b231SKirill 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);
4117e010df5SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
4128df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
4137e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
4147e010df5SKirill Tkhai #endif
4151da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
4168e04944fSTetsuo Handa }
4178e04944fSTetsuo Handa 
4188e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
4198e04944fSTetsuo Handa {
4208e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4218e04944fSTetsuo Handa 
4228e04944fSTetsuo Handa 	if (err)
4238e04944fSTetsuo Handa 		return err;
4248e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4251d3d4437SGlauber Costa 	return 0;
4261da177e4SLinus Torvalds }
4278e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4281da177e4SLinus Torvalds 
4291da177e4SLinus Torvalds /*
4301da177e4SLinus Torvalds  * Remove one
4311da177e4SLinus Torvalds  */
4328e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4331da177e4SLinus Torvalds {
434bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
435bb422a73STetsuo Handa 		return;
436b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
437b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4381da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4391da177e4SLinus Torvalds 	list_del(&shrinker->list);
4401da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
441ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
442bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4431da177e4SLinus Torvalds }
4448e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4451da177e4SLinus Torvalds 
4461da177e4SLinus Torvalds #define SHRINK_BATCH 128
4471d3d4437SGlauber Costa 
448cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4499092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4501da177e4SLinus Torvalds {
45124f7c6b9SDave Chinner 	unsigned long freed = 0;
4521da177e4SLinus Torvalds 	unsigned long long delta;
453635697c6SKonstantin Khlebnikov 	long total_scan;
454d5bc5fd3SVladimir Davydov 	long freeable;
455acf92b48SDave Chinner 	long nr;
456acf92b48SDave Chinner 	long new_nr;
4571d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
458e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
459e9299f50SDave Chinner 					  : SHRINK_BATCH;
4605f33a080SShaohua Li 	long scanned = 0, next_deferred;
4611da177e4SLinus Torvalds 
462ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
463ac7fb3adSKirill Tkhai 		nid = 0;
464ac7fb3adSKirill Tkhai 
465d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4669b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4679b996468SKirill Tkhai 		return freeable;
468635697c6SKonstantin Khlebnikov 
469acf92b48SDave Chinner 	/*
470acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
471acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
472acf92b48SDave Chinner 	 * don't also do this scanning work.
473acf92b48SDave Chinner 	 */
4741d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
475acf92b48SDave Chinner 
476acf92b48SDave Chinner 	total_scan = nr;
477*4b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4789092c71bSJosef Bacik 		delta = freeable >> priority;
4799092c71bSJosef Bacik 		delta *= 4;
4809092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
481*4b85afbdSJohannes Weiner 	} else {
482*4b85afbdSJohannes Weiner 		/*
483*4b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
484*4b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
485*4b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
486*4b85afbdSJohannes Weiner 		 */
487*4b85afbdSJohannes Weiner 		delta = freeable / 2;
488*4b85afbdSJohannes Weiner 	}
489172b06c3SRoman Gushchin 
490172b06c3SRoman Gushchin 	/*
491172b06c3SRoman Gushchin 	 * Make sure we apply some minimal pressure on default priority
492172b06c3SRoman Gushchin 	 * even on small cgroups. Stale objects are not only consuming memory
493172b06c3SRoman Gushchin 	 * by themselves, but can also hold a reference to a dying cgroup,
494172b06c3SRoman Gushchin 	 * preventing it from being reclaimed. A dying cgroup with all
495172b06c3SRoman Gushchin 	 * corresponding structures like per-cpu stats and kmem caches
496172b06c3SRoman Gushchin 	 * can be really big, so it may lead to a significant waste of memory.
497172b06c3SRoman Gushchin 	 */
498172b06c3SRoman Gushchin 	delta = max_t(unsigned long long, delta, min(freeable, batch_size));
499172b06c3SRoman Gushchin 
500acf92b48SDave Chinner 	total_scan += delta;
501acf92b48SDave Chinner 	if (total_scan < 0) {
5028612c663SPintu Kumar 		pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
503a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
504d5bc5fd3SVladimir Davydov 		total_scan = freeable;
5055f33a080SShaohua Li 		next_deferred = nr;
5065f33a080SShaohua Li 	} else
5075f33a080SShaohua Li 		next_deferred = total_scan;
508ea164d73SAndrea Arcangeli 
509ea164d73SAndrea Arcangeli 	/*
5103567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
5113567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
5123567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
5133567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
5143567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
515d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
5163567b59aSDave Chinner 	 * memory.
5173567b59aSDave Chinner 	 *
5183567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
5193567b59aSDave Chinner 	 * a large delta change is calculated directly.
5203567b59aSDave Chinner 	 */
521d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
522d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
5233567b59aSDave Chinner 
5243567b59aSDave Chinner 	/*
525ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
526ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
527ea164d73SAndrea Arcangeli 	 * freeable entries.
528ea164d73SAndrea Arcangeli 	 */
529d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
530d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5311da177e4SLinus Torvalds 
53224f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5339092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
53409576073SDave Chinner 
5350b1fb40aSVladimir Davydov 	/*
5360b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5370b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5380b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5390b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5400b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5410b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5420b1fb40aSVladimir Davydov 	 * batch_size.
5430b1fb40aSVladimir Davydov 	 *
5440b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5450b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
546d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5470b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5480b1fb40aSVladimir Davydov 	 * possible.
5490b1fb40aSVladimir Davydov 	 */
5500b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
551d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
55224f7c6b9SDave Chinner 		unsigned long ret;
5530b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5541da177e4SLinus Torvalds 
5550b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
556d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
55724f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
55824f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5591da177e4SLinus Torvalds 			break;
56024f7c6b9SDave Chinner 		freed += ret;
56124f7c6b9SDave Chinner 
562d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
563d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
564d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5651da177e4SLinus Torvalds 
5661da177e4SLinus Torvalds 		cond_resched();
5671da177e4SLinus Torvalds 	}
5681da177e4SLinus Torvalds 
5695f33a080SShaohua Li 	if (next_deferred >= scanned)
5705f33a080SShaohua Li 		next_deferred -= scanned;
5715f33a080SShaohua Li 	else
5725f33a080SShaohua Li 		next_deferred = 0;
573acf92b48SDave Chinner 	/*
574acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
575acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
576acf92b48SDave Chinner 	 * scan, there is no need to do an update.
577acf92b48SDave Chinner 	 */
5785f33a080SShaohua Li 	if (next_deferred > 0)
5795f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5801d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
58183aeeadaSKonstantin Khlebnikov 	else
5821d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
583acf92b48SDave Chinner 
584df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5851d3d4437SGlauber Costa 	return freed;
5861d3d4437SGlauber Costa }
5871d3d4437SGlauber Costa 
588b0dedc49SKirill Tkhai #ifdef CONFIG_MEMCG_KMEM
589b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
590b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
591b0dedc49SKirill Tkhai {
592b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
593b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
594b8e57efaSKirill Tkhai 	int i;
595b0dedc49SKirill Tkhai 
596b0dedc49SKirill Tkhai 	if (!memcg_kmem_enabled() || !mem_cgroup_online(memcg))
597b0dedc49SKirill Tkhai 		return 0;
598b0dedc49SKirill Tkhai 
599b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
600b0dedc49SKirill Tkhai 		return 0;
601b0dedc49SKirill Tkhai 
602b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
603b0dedc49SKirill Tkhai 					true);
604b0dedc49SKirill Tkhai 	if (unlikely(!map))
605b0dedc49SKirill Tkhai 		goto unlock;
606b0dedc49SKirill Tkhai 
607b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
608b0dedc49SKirill Tkhai 		struct shrink_control sc = {
609b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
610b0dedc49SKirill Tkhai 			.nid = nid,
611b0dedc49SKirill Tkhai 			.memcg = memcg,
612b0dedc49SKirill Tkhai 		};
613b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
614b0dedc49SKirill Tkhai 
615b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
6167e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
6177e010df5SKirill Tkhai 			if (!shrinker)
618b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
619b0dedc49SKirill Tkhai 			continue;
620b0dedc49SKirill Tkhai 		}
621b0dedc49SKirill Tkhai 
622b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
623f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
624f90280d6SKirill Tkhai 			clear_bit(i, map->map);
625f90280d6SKirill Tkhai 			/*
626f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
627f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
628f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
629f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
630f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
631f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
632f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
633f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
634f90280d6SKirill Tkhai 			 *
635f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
636f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
637f90280d6SKirill Tkhai 			 *   <MB>               <MB>
638f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
639f90280d6SKirill Tkhai 			 */
640f90280d6SKirill Tkhai 			smp_mb__after_atomic();
641f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6429b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6439b996468SKirill Tkhai 				ret = 0;
644f90280d6SKirill Tkhai 			else
645f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
646f90280d6SKirill Tkhai 		}
647b0dedc49SKirill Tkhai 		freed += ret;
648b0dedc49SKirill Tkhai 
649b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
650b0dedc49SKirill Tkhai 			freed = freed ? : 1;
651b0dedc49SKirill Tkhai 			break;
652b0dedc49SKirill Tkhai 		}
653b0dedc49SKirill Tkhai 	}
654b0dedc49SKirill Tkhai unlock:
655b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
656b0dedc49SKirill Tkhai 	return freed;
657b0dedc49SKirill Tkhai }
658b0dedc49SKirill Tkhai #else /* CONFIG_MEMCG_KMEM */
659b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
660b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
661b0dedc49SKirill Tkhai {
662b0dedc49SKirill Tkhai 	return 0;
663b0dedc49SKirill Tkhai }
664b0dedc49SKirill Tkhai #endif /* CONFIG_MEMCG_KMEM */
665b0dedc49SKirill Tkhai 
6666b4f7799SJohannes Weiner /**
667cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6686b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6696b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
670cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6719092c71bSJosef Bacik  * @priority: the reclaim priority
6721d3d4437SGlauber Costa  *
6736b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6741d3d4437SGlauber Costa  *
6756b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6766b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6771d3d4437SGlauber Costa  *
678aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
679aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
680cb731d6cSVladimir Davydov  *
6819092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6829092c71bSJosef Bacik  * in order to get the scan target.
6831d3d4437SGlauber Costa  *
6846b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6851d3d4437SGlauber Costa  */
686cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
687cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6889092c71bSJosef Bacik 				 int priority)
6891d3d4437SGlauber Costa {
690b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6911d3d4437SGlauber Costa 	struct shrinker *shrinker;
6921d3d4437SGlauber Costa 
693aeed1d32SVladimir Davydov 	if (!mem_cgroup_is_root(memcg))
694b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
695cb731d6cSVladimir Davydov 
696e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6971d3d4437SGlauber Costa 		goto out;
6981d3d4437SGlauber Costa 
6991d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
7006b4f7799SJohannes Weiner 		struct shrink_control sc = {
7016b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
7026b4f7799SJohannes Weiner 			.nid = nid,
703cb731d6cSVladimir Davydov 			.memcg = memcg,
7046b4f7799SJohannes Weiner 		};
7056b4f7799SJohannes Weiner 
7069b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
7079b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
7089b996468SKirill Tkhai 			ret = 0;
7099b996468SKirill Tkhai 		freed += ret;
710e496612cSMinchan Kim 		/*
711e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
712e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
713e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
714e496612cSMinchan Kim 		 */
715e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
716e496612cSMinchan Kim 			freed = freed ? : 1;
717e496612cSMinchan Kim 			break;
718e496612cSMinchan Kim 		}
719ec97097bSVladimir Davydov 	}
7201d3d4437SGlauber Costa 
7211da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
722f06590bdSMinchan Kim out:
723f06590bdSMinchan Kim 	cond_resched();
72424f7c6b9SDave Chinner 	return freed;
7251da177e4SLinus Torvalds }
7261da177e4SLinus Torvalds 
727cb731d6cSVladimir Davydov void drop_slab_node(int nid)
728cb731d6cSVladimir Davydov {
729cb731d6cSVladimir Davydov 	unsigned long freed;
730cb731d6cSVladimir Davydov 
731cb731d6cSVladimir Davydov 	do {
732cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
733cb731d6cSVladimir Davydov 
734cb731d6cSVladimir Davydov 		freed = 0;
735aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
736cb731d6cSVladimir Davydov 		do {
7379092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
738cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
739cb731d6cSVladimir Davydov 	} while (freed > 10);
740cb731d6cSVladimir Davydov }
741cb731d6cSVladimir Davydov 
742cb731d6cSVladimir Davydov void drop_slab(void)
743cb731d6cSVladimir Davydov {
744cb731d6cSVladimir Davydov 	int nid;
745cb731d6cSVladimir Davydov 
746cb731d6cSVladimir Davydov 	for_each_online_node(nid)
747cb731d6cSVladimir Davydov 		drop_slab_node(nid);
748cb731d6cSVladimir Davydov }
749cb731d6cSVladimir Davydov 
7501da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7511da177e4SLinus Torvalds {
752ceddc3a5SJohannes Weiner 	/*
753ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
754ceddc3a5SJohannes Weiner 	 * that isolated the page, the page cache radix tree and
755ceddc3a5SJohannes Weiner 	 * optional buffer heads at page->private.
756ceddc3a5SJohannes Weiner 	 */
757bd4c82c2SHuang Ying 	int radix_pins = PageTransHuge(page) && PageSwapCache(page) ?
758bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
759bd4c82c2SHuang Ying 	return page_count(page) - page_has_private(page) == 1 + radix_pins;
7601da177e4SLinus Torvalds }
7611da177e4SLinus Torvalds 
762703c2708STejun Heo static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
7631da177e4SLinus Torvalds {
764930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7651da177e4SLinus Torvalds 		return 1;
766703c2708STejun Heo 	if (!inode_write_congested(inode))
7671da177e4SLinus Torvalds 		return 1;
768703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7691da177e4SLinus Torvalds 		return 1;
7701da177e4SLinus Torvalds 	return 0;
7711da177e4SLinus Torvalds }
7721da177e4SLinus Torvalds 
7731da177e4SLinus Torvalds /*
7741da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7751da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7761da177e4SLinus Torvalds  * fsync(), msync() or close().
7771da177e4SLinus Torvalds  *
7781da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7791da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7801da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7811da177e4SLinus Torvalds  *
7821da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7831da177e4SLinus Torvalds  * __GFP_FS.
7841da177e4SLinus Torvalds  */
7851da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7861da177e4SLinus Torvalds 				struct page *page, int error)
7871da177e4SLinus Torvalds {
7887eaceaccSJens Axboe 	lock_page(page);
7893e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7903e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7911da177e4SLinus Torvalds 	unlock_page(page);
7921da177e4SLinus Torvalds }
7931da177e4SLinus Torvalds 
79404e62a29SChristoph Lameter /* possible outcome of pageout() */
79504e62a29SChristoph Lameter typedef enum {
79604e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
79704e62a29SChristoph Lameter 	PAGE_KEEP,
79804e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
79904e62a29SChristoph Lameter 	PAGE_ACTIVATE,
80004e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
80104e62a29SChristoph Lameter 	PAGE_SUCCESS,
80204e62a29SChristoph Lameter 	/* page is clean and locked */
80304e62a29SChristoph Lameter 	PAGE_CLEAN,
80404e62a29SChristoph Lameter } pageout_t;
80504e62a29SChristoph Lameter 
8061da177e4SLinus Torvalds /*
8071742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
8081742f19fSAndrew Morton  * Calls ->writepage().
8091da177e4SLinus Torvalds  */
810c661b078SAndy Whitcroft static pageout_t pageout(struct page *page, struct address_space *mapping,
8117d3579e8SKOSAKI Motohiro 			 struct scan_control *sc)
8121da177e4SLinus Torvalds {
8131da177e4SLinus Torvalds 	/*
8141da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
8151da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
8161da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
8171da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
8181da177e4SLinus Torvalds 	 * PagePrivate for that.
8191da177e4SLinus Torvalds 	 *
8208174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
8211da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
8221da177e4SLinus Torvalds 	 * will block.
8231da177e4SLinus Torvalds 	 *
8241da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
8251da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
8261da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
8271da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
8281da177e4SLinus Torvalds 	 */
8291da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
8301da177e4SLinus Torvalds 		return PAGE_KEEP;
8311da177e4SLinus Torvalds 	if (!mapping) {
8321da177e4SLinus Torvalds 		/*
8331da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8341da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8351da177e4SLinus Torvalds 		 */
836266cf658SDavid Howells 		if (page_has_private(page)) {
8371da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8381da177e4SLinus Torvalds 				ClearPageDirty(page);
839b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8401da177e4SLinus Torvalds 				return PAGE_CLEAN;
8411da177e4SLinus Torvalds 			}
8421da177e4SLinus Torvalds 		}
8431da177e4SLinus Torvalds 		return PAGE_KEEP;
8441da177e4SLinus Torvalds 	}
8451da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8461da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
847703c2708STejun Heo 	if (!may_write_to_inode(mapping->host, sc))
8481da177e4SLinus Torvalds 		return PAGE_KEEP;
8491da177e4SLinus Torvalds 
8501da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8511da177e4SLinus Torvalds 		int res;
8521da177e4SLinus Torvalds 		struct writeback_control wbc = {
8531da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8541da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
855111ebb6eSOGAWA Hirofumi 			.range_start = 0,
856111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8571da177e4SLinus Torvalds 			.for_reclaim = 1,
8581da177e4SLinus Torvalds 		};
8591da177e4SLinus Torvalds 
8601da177e4SLinus Torvalds 		SetPageReclaim(page);
8611da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8621da177e4SLinus Torvalds 		if (res < 0)
8631da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
864994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8651da177e4SLinus Torvalds 			ClearPageReclaim(page);
8661da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8671da177e4SLinus Torvalds 		}
868c661b078SAndy Whitcroft 
8691da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8701da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8711da177e4SLinus Torvalds 			ClearPageReclaim(page);
8721da177e4SLinus Torvalds 		}
8733aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
874c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8751da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8761da177e4SLinus Torvalds 	}
8771da177e4SLinus Torvalds 
8781da177e4SLinus Torvalds 	return PAGE_CLEAN;
8791da177e4SLinus Torvalds }
8801da177e4SLinus Torvalds 
881a649fd92SAndrew Morton /*
882e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
883e286781dSNick Piggin  * gets returned with a refcount of 0.
884a649fd92SAndrew Morton  */
885a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
886a528910eSJohannes Weiner 			    bool reclaimed)
88749d2e9ccSChristoph Lameter {
888c4843a75SGreg Thelen 	unsigned long flags;
889bd4c82c2SHuang Ying 	int refcount;
890c4843a75SGreg Thelen 
89128e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
89228e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
89349d2e9ccSChristoph Lameter 
894b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
89549d2e9ccSChristoph Lameter 	/*
8960fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8970fd0e6b0SNick Piggin 	 *
8980fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8990fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
9000fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
9010fd0e6b0SNick Piggin 	 * here, then the following race may occur:
9020fd0e6b0SNick Piggin 	 *
9030fd0e6b0SNick Piggin 	 * get_user_pages(&page);
9040fd0e6b0SNick Piggin 	 * [user mapping goes away]
9050fd0e6b0SNick Piggin 	 * write_to(page);
9060fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
9070fd0e6b0SNick Piggin 	 * SetPageDirty(page);
9080fd0e6b0SNick Piggin 	 * put_page(page);
9090fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
9100fd0e6b0SNick Piggin 	 *
9110fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
9120fd0e6b0SNick Piggin 	 *
9130fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
9140fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
9150139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
9160fd0e6b0SNick Piggin 	 *
9170fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
918b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
91949d2e9ccSChristoph Lameter 	 */
920bd4c82c2SHuang Ying 	if (unlikely(PageTransHuge(page)) && PageSwapCache(page))
921bd4c82c2SHuang Ying 		refcount = 1 + HPAGE_PMD_NR;
922bd4c82c2SHuang Ying 	else
923bd4c82c2SHuang Ying 		refcount = 2;
924bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
92549d2e9ccSChristoph Lameter 		goto cannot_free;
9261c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
927e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
928bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
92949d2e9ccSChristoph Lameter 		goto cannot_free;
930e286781dSNick Piggin 	}
93149d2e9ccSChristoph Lameter 
93249d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
93349d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
9340a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
93549d2e9ccSChristoph Lameter 		__delete_from_swap_cache(page);
936b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
93775f6d6d2SMinchan Kim 		put_swap_page(page, swap);
938e286781dSNick Piggin 	} else {
9396072d13cSLinus Torvalds 		void (*freepage)(struct page *);
940a528910eSJohannes Weiner 		void *shadow = NULL;
9416072d13cSLinus Torvalds 
9426072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
943a528910eSJohannes Weiner 		/*
944a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
945a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
946a528910eSJohannes Weiner 		 *
947a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
948a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
949a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
950a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
951a528910eSJohannes Weiner 		 * back.
952f9fe48beSRoss Zwisler 		 *
953f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
954f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
955f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
956f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
957b93b0163SMatthew Wilcox 		 * same address_space.
958a528910eSJohannes Weiner 		 */
959a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
960f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
961a528910eSJohannes Weiner 			shadow = workingset_eviction(mapping, page);
96262cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
963b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9646072d13cSLinus Torvalds 
9656072d13cSLinus Torvalds 		if (freepage != NULL)
9666072d13cSLinus Torvalds 			freepage(page);
967e286781dSNick Piggin 	}
968e286781dSNick Piggin 
96949d2e9ccSChristoph Lameter 	return 1;
97049d2e9ccSChristoph Lameter 
97149d2e9ccSChristoph Lameter cannot_free:
972b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
97349d2e9ccSChristoph Lameter 	return 0;
97449d2e9ccSChristoph Lameter }
97549d2e9ccSChristoph Lameter 
9761da177e4SLinus Torvalds /*
977e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
978e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
979e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
980e286781dSNick Piggin  * this page.
981e286781dSNick Piggin  */
982e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
983e286781dSNick Piggin {
984a528910eSJohannes Weiner 	if (__remove_mapping(mapping, page, false)) {
985e286781dSNick Piggin 		/*
986e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
987e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
988e286781dSNick Piggin 		 * atomic operation.
989e286781dSNick Piggin 		 */
990fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
991e286781dSNick Piggin 		return 1;
992e286781dSNick Piggin 	}
993e286781dSNick Piggin 	return 0;
994e286781dSNick Piggin }
995e286781dSNick Piggin 
996894bc310SLee Schermerhorn /**
997894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
998894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
999894bc310SLee Schermerhorn  *
1000894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
1001894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
1002894bc310SLee Schermerhorn  *
1003894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
1004894bc310SLee Schermerhorn  */
1005894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
1006894bc310SLee Schermerhorn {
1007c53954a0SMel Gorman 	lru_cache_add(page);
1008894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
1009894bc310SLee Schermerhorn }
1010894bc310SLee Schermerhorn 
1011dfc8d636SJohannes Weiner enum page_references {
1012dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
1013dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
101464574746SJohannes Weiner 	PAGEREF_KEEP,
1015dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
1016dfc8d636SJohannes Weiner };
1017dfc8d636SJohannes Weiner 
1018dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
1019dfc8d636SJohannes Weiner 						  struct scan_control *sc)
1020dfc8d636SJohannes Weiner {
102164574746SJohannes Weiner 	int referenced_ptes, referenced_page;
1022dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1023dfc8d636SJohannes Weiner 
1024c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1025c3ac9a8aSJohannes Weiner 					  &vm_flags);
102664574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1027dfc8d636SJohannes Weiner 
1028dfc8d636SJohannes Weiner 	/*
1029dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1030dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1031dfc8d636SJohannes Weiner 	 */
1032dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1033dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1034dfc8d636SJohannes Weiner 
103564574746SJohannes Weiner 	if (referenced_ptes) {
1036e4898273SMichal Hocko 		if (PageSwapBacked(page))
103764574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
103864574746SJohannes Weiner 		/*
103964574746SJohannes Weiner 		 * All mapped pages start out with page table
104064574746SJohannes Weiner 		 * references from the instantiating fault, so we need
104164574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
104264574746SJohannes Weiner 		 * than once.
104364574746SJohannes Weiner 		 *
104464574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
104564574746SJohannes Weiner 		 * inactive list.  Another page table reference will
104664574746SJohannes Weiner 		 * lead to its activation.
104764574746SJohannes Weiner 		 *
104864574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
104964574746SJohannes Weiner 		 * so that recently deactivated but used pages are
105064574746SJohannes Weiner 		 * quickly recovered.
105164574746SJohannes Weiner 		 */
105264574746SJohannes Weiner 		SetPageReferenced(page);
105364574746SJohannes Weiner 
105434dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1055dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1056dfc8d636SJohannes Weiner 
1057c909e993SKonstantin Khlebnikov 		/*
1058c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1059c909e993SKonstantin Khlebnikov 		 */
1060c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1061c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1062c909e993SKonstantin Khlebnikov 
106364574746SJohannes Weiner 		return PAGEREF_KEEP;
106464574746SJohannes Weiner 	}
106564574746SJohannes Weiner 
1066dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10672e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1068dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
106964574746SJohannes Weiner 
107064574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1071dfc8d636SJohannes Weiner }
1072dfc8d636SJohannes Weiner 
1073e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1074e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1075e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1076e2be15f6SMel Gorman {
1077b4597226SMel Gorman 	struct address_space *mapping;
1078b4597226SMel Gorman 
1079e2be15f6SMel Gorman 	/*
1080e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1081e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1082e2be15f6SMel Gorman 	 */
1083802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1084802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1085e2be15f6SMel Gorman 		*dirty = false;
1086e2be15f6SMel Gorman 		*writeback = false;
1087e2be15f6SMel Gorman 		return;
1088e2be15f6SMel Gorman 	}
1089e2be15f6SMel Gorman 
1090e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1091e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1092e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1093b4597226SMel Gorman 
1094b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1095b4597226SMel Gorman 	if (!page_has_private(page))
1096b4597226SMel Gorman 		return;
1097b4597226SMel Gorman 
1098b4597226SMel Gorman 	mapping = page_mapping(page);
1099b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1100b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1101e2be15f6SMel Gorman }
1102e2be15f6SMel Gorman 
1103e286781dSNick Piggin /*
11041742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
11051da177e4SLinus Torvalds  */
11061742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1107599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1108f84f6e2bSMel Gorman 				      struct scan_control *sc,
110902c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
11103c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
111102c6de8dSMinchan Kim 				      bool force_reclaim)
11121da177e4SLinus Torvalds {
11131da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1114abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
11151da177e4SLinus Torvalds 	int pgactivate = 0;
11163c710c1aSMichal Hocko 	unsigned nr_unqueued_dirty = 0;
11173c710c1aSMichal Hocko 	unsigned nr_dirty = 0;
11183c710c1aSMichal Hocko 	unsigned nr_congested = 0;
11193c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
11203c710c1aSMichal Hocko 	unsigned nr_writeback = 0;
11213c710c1aSMichal Hocko 	unsigned nr_immediate = 0;
11225bccd166SMichal Hocko 	unsigned nr_ref_keep = 0;
11235bccd166SMichal Hocko 	unsigned nr_unmap_fail = 0;
11241da177e4SLinus Torvalds 
11251da177e4SLinus Torvalds 	cond_resched();
11261da177e4SLinus Torvalds 
11271da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
11281da177e4SLinus Torvalds 		struct address_space *mapping;
11291da177e4SLinus Torvalds 		struct page *page;
11301da177e4SLinus Torvalds 		int may_enter_fs;
113102c6de8dSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM_CLEAN;
1132e2be15f6SMel Gorman 		bool dirty, writeback;
11331da177e4SLinus Torvalds 
11341da177e4SLinus Torvalds 		cond_resched();
11351da177e4SLinus Torvalds 
11361da177e4SLinus Torvalds 		page = lru_to_page(page_list);
11371da177e4SLinus Torvalds 		list_del(&page->lru);
11381da177e4SLinus Torvalds 
1139529ae9aaSNick Piggin 		if (!trylock_page(page))
11401da177e4SLinus Torvalds 			goto keep;
11411da177e4SLinus Torvalds 
1142309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11431da177e4SLinus Torvalds 
11441da177e4SLinus Torvalds 		sc->nr_scanned++;
114580e43426SChristoph Lameter 
114639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1147ad6b6704SMinchan Kim 			goto activate_locked;
1148894bc310SLee Schermerhorn 
1149a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
115080e43426SChristoph Lameter 			goto keep_locked;
115180e43426SChristoph Lameter 
11521da177e4SLinus Torvalds 		/* Double the slab pressure for mapped and swapcache pages */
1153802a3a92SShaohua Li 		if ((page_mapped(page) || PageSwapCache(page)) &&
1154802a3a92SShaohua Li 		    !(PageAnon(page) && !PageSwapBacked(page)))
11551da177e4SLinus Torvalds 			sc->nr_scanned++;
11561da177e4SLinus Torvalds 
1157c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1158c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1159c661b078SAndy Whitcroft 
1160e62e384eSMichal Hocko 		/*
1161894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1162e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1163e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1164e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1165e2be15f6SMel Gorman 		 */
1166e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1167e2be15f6SMel Gorman 		if (dirty || writeback)
1168e2be15f6SMel Gorman 			nr_dirty++;
1169e2be15f6SMel Gorman 
1170e2be15f6SMel Gorman 		if (dirty && !writeback)
1171e2be15f6SMel Gorman 			nr_unqueued_dirty++;
1172e2be15f6SMel Gorman 
1173d04e8acdSMel Gorman 		/*
1174d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1175d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1176d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1177d04e8acdSMel Gorman 		 * end of the LRU a second time.
1178d04e8acdSMel Gorman 		 */
1179e2be15f6SMel Gorman 		mapping = page_mapping(page);
11801da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1181703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1182d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1183e2be15f6SMel Gorman 			nr_congested++;
1184e2be15f6SMel Gorman 
1185e2be15f6SMel Gorman 		/*
1186283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1187283aba9fSMel Gorman 		 * are three cases to consider.
1188e62e384eSMichal Hocko 		 *
1189283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1190283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1191283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1192283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1193283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1194283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1195283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1196b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1197b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1198c3b94f44SHugh Dickins 		 *
119997c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1200ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1201ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1202ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
120397c9341fSTejun Heo 		 *    reclaim and continue scanning.
1204283aba9fSMel Gorman 		 *
1205ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1206ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1207283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1208283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1209283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1210283aba9fSMel Gorman 		 *    would probably show more reasons.
1211283aba9fSMel Gorman 		 *
12127fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1213283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1214283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1215283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1216283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1217c55e8d03SJohannes Weiner 		 *
1218c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1219c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1220c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1221c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1222c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1223c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1224c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1225c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1226e62e384eSMichal Hocko 		 */
1227283aba9fSMel Gorman 		if (PageWriteback(page)) {
1228283aba9fSMel Gorman 			/* Case 1 above */
1229283aba9fSMel Gorman 			if (current_is_kswapd() &&
1230283aba9fSMel Gorman 			    PageReclaim(page) &&
1231599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1232b1a6f21eSMel Gorman 				nr_immediate++;
1233c55e8d03SJohannes Weiner 				goto activate_locked;
1234283aba9fSMel Gorman 
1235283aba9fSMel Gorman 			/* Case 2 above */
123697c9341fSTejun Heo 			} else if (sane_reclaim(sc) ||
1237ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1238c3b94f44SHugh Dickins 				/*
1239c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1240c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1241c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1242c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1243c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1244c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1245c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1246c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1247c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1248c3b94f44SHugh Dickins 				 */
1249c3b94f44SHugh Dickins 				SetPageReclaim(page);
125092df3a72SMel Gorman 				nr_writeback++;
1251c55e8d03SJohannes Weiner 				goto activate_locked;
1252283aba9fSMel Gorman 
1253283aba9fSMel Gorman 			/* Case 3 above */
1254283aba9fSMel Gorman 			} else {
12557fadc820SHugh Dickins 				unlock_page(page);
1256c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12577fadc820SHugh Dickins 				/* then go back and try same page again */
12587fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12597fadc820SHugh Dickins 				continue;
1260e62e384eSMichal Hocko 			}
1261283aba9fSMel Gorman 		}
12621da177e4SLinus Torvalds 
126302c6de8dSMinchan Kim 		if (!force_reclaim)
12646a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
126502c6de8dSMinchan Kim 
1266dfc8d636SJohannes Weiner 		switch (references) {
1267dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12681da177e4SLinus Torvalds 			goto activate_locked;
126964574746SJohannes Weiner 		case PAGEREF_KEEP:
12705bccd166SMichal Hocko 			nr_ref_keep++;
127164574746SJohannes Weiner 			goto keep_locked;
1272dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1273dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1274dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1275dfc8d636SJohannes Weiner 		}
12761da177e4SLinus Torvalds 
12771da177e4SLinus Torvalds 		/*
12781da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12791da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1280802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12811da177e4SLinus Torvalds 		 */
1282bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1283bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
128463eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
128563eb6b93SHugh Dickins 					goto keep_locked;
1286747552b1SHuang Ying 				if (PageTransHuge(page)) {
1287b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1288747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1289b8f593cdSHuang Ying 						goto activate_locked;
1290747552b1SHuang Ying 					/*
1291747552b1SHuang Ying 					 * Split pages without a PMD map right
1292747552b1SHuang Ying 					 * away. Chances are some or all of the
1293747552b1SHuang Ying 					 * tail pages can be freed without IO.
1294747552b1SHuang Ying 					 */
1295747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1296bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1297bd4c82c2SHuang Ying 								    page_list))
1298747552b1SHuang Ying 						goto activate_locked;
1299747552b1SHuang Ying 				}
13000f074658SMinchan Kim 				if (!add_to_swap(page)) {
13010f074658SMinchan Kim 					if (!PageTransHuge(page))
13021da177e4SLinus Torvalds 						goto activate_locked;
1303bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1304bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1305bd4c82c2SHuang Ying 								    page_list))
13060f074658SMinchan Kim 						goto activate_locked;
1307fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1308fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1309fe490cc0SHuang Ying #endif
13100f074658SMinchan Kim 					if (!add_to_swap(page))
13110f074658SMinchan Kim 						goto activate_locked;
13120f074658SMinchan Kim 				}
13130f074658SMinchan Kim 
131463eb6b93SHugh Dickins 				may_enter_fs = 1;
13151da177e4SLinus Torvalds 
1316e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
13171da177e4SLinus Torvalds 				mapping = page_mapping(page);
1318bd4c82c2SHuang Ying 			}
13197751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
13207751b2daSKirill A. Shutemov 			/* Split file THP */
13217751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
13227751b2daSKirill A. Shutemov 				goto keep_locked;
1323e2be15f6SMel Gorman 		}
13241da177e4SLinus Torvalds 
13251da177e4SLinus Torvalds 		/*
13261da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
13271da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
13281da177e4SLinus Torvalds 		 */
1329802a3a92SShaohua Li 		if (page_mapped(page)) {
1330bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1331bd4c82c2SHuang Ying 
1332bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1333bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1334bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
13355bccd166SMichal Hocko 				nr_unmap_fail++;
13361da177e4SLinus Torvalds 				goto activate_locked;
13371da177e4SLinus Torvalds 			}
13381da177e4SLinus Torvalds 		}
13391da177e4SLinus Torvalds 
13401da177e4SLinus Torvalds 		if (PageDirty(page)) {
1341ee72886dSMel Gorman 			/*
13424eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13434eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13444eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13454eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13464eda4823SJohannes Weiner 			 * write pages when we've encountered many
13474eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13484eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13494eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1350ee72886dSMel Gorman 			 */
1351f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13524eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1353599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
135449ea7eb6SMel Gorman 				/*
135549ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
135649ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
135749ea7eb6SMel Gorman 				 * except we already have the page isolated
135849ea7eb6SMel Gorman 				 * and know it's dirty
135949ea7eb6SMel Gorman 				 */
1360c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
136149ea7eb6SMel Gorman 				SetPageReclaim(page);
136249ea7eb6SMel Gorman 
1363c55e8d03SJohannes Weiner 				goto activate_locked;
1364ee72886dSMel Gorman 			}
1365ee72886dSMel Gorman 
1366dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13671da177e4SLinus Torvalds 				goto keep_locked;
13684dd4b920SAndrew Morton 			if (!may_enter_fs)
13691da177e4SLinus Torvalds 				goto keep_locked;
137052a8363eSChristoph Lameter 			if (!sc->may_writepage)
13711da177e4SLinus Torvalds 				goto keep_locked;
13721da177e4SLinus Torvalds 
1373d950c947SMel Gorman 			/*
1374d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1375d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1376d950c947SMel Gorman 			 * starts and then write it out here.
1377d950c947SMel Gorman 			 */
1378d950c947SMel Gorman 			try_to_unmap_flush_dirty();
13797d3579e8SKOSAKI Motohiro 			switch (pageout(page, mapping, sc)) {
13801da177e4SLinus Torvalds 			case PAGE_KEEP:
13811da177e4SLinus Torvalds 				goto keep_locked;
13821da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13831da177e4SLinus Torvalds 				goto activate_locked;
13841da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13857d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
138641ac1999SMel Gorman 					goto keep;
13877d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13881da177e4SLinus Torvalds 					goto keep;
13897d3579e8SKOSAKI Motohiro 
13901da177e4SLinus Torvalds 				/*
13911da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13921da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13931da177e4SLinus Torvalds 				 */
1394529ae9aaSNick Piggin 				if (!trylock_page(page))
13951da177e4SLinus Torvalds 					goto keep;
13961da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13971da177e4SLinus Torvalds 					goto keep_locked;
13981da177e4SLinus Torvalds 				mapping = page_mapping(page);
13991da177e4SLinus Torvalds 			case PAGE_CLEAN:
14001da177e4SLinus Torvalds 				; /* try to free the page below */
14011da177e4SLinus Torvalds 			}
14021da177e4SLinus Torvalds 		}
14031da177e4SLinus Torvalds 
14041da177e4SLinus Torvalds 		/*
14051da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
14061da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
14071da177e4SLinus Torvalds 		 * the page as well.
14081da177e4SLinus Torvalds 		 *
14091da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
14101da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
14111da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
14121da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
14131da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
14141da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
14151da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
14161da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
14171da177e4SLinus Torvalds 		 *
14181da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
14191da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
14201da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
14211da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
14221da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
14231da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
14241da177e4SLinus Torvalds 		 */
1425266cf658SDavid Howells 		if (page_has_private(page)) {
14261da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14271da177e4SLinus Torvalds 				goto activate_locked;
1428e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1429e286781dSNick Piggin 				unlock_page(page);
1430e286781dSNick Piggin 				if (put_page_testzero(page))
14311da177e4SLinus Torvalds 					goto free_it;
1432e286781dSNick Piggin 				else {
1433e286781dSNick Piggin 					/*
1434e286781dSNick Piggin 					 * rare race with speculative reference.
1435e286781dSNick Piggin 					 * the speculative reference will free
1436e286781dSNick Piggin 					 * this page shortly, so we may
1437e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1438e286781dSNick Piggin 					 * leave it off the LRU).
1439e286781dSNick Piggin 					 */
1440e286781dSNick Piggin 					nr_reclaimed++;
1441e286781dSNick Piggin 					continue;
1442e286781dSNick Piggin 				}
1443e286781dSNick Piggin 			}
14441da177e4SLinus Torvalds 		}
14451da177e4SLinus Torvalds 
1446802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1447802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1448802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
144949d2e9ccSChristoph Lameter 				goto keep_locked;
1450802a3a92SShaohua Li 			if (PageDirty(page)) {
1451802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1452802a3a92SShaohua Li 				goto keep_locked;
1453802a3a92SShaohua Li 			}
14541da177e4SLinus Torvalds 
1455802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14562262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1457802a3a92SShaohua Li 		} else if (!mapping || !__remove_mapping(mapping, page, true))
1458802a3a92SShaohua Li 			goto keep_locked;
1459a978d6f5SNick Piggin 		/*
1460a978d6f5SNick Piggin 		 * At this point, we have no other references and there is
1461a978d6f5SNick Piggin 		 * no way to pick any more up (removed from LRU, removed
1462a978d6f5SNick Piggin 		 * from pagecache). Can use non-atomic bitops now (and
1463a978d6f5SNick Piggin 		 * we obviously don't have to worry about waking up a process
1464a978d6f5SNick Piggin 		 * waiting on the page lock, because there are no references.
1465a978d6f5SNick Piggin 		 */
146648c935adSKirill A. Shutemov 		__ClearPageLocked(page);
1467e286781dSNick Piggin free_it:
146805ff5137SAndrew Morton 		nr_reclaimed++;
1469abe4c3b5SMel Gorman 
1470abe4c3b5SMel Gorman 		/*
1471abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1472abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1473abe4c3b5SMel Gorman 		 */
1474bd4c82c2SHuang Ying 		if (unlikely(PageTransHuge(page))) {
1475bd4c82c2SHuang Ying 			mem_cgroup_uncharge(page);
1476bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
1477bd4c82c2SHuang Ying 		} else
1478abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14791da177e4SLinus Torvalds 		continue;
14801da177e4SLinus Torvalds 
14811da177e4SLinus Torvalds activate_locked:
148268a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1483ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1484ad6b6704SMinchan Kim 						PageMlocked(page)))
1485a2c43eedSHugh Dickins 			try_to_free_swap(page);
1486309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1487ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
14881da177e4SLinus Torvalds 			SetPageActive(page);
14891da177e4SLinus Torvalds 			pgactivate++;
14902262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1491ad6b6704SMinchan Kim 		}
14921da177e4SLinus Torvalds keep_locked:
14931da177e4SLinus Torvalds 		unlock_page(page);
14941da177e4SLinus Torvalds keep:
14951da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1496309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14971da177e4SLinus Torvalds 	}
1498abe4c3b5SMel Gorman 
1499747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
150072b252aeSMel Gorman 	try_to_unmap_flush();
15012d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1502abe4c3b5SMel Gorman 
15031da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1504f8891e5eSChristoph Lameter 	count_vm_events(PGACTIVATE, pgactivate);
15050a31bc97SJohannes Weiner 
15063c710c1aSMichal Hocko 	if (stat) {
15073c710c1aSMichal Hocko 		stat->nr_dirty = nr_dirty;
15083c710c1aSMichal Hocko 		stat->nr_congested = nr_congested;
15093c710c1aSMichal Hocko 		stat->nr_unqueued_dirty = nr_unqueued_dirty;
15103c710c1aSMichal Hocko 		stat->nr_writeback = nr_writeback;
15113c710c1aSMichal Hocko 		stat->nr_immediate = nr_immediate;
15125bccd166SMichal Hocko 		stat->nr_activate = pgactivate;
15135bccd166SMichal Hocko 		stat->nr_ref_keep = nr_ref_keep;
15145bccd166SMichal Hocko 		stat->nr_unmap_fail = nr_unmap_fail;
15153c710c1aSMichal Hocko 	}
151605ff5137SAndrew Morton 	return nr_reclaimed;
15171da177e4SLinus Torvalds }
15181da177e4SLinus Torvalds 
151902c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
152002c6de8dSMinchan Kim 					    struct list_head *page_list)
152102c6de8dSMinchan Kim {
152202c6de8dSMinchan Kim 	struct scan_control sc = {
152302c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
152402c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
152502c6de8dSMinchan Kim 		.may_unmap = 1,
152602c6de8dSMinchan Kim 	};
15273c710c1aSMichal Hocko 	unsigned long ret;
152802c6de8dSMinchan Kim 	struct page *page, *next;
152902c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
153002c6de8dSMinchan Kim 
153102c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1532117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1533b1123ea6SMinchan Kim 		    !__PageMovable(page)) {
153402c6de8dSMinchan Kim 			ClearPageActive(page);
153502c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
153602c6de8dSMinchan Kim 		}
153702c6de8dSMinchan Kim 	}
153802c6de8dSMinchan Kim 
1539599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1540a128ca71SShaohua Li 			TTU_IGNORE_ACCESS, NULL, true);
154102c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1542599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
154302c6de8dSMinchan Kim 	return ret;
154402c6de8dSMinchan Kim }
154502c6de8dSMinchan Kim 
15465ad333ebSAndy Whitcroft /*
15475ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15485ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15495ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15505ad333ebSAndy Whitcroft  *
15515ad333ebSAndy Whitcroft  * page:	page to consider
15525ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15535ad333ebSAndy Whitcroft  *
15545ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15555ad333ebSAndy Whitcroft  */
1556f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15575ad333ebSAndy Whitcroft {
15585ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15595ad333ebSAndy Whitcroft 
15605ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15615ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15625ad333ebSAndy Whitcroft 		return ret;
15635ad333ebSAndy Whitcroft 
1564e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1565e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1566894bc310SLee Schermerhorn 		return ret;
1567894bc310SLee Schermerhorn 
15685ad333ebSAndy Whitcroft 	ret = -EBUSY;
156908e552c6SKAMEZAWA Hiroyuki 
1570c8244935SMel Gorman 	/*
1571c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1572c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1573c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1574c8244935SMel Gorman 	 *
1575c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1576c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1577c8244935SMel Gorman 	 */
15781276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1579c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1580c8244935SMel Gorman 		if (PageWriteback(page))
158139deaf85SMinchan Kim 			return ret;
158239deaf85SMinchan Kim 
1583c8244935SMel Gorman 		if (PageDirty(page)) {
1584c8244935SMel Gorman 			struct address_space *mapping;
158569d763fcSMel Gorman 			bool migrate_dirty;
1586c8244935SMel Gorman 
1587c8244935SMel Gorman 			/*
1588c8244935SMel Gorman 			 * Only pages without mappings or that have a
1589c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
159069d763fcSMel Gorman 			 * without blocking. However, we can be racing with
159169d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
159269d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
159369d763fcSMel Gorman 			 * the page lock until after the page is removed
159469d763fcSMel Gorman 			 * from the page cache.
1595c8244935SMel Gorman 			 */
159669d763fcSMel Gorman 			if (!trylock_page(page))
159769d763fcSMel Gorman 				return ret;
159869d763fcSMel Gorman 
1599c8244935SMel Gorman 			mapping = page_mapping(page);
1600145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
160169d763fcSMel Gorman 			unlock_page(page);
160269d763fcSMel Gorman 			if (!migrate_dirty)
1603c8244935SMel Gorman 				return ret;
1604c8244935SMel Gorman 		}
1605c8244935SMel Gorman 	}
1606c8244935SMel Gorman 
1607f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1608f80c0673SMinchan Kim 		return ret;
1609f80c0673SMinchan Kim 
16105ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
16115ad333ebSAndy Whitcroft 		/*
16125ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
16135ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
16145ad333ebSAndy Whitcroft 		 * page release code relies on it.
16155ad333ebSAndy Whitcroft 		 */
16165ad333ebSAndy Whitcroft 		ClearPageLRU(page);
16175ad333ebSAndy Whitcroft 		ret = 0;
16185ad333ebSAndy Whitcroft 	}
16195ad333ebSAndy Whitcroft 
16205ad333ebSAndy Whitcroft 	return ret;
16215ad333ebSAndy Whitcroft }
16225ad333ebSAndy Whitcroft 
16237ee36a14SMel Gorman 
16247ee36a14SMel Gorman /*
16257ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
16267ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
16277ee36a14SMel Gorman  */
16287ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1629b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16307ee36a14SMel Gorman {
16317ee36a14SMel Gorman 	int zid;
16327ee36a14SMel Gorman 
16337ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16347ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16357ee36a14SMel Gorman 			continue;
16367ee36a14SMel Gorman 
16377ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1638b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1639b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1640b4536f0cSMichal Hocko #endif
16417ee36a14SMel Gorman 	}
16427ee36a14SMel Gorman 
16437ee36a14SMel Gorman }
16447ee36a14SMel Gorman 
164549d2e9ccSChristoph Lameter /*
1646a52633d8SMel Gorman  * zone_lru_lock is heavily contended.  Some of the functions that
16471da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16481da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16491da177e4SLinus Torvalds  *
16501da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16511da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16521da177e4SLinus Torvalds  *
16531da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16541da177e4SLinus Torvalds  *
1655791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16565dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16571da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1658f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1659fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16605ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16613cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16621da177e4SLinus Torvalds  *
16631da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16641da177e4SLinus Torvalds  */
166569e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16665dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1667fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
16683cb99451SKonstantin Khlebnikov 		isolate_mode_t mode, enum lru_list lru)
16691da177e4SLinus Torvalds {
167075b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
167169e05944SAndrew Morton 	unsigned long nr_taken = 0;
1672599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16737cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16743db65812SJohannes Weiner 	unsigned long skipped = 0;
1675791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1676b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
16771da177e4SLinus Torvalds 
1678791b48b6SMinchan Kim 	scan = 0;
1679791b48b6SMinchan Kim 	for (total_scan = 0;
1680791b48b6SMinchan Kim 	     scan < nr_to_scan && nr_taken < nr_to_scan && !list_empty(src);
1681791b48b6SMinchan Kim 	     total_scan++) {
16825ad333ebSAndy Whitcroft 		struct page *page;
16835ad333ebSAndy Whitcroft 
16841da177e4SLinus Torvalds 		page = lru_to_page(src);
16851da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16861da177e4SLinus Torvalds 
1687309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16888d438f96SNick Piggin 
1689b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1690b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
16917cc30fcfSMel Gorman 			nr_skipped[page_zonenum(page)]++;
1692b2e18757SMel Gorman 			continue;
1693b2e18757SMel Gorman 		}
1694b2e18757SMel Gorman 
1695791b48b6SMinchan Kim 		/*
1696791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1697791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1698791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1699791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
1700791b48b6SMinchan Kim 		 */
1701791b48b6SMinchan Kim 		scan++;
1702f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
17035ad333ebSAndy Whitcroft 		case 0:
1704599d0c95SMel Gorman 			nr_pages = hpage_nr_pages(page);
1705599d0c95SMel Gorman 			nr_taken += nr_pages;
1706599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
17075ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
17085ad333ebSAndy Whitcroft 			break;
17097c8ee9a8SNick Piggin 
17105ad333ebSAndy Whitcroft 		case -EBUSY:
17115ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
17125ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
17135ad333ebSAndy Whitcroft 			continue;
17145ad333ebSAndy Whitcroft 
17155ad333ebSAndy Whitcroft 		default:
17165ad333ebSAndy Whitcroft 			BUG();
17175ad333ebSAndy Whitcroft 		}
17185ad333ebSAndy Whitcroft 	}
17191da177e4SLinus Torvalds 
1720b2e18757SMel Gorman 	/*
1721b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1722b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1723b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1724b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1725b2e18757SMel Gorman 	 * system at risk of premature OOM.
1726b2e18757SMel Gorman 	 */
17277cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17287cc30fcfSMel Gorman 		int zid;
17297cc30fcfSMel Gorman 
17303db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17317cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17327cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17337cc30fcfSMel Gorman 				continue;
17347cc30fcfSMel Gorman 
17357cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17361265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17377cc30fcfSMel Gorman 		}
17387cc30fcfSMel Gorman 	}
1739791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17401265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1741791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1742b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17431da177e4SLinus Torvalds 	return nr_taken;
17441da177e4SLinus Torvalds }
17451da177e4SLinus Torvalds 
174662695a84SNick Piggin /**
174762695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
174862695a84SNick Piggin  * @page: page to isolate from its LRU list
174962695a84SNick Piggin  *
175062695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
175162695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
175262695a84SNick Piggin  *
175362695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
175462695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
175562695a84SNick Piggin  *
175662695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1757894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1758894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1759894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
176062695a84SNick Piggin  *
176162695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
176262695a84SNick Piggin  * found will be decremented.
176362695a84SNick Piggin  *
176462695a84SNick Piggin  * Restrictions:
1765a5d09bedSMike Rapoport  *
176662695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
176762695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
176862695a84SNick Piggin  *     without a stable reference).
176962695a84SNick Piggin  * (2) the lru_lock must not be held.
177062695a84SNick Piggin  * (3) interrupts must be enabled.
177162695a84SNick Piggin  */
177262695a84SNick Piggin int isolate_lru_page(struct page *page)
177362695a84SNick Piggin {
177462695a84SNick Piggin 	int ret = -EBUSY;
177562695a84SNick Piggin 
1776309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1777cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17780c917313SKonstantin Khlebnikov 
177962695a84SNick Piggin 	if (PageLRU(page)) {
178062695a84SNick Piggin 		struct zone *zone = page_zone(page);
1781fa9add64SHugh Dickins 		struct lruvec *lruvec;
178262695a84SNick Piggin 
1783a52633d8SMel Gorman 		spin_lock_irq(zone_lru_lock(zone));
1784599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, zone->zone_pgdat);
17850c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1786894bc310SLee Schermerhorn 			int lru = page_lru(page);
17870c917313SKonstantin Khlebnikov 			get_page(page);
178862695a84SNick Piggin 			ClearPageLRU(page);
1789fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1790fa9add64SHugh Dickins 			ret = 0;
179162695a84SNick Piggin 		}
1792a52633d8SMel Gorman 		spin_unlock_irq(zone_lru_lock(zone));
179362695a84SNick Piggin 	}
179462695a84SNick Piggin 	return ret;
179562695a84SNick Piggin }
179662695a84SNick Piggin 
17975ad333ebSAndy Whitcroft /*
1798d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1799d37dd5dcSFengguang Wu  * then get resheduled. When there are massive number of tasks doing page
1800d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1801d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1802d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
180335cd7815SRik van Riel  */
1804599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
180535cd7815SRik van Riel 		struct scan_control *sc)
180635cd7815SRik van Riel {
180735cd7815SRik van Riel 	unsigned long inactive, isolated;
180835cd7815SRik van Riel 
180935cd7815SRik van Riel 	if (current_is_kswapd())
181035cd7815SRik van Riel 		return 0;
181135cd7815SRik van Riel 
181297c9341fSTejun Heo 	if (!sane_reclaim(sc))
181335cd7815SRik van Riel 		return 0;
181435cd7815SRik van Riel 
181535cd7815SRik van Riel 	if (file) {
1816599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1817599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
181835cd7815SRik van Riel 	} else {
1819599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1820599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
182135cd7815SRik van Riel 	}
182235cd7815SRik van Riel 
18233cf23841SFengguang Wu 	/*
18243cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18253cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18263cf23841SFengguang Wu 	 * deadlock.
18273cf23841SFengguang Wu 	 */
1828d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18293cf23841SFengguang Wu 		inactive >>= 3;
18303cf23841SFengguang Wu 
183135cd7815SRik van Riel 	return isolated > inactive;
183235cd7815SRik van Riel }
183335cd7815SRik van Riel 
183466635629SMel Gorman static noinline_for_stack void
183575b00af7SHugh Dickins putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
183666635629SMel Gorman {
183727ac81d8SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1838599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
18393f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
184066635629SMel Gorman 
184166635629SMel Gorman 	/*
184266635629SMel Gorman 	 * Put back any unfreeable pages.
184366635629SMel Gorman 	 */
184466635629SMel Gorman 	while (!list_empty(page_list)) {
18453f79768fSHugh Dickins 		struct page *page = lru_to_page(page_list);
184666635629SMel Gorman 		int lru;
18473f79768fSHugh Dickins 
1848309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
184966635629SMel Gorman 		list_del(&page->lru);
185039b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1851599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
185266635629SMel Gorman 			putback_lru_page(page);
1853599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
185466635629SMel Gorman 			continue;
185566635629SMel Gorman 		}
1856fa9add64SHugh Dickins 
1857599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1858fa9add64SHugh Dickins 
18597a608572SLinus Torvalds 		SetPageLRU(page);
186066635629SMel Gorman 		lru = page_lru(page);
1861fa9add64SHugh Dickins 		add_page_to_lru_list(page, lruvec, lru);
1862fa9add64SHugh Dickins 
186366635629SMel Gorman 		if (is_active_lru(lru)) {
186466635629SMel Gorman 			int file = is_file_lru(lru);
18659992af10SRik van Riel 			int numpages = hpage_nr_pages(page);
18669992af10SRik van Riel 			reclaim_stat->recent_rotated[file] += numpages;
186766635629SMel Gorman 		}
18682bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18692bcf8879SHugh Dickins 			__ClearPageLRU(page);
18702bcf8879SHugh Dickins 			__ClearPageActive(page);
1871fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18722bcf8879SHugh Dickins 
18732bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1874599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
1875747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
18762bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1877599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18782bcf8879SHugh Dickins 			} else
18792bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
188066635629SMel Gorman 		}
188166635629SMel Gorman 	}
188266635629SMel Gorman 
18833f79768fSHugh Dickins 	/*
18843f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
18853f79768fSHugh Dickins 	 */
18863f79768fSHugh Dickins 	list_splice(&pages_to_free, page_list);
188766635629SMel Gorman }
188866635629SMel Gorman 
188966635629SMel Gorman /*
1890399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1891399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1892399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1893399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1894399ba0b9SNeilBrown  */
1895399ba0b9SNeilBrown static int current_may_throttle(void)
1896399ba0b9SNeilBrown {
1897399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1898399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1899399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1900399ba0b9SNeilBrown }
1901399ba0b9SNeilBrown 
1902399ba0b9SNeilBrown /*
1903b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
19041742f19fSAndrew Morton  * of reclaimed pages
19051da177e4SLinus Torvalds  */
190666635629SMel Gorman static noinline_for_stack unsigned long
19071a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19089e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19091da177e4SLinus Torvalds {
19101da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1911e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
191205ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1913e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
19143c710c1aSMichal Hocko 	struct reclaim_stat stat = {};
1915f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
19163cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1917599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19181a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1919db73ee0dSMichal Hocko 	bool stalled = false;
192078dc583dSKOSAKI Motohiro 
1921599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1922db73ee0dSMichal Hocko 		if (stalled)
1923db73ee0dSMichal Hocko 			return 0;
1924db73ee0dSMichal Hocko 
1925db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1926db73ee0dSMichal Hocko 		msleep(100);
1927db73ee0dSMichal Hocko 		stalled = true;
192835cd7815SRik van Riel 
192935cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
193035cd7815SRik van Riel 		if (fatal_signal_pending(current))
193135cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
193235cd7815SRik van Riel 	}
193335cd7815SRik van Riel 
19341da177e4SLinus Torvalds 	lru_add_drain();
1935f80c0673SMinchan Kim 
1936f80c0673SMinchan Kim 	if (!sc->may_unmap)
193761317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
1938f80c0673SMinchan Kim 
1939599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19401da177e4SLinus Torvalds 
19415dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
19425dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
194395d918fcSKonstantin Khlebnikov 
1944599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19459d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
194695d918fcSKonstantin Khlebnikov 
19472262185cSRoman Gushchin 	if (current_is_kswapd()) {
19482262185cSRoman Gushchin 		if (global_reclaim(sc))
1949599d0c95SMel Gorman 			__count_vm_events(PGSCAN_KSWAPD, nr_scanned);
19502262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_KSWAPD,
19512262185cSRoman Gushchin 				   nr_scanned);
19522262185cSRoman Gushchin 	} else {
19532262185cSRoman Gushchin 		if (global_reclaim(sc))
1954599d0c95SMel Gorman 			__count_vm_events(PGSCAN_DIRECT, nr_scanned);
19552262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSCAN_DIRECT,
19562262185cSRoman Gushchin 				   nr_scanned);
1957b35ea17bSKOSAKI Motohiro 	}
1958599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1959d563c050SHillf Danton 
1960d563c050SHillf Danton 	if (nr_taken == 0)
196166635629SMel Gorman 		return 0;
1962b35ea17bSKOSAKI Motohiro 
1963a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19643c710c1aSMichal Hocko 				&stat, false);
1965c661b078SAndy Whitcroft 
1966599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19673f79768fSHugh Dickins 
19682262185cSRoman Gushchin 	if (current_is_kswapd()) {
19692262185cSRoman Gushchin 		if (global_reclaim(sc))
1970599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_KSWAPD, nr_reclaimed);
19712262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_KSWAPD,
19722262185cSRoman Gushchin 				   nr_reclaimed);
19732262185cSRoman Gushchin 	} else {
19742262185cSRoman Gushchin 		if (global_reclaim(sc))
1975599d0c95SMel Gorman 			__count_vm_events(PGSTEAL_DIRECT, nr_reclaimed);
19762262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGSTEAL_DIRECT,
19772262185cSRoman Gushchin 				   nr_reclaimed);
1978904249aaSYing Han 	}
1979a74609faSNick Piggin 
198027ac81d8SKonstantin Khlebnikov 	putback_inactive_pages(lruvec, &page_list);
19813f79768fSHugh Dickins 
1982599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19833f79768fSHugh Dickins 
1984599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19853f79768fSHugh Dickins 
1986747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19872d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1988e11da5b4SMel Gorman 
198992df3a72SMel Gorman 	/*
19901c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19911c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19921c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19931c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19941c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19951c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
19961c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
19971c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
19981c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
19991c610d5fSAndrey Ryabinin 	 */
20001c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
20011c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
20021c610d5fSAndrey Ryabinin 
2003d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
2004d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
2005d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2006d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
2007d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
2008d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2009d108c772SAndrey Ryabinin 	if (file)
2010d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
20118e950282SMel Gorman 
2012599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2013d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
201405ff5137SAndrew Morton 	return nr_reclaimed;
20151da177e4SLinus Torvalds }
20161da177e4SLinus Torvalds 
20173bb1a852SMartin Bligh /*
20181cfb419bSKAMEZAWA Hiroyuki  * This moves pages from the active list to the inactive list.
20191cfb419bSKAMEZAWA Hiroyuki  *
20201cfb419bSKAMEZAWA Hiroyuki  * We move them the other way if the page is referenced by one or more
20211cfb419bSKAMEZAWA Hiroyuki  * processes, from rmap.
20221cfb419bSKAMEZAWA Hiroyuki  *
20231cfb419bSKAMEZAWA Hiroyuki  * If the pages are mostly unmapped, the processing is fast and it is
2024a52633d8SMel Gorman  * appropriate to hold zone_lru_lock across the whole operation.  But if
20251cfb419bSKAMEZAWA Hiroyuki  * the pages are mapped, the processing is slow (page_referenced()) so we
2026a52633d8SMel Gorman  * should drop zone_lru_lock around each page.  It's impossible to balance
20271cfb419bSKAMEZAWA Hiroyuki  * this, so instead we remove the pages from the LRU while processing them.
20281cfb419bSKAMEZAWA Hiroyuki  * It is safe to rely on PG_active against the non-LRU pages in here because
20291cfb419bSKAMEZAWA Hiroyuki  * nobody will play with that bit on a non-LRU page.
20301cfb419bSKAMEZAWA Hiroyuki  *
20310139aa7bSJoonsoo Kim  * The downside is that we have to touch page->_refcount against each page.
20321cfb419bSKAMEZAWA Hiroyuki  * But we had to alter page->flags anyway.
20339d998b4fSMichal Hocko  *
20349d998b4fSMichal Hocko  * Returns the number of pages moved to the given lru.
20351cfb419bSKAMEZAWA Hiroyuki  */
20361cfb419bSKAMEZAWA Hiroyuki 
20379d998b4fSMichal Hocko static unsigned move_active_pages_to_lru(struct lruvec *lruvec,
20383eb4140fSWu Fengguang 				     struct list_head *list,
20392bcf8879SHugh Dickins 				     struct list_head *pages_to_free,
20403eb4140fSWu Fengguang 				     enum lru_list lru)
20413eb4140fSWu Fengguang {
2042599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20433eb4140fSWu Fengguang 	struct page *page;
2044fa9add64SHugh Dickins 	int nr_pages;
20459d998b4fSMichal Hocko 	int nr_moved = 0;
20463eb4140fSWu Fengguang 
20473eb4140fSWu Fengguang 	while (!list_empty(list)) {
20483eb4140fSWu Fengguang 		page = lru_to_page(list);
2049599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
20503eb4140fSWu Fengguang 
2051309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
20523eb4140fSWu Fengguang 		SetPageLRU(page);
20533eb4140fSWu Fengguang 
2054fa9add64SHugh Dickins 		nr_pages = hpage_nr_pages(page);
2055599d0c95SMel Gorman 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
2056925b7673SJohannes Weiner 		list_move(&page->lru, &lruvec->lists[lru]);
20573eb4140fSWu Fengguang 
20582bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
20592bcf8879SHugh Dickins 			__ClearPageLRU(page);
20602bcf8879SHugh Dickins 			__ClearPageActive(page);
2061fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
20622bcf8879SHugh Dickins 
20632bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
2064599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
2065747db954SJohannes Weiner 				mem_cgroup_uncharge(page);
20662bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
2067599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
20682bcf8879SHugh Dickins 			} else
20692bcf8879SHugh Dickins 				list_add(&page->lru, pages_to_free);
20709d998b4fSMichal Hocko 		} else {
20719d998b4fSMichal Hocko 			nr_moved += nr_pages;
20723eb4140fSWu Fengguang 		}
20733eb4140fSWu Fengguang 	}
20749d5e6a9fSHugh Dickins 
20752262185cSRoman Gushchin 	if (!is_active_lru(lru)) {
2076f0958906SMichal Hocko 		__count_vm_events(PGDEACTIVATE, nr_moved);
20772262185cSRoman Gushchin 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
20782262185cSRoman Gushchin 				   nr_moved);
20792262185cSRoman Gushchin 	}
20809d998b4fSMichal Hocko 
20819d998b4fSMichal Hocko 	return nr_moved;
20823eb4140fSWu Fengguang }
20831cfb419bSKAMEZAWA Hiroyuki 
2084f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20851a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2086f16015fbSJohannes Weiner 			       struct scan_control *sc,
20879e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20881cfb419bSKAMEZAWA Hiroyuki {
208944c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2090f626012dSHugh Dickins 	unsigned long nr_scanned;
20916fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20921cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20938cab4754SWu Fengguang 	LIST_HEAD(l_active);
2094b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20951cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20961a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20979d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20989d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
2099f3fd4a61SKonstantin Khlebnikov 	isolate_mode_t isolate_mode = 0;
21003cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2101599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
21021cfb419bSKAMEZAWA Hiroyuki 
21031da177e4SLinus Torvalds 	lru_add_drain();
2104f80c0673SMinchan Kim 
2105f80c0673SMinchan Kim 	if (!sc->may_unmap)
210661317289SHillf Danton 		isolate_mode |= ISOLATE_UNMAPPED;
2107f80c0673SMinchan Kim 
2108599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2109925b7673SJohannes Weiner 
21105dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
21115dc35979SKonstantin Khlebnikov 				     &nr_scanned, sc, isolate_mode, lru);
211289b5fae5SJohannes Weiner 
2113599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2114b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
21151cfb419bSKAMEZAWA Hiroyuki 
2116599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
21172262185cSRoman Gushchin 	count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
21189d5e6a9fSHugh Dickins 
2119599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21201da177e4SLinus Torvalds 
21211da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
21221da177e4SLinus Torvalds 		cond_resched();
21231da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
21241da177e4SLinus Torvalds 		list_del(&page->lru);
21257e9cd484SRik van Riel 
212639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2127894bc310SLee Schermerhorn 			putback_lru_page(page);
2128894bc310SLee Schermerhorn 			continue;
2129894bc310SLee Schermerhorn 		}
2130894bc310SLee Schermerhorn 
2131cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2132cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2133cc715d99SMel Gorman 				if (page_has_private(page))
2134cc715d99SMel Gorman 					try_to_release_page(page, 0);
2135cc715d99SMel Gorman 				unlock_page(page);
2136cc715d99SMel Gorman 			}
2137cc715d99SMel Gorman 		}
2138cc715d99SMel Gorman 
2139c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2140c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
21419992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
21428cab4754SWu Fengguang 			/*
21438cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
21448cab4754SWu Fengguang 			 * give them one more trip around the active list. So
21458cab4754SWu Fengguang 			 * that executable code get better chances to stay in
21468cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
21478cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
21488cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
21498cab4754SWu Fengguang 			 * so we ignore them here.
21508cab4754SWu Fengguang 			 */
215141e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
21528cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
21538cab4754SWu Fengguang 				continue;
21548cab4754SWu Fengguang 			}
21558cab4754SWu Fengguang 		}
21567e9cd484SRik van Riel 
21575205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
21581899ad18SJohannes Weiner 		SetPageWorkingset(page);
21591da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
21601da177e4SLinus Torvalds 	}
21611da177e4SLinus Torvalds 
2162b555749aSAndrew Morton 	/*
21638cab4754SWu Fengguang 	 * Move pages back to the lru list.
2164b555749aSAndrew Morton 	 */
2165599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
21664f98a2feSRik van Riel 	/*
21678cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
21688cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
21698cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
21707c0db9e9SJerome Marchand 	 * get_scan_count.
2171556adecbSRik van Riel 	 */
2172b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2173556adecbSRik van Riel 
21749d998b4fSMichal Hocko 	nr_activate = move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
21759d998b4fSMichal Hocko 	nr_deactivate = move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
2176599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2177599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21782bcf8879SHugh Dickins 
2179747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&l_hold);
21802d4894b5SMel Gorman 	free_unref_page_list(&l_hold);
21819d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21829d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21831da177e4SLinus Torvalds }
21841da177e4SLinus Torvalds 
218559dc76b0SRik van Riel /*
218659dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
218759dc76b0SRik van Riel  * to do too much work.
218814797e23SKOSAKI Motohiro  *
218959dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
219059dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
219159dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
219259dc76b0SRik van Riel  *
219359dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
219459dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
219559dc76b0SRik van Riel  *
21962a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21972a2e4885SJohannes Weiner  *
219859dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21993a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
220059dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
220159dc76b0SRik van Riel  *
220259dc76b0SRik van Riel  * total     target    max
220359dc76b0SRik van Riel  * memory    ratio     inactive
220459dc76b0SRik van Riel  * -------------------------------------
220559dc76b0SRik van Riel  *   10MB       1         5MB
220659dc76b0SRik van Riel  *  100MB       1        50MB
220759dc76b0SRik van Riel  *    1GB       3       250MB
220859dc76b0SRik van Riel  *   10GB      10       0.9GB
220959dc76b0SRik van Riel  *  100GB      31         3GB
221059dc76b0SRik van Riel  *    1TB     101        10GB
221159dc76b0SRik van Riel  *   10TB     320        32GB
221214797e23SKOSAKI Motohiro  */
2213f8d1a311SMel Gorman static bool inactive_list_is_low(struct lruvec *lruvec, bool file,
22142a2e4885SJohannes Weiner 				 struct mem_cgroup *memcg,
22152a2e4885SJohannes Weiner 				 struct scan_control *sc, bool actual_reclaim)
221614797e23SKOSAKI Motohiro {
2217fd538803SMichal Hocko 	enum lru_list active_lru = file * LRU_FILE + LRU_ACTIVE;
22182a2e4885SJohannes Weiner 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22192a2e4885SJohannes Weiner 	enum lru_list inactive_lru = file * LRU_FILE;
22202a2e4885SJohannes Weiner 	unsigned long inactive, active;
22212a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
22222a2e4885SJohannes Weiner 	unsigned long refaults;
222359dc76b0SRik van Riel 	unsigned long gb;
222459dc76b0SRik van Riel 
222574e3f3c3SMinchan Kim 	/*
222674e3f3c3SMinchan Kim 	 * If we don't have swap space, anonymous page deactivation
222774e3f3c3SMinchan Kim 	 * is pointless.
222874e3f3c3SMinchan Kim 	 */
222959dc76b0SRik van Riel 	if (!file && !total_swap_pages)
223042e2e457SYaowei Bai 		return false;
223174e3f3c3SMinchan Kim 
2232fd538803SMichal Hocko 	inactive = lruvec_lru_size(lruvec, inactive_lru, sc->reclaim_idx);
2233fd538803SMichal Hocko 	active = lruvec_lru_size(lruvec, active_lru, sc->reclaim_idx);
2234f8d1a311SMel Gorman 
22352a2e4885SJohannes Weiner 	if (memcg)
2236ccda7f43SJohannes Weiner 		refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
22372a2e4885SJohannes Weiner 	else
22382a2e4885SJohannes Weiner 		refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
22392a2e4885SJohannes Weiner 
22402a2e4885SJohannes Weiner 	/*
22412a2e4885SJohannes Weiner 	 * When refaults are being observed, it means a new workingset
22422a2e4885SJohannes Weiner 	 * is being established. Disable active list protection to get
22432a2e4885SJohannes Weiner 	 * rid of the stale workingset quickly.
22442a2e4885SJohannes Weiner 	 */
22452a2e4885SJohannes Weiner 	if (file && actual_reclaim && lruvec->refaults != refaults) {
22462a2e4885SJohannes Weiner 		inactive_ratio = 0;
22472a2e4885SJohannes Weiner 	} else {
224859dc76b0SRik van Riel 		gb = (inactive + active) >> (30 - PAGE_SHIFT);
224959dc76b0SRik van Riel 		if (gb)
225059dc76b0SRik van Riel 			inactive_ratio = int_sqrt(10 * gb);
2251b39415b2SRik van Riel 		else
225259dc76b0SRik van Riel 			inactive_ratio = 1;
22532a2e4885SJohannes Weiner 	}
225459dc76b0SRik van Riel 
22552a2e4885SJohannes Weiner 	if (actual_reclaim)
22562a2e4885SJohannes Weiner 		trace_mm_vmscan_inactive_list_is_low(pgdat->node_id, sc->reclaim_idx,
2257fd538803SMichal Hocko 			lruvec_lru_size(lruvec, inactive_lru, MAX_NR_ZONES), inactive,
2258fd538803SMichal Hocko 			lruvec_lru_size(lruvec, active_lru, MAX_NR_ZONES), active,
2259fd538803SMichal Hocko 			inactive_ratio, file);
2260fd538803SMichal Hocko 
226159dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2262b39415b2SRik van Riel }
2263b39415b2SRik van Riel 
22644f98a2feSRik van Riel static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
22652a2e4885SJohannes Weiner 				 struct lruvec *lruvec, struct mem_cgroup *memcg,
22662a2e4885SJohannes Weiner 				 struct scan_control *sc)
2267b69408e8SChristoph Lameter {
2268b39415b2SRik van Riel 	if (is_active_lru(lru)) {
22692a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, is_file_lru(lru),
22702a2e4885SJohannes Weiner 					 memcg, sc, true))
22711a93be0eSKonstantin Khlebnikov 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2272556adecbSRik van Riel 		return 0;
2273556adecbSRik van Riel 	}
2274556adecbSRik van Riel 
22751a93be0eSKonstantin Khlebnikov 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2276b69408e8SChristoph Lameter }
2277b69408e8SChristoph Lameter 
22789a265114SJohannes Weiner enum scan_balance {
22799a265114SJohannes Weiner 	SCAN_EQUAL,
22809a265114SJohannes Weiner 	SCAN_FRACT,
22819a265114SJohannes Weiner 	SCAN_ANON,
22829a265114SJohannes Weiner 	SCAN_FILE,
22839a265114SJohannes Weiner };
22849a265114SJohannes Weiner 
22851da177e4SLinus Torvalds /*
22864f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22874f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22884f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22894f98a2feSRik van Riel  * onto the active list instead of evict.
22904f98a2feSRik van Riel  *
2291be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2292be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22934f98a2feSRik van Riel  */
229433377678SVladimir Davydov static void get_scan_count(struct lruvec *lruvec, struct mem_cgroup *memcg,
22956b4f7799SJohannes Weiner 			   struct scan_control *sc, unsigned long *nr,
22966b4f7799SJohannes Weiner 			   unsigned long *lru_pages)
22974f98a2feSRik van Riel {
229833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
229990126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
23009a265114SJohannes Weiner 	u64 fraction[2];
23019a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2302599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
23039a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
23049a265114SJohannes Weiner 	enum scan_balance scan_balance;
23050bf1457fSJohannes Weiner 	unsigned long anon, file;
23069a265114SJohannes Weiner 	unsigned long ap, fp;
23079a265114SJohannes Weiner 	enum lru_list lru;
230876a33fc3SShaohua Li 
230976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2310d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
23119a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
231276a33fc3SShaohua Li 		goto out;
231376a33fc3SShaohua Li 	}
23144f98a2feSRik van Riel 
231510316b31SJohannes Weiner 	/*
231610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
231710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
231810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
231910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
232010316b31SJohannes Weiner 	 * too expensive.
232110316b31SJohannes Weiner 	 */
232202695175SJohannes Weiner 	if (!global_reclaim(sc) && !swappiness) {
23239a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
232410316b31SJohannes Weiner 		goto out;
232510316b31SJohannes Weiner 	}
232610316b31SJohannes Weiner 
232710316b31SJohannes Weiner 	/*
232810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
232910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
233010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
233110316b31SJohannes Weiner 	 */
233202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
23339a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
233410316b31SJohannes Weiner 		goto out;
233510316b31SJohannes Weiner 	}
233610316b31SJohannes Weiner 
233711d16c25SJohannes Weiner 	/*
233862376251SJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
233962376251SJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
234062376251SJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
234162376251SJohannes Weiner 	 * shrinks, so does the window for rotation from references.
234262376251SJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
234362376251SJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
234462376251SJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
234562376251SJohannes Weiner 	 */
234662376251SJohannes Weiner 	if (global_reclaim(sc)) {
2347599d0c95SMel Gorman 		unsigned long pgdatfile;
2348599d0c95SMel Gorman 		unsigned long pgdatfree;
2349599d0c95SMel Gorman 		int z;
2350599d0c95SMel Gorman 		unsigned long total_high_wmark = 0;
235162376251SJohannes Weiner 
2352599d0c95SMel Gorman 		pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2353599d0c95SMel Gorman 		pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2354599d0c95SMel Gorman 			   node_page_state(pgdat, NR_INACTIVE_FILE);
23552ab051e1SJerome Marchand 
2356599d0c95SMel Gorman 		for (z = 0; z < MAX_NR_ZONES; z++) {
2357599d0c95SMel Gorman 			struct zone *zone = &pgdat->node_zones[z];
23586aa303deSMel Gorman 			if (!managed_zone(zone))
2359599d0c95SMel Gorman 				continue;
2360599d0c95SMel Gorman 
2361599d0c95SMel Gorman 			total_high_wmark += high_wmark_pages(zone);
2362599d0c95SMel Gorman 		}
2363599d0c95SMel Gorman 
2364599d0c95SMel Gorman 		if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
236506226226SDavid Rientjes 			/*
236606226226SDavid Rientjes 			 * Force SCAN_ANON if there are enough inactive
236706226226SDavid Rientjes 			 * anonymous pages on the LRU in eligible zones.
236806226226SDavid Rientjes 			 * Otherwise, the small LRU gets thrashed.
236906226226SDavid Rientjes 			 */
237006226226SDavid Rientjes 			if (!inactive_list_is_low(lruvec, false, memcg, sc, false) &&
237106226226SDavid Rientjes 			    lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
237206226226SDavid Rientjes 					>> sc->priority) {
237362376251SJohannes Weiner 				scan_balance = SCAN_ANON;
237462376251SJohannes Weiner 				goto out;
237562376251SJohannes Weiner 			}
237662376251SJohannes Weiner 		}
237706226226SDavid Rientjes 	}
237862376251SJohannes Weiner 
237962376251SJohannes Weiner 	/*
2380316bda0eSVladimir Davydov 	 * If there is enough inactive page cache, i.e. if the size of the
2381316bda0eSVladimir Davydov 	 * inactive list is greater than that of the active list *and* the
2382316bda0eSVladimir Davydov 	 * inactive list actually has some pages to scan on this priority, we
2383316bda0eSVladimir Davydov 	 * do not reclaim anything from the anonymous working set right now.
2384316bda0eSVladimir Davydov 	 * Without the second condition we could end up never scanning an
2385316bda0eSVladimir Davydov 	 * lruvec even if it has plenty of old anonymous pages unless the
2386316bda0eSVladimir Davydov 	 * system is under heavy pressure.
2387e9868505SRik van Riel 	 */
23882a2e4885SJohannes Weiner 	if (!inactive_list_is_low(lruvec, true, memcg, sc, false) &&
238971ab6cfeSMichal Hocko 	    lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
23909a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2391e9868505SRik van Riel 		goto out;
23924f98a2feSRik van Riel 	}
23934f98a2feSRik van Riel 
23949a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23959a265114SJohannes Weiner 
23964f98a2feSRik van Riel 	/*
239758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
239858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
239958c37f6eSKOSAKI Motohiro 	 */
240002695175SJohannes Weiner 	anon_prio = swappiness;
240175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
240258c37f6eSKOSAKI Motohiro 
240358c37f6eSKOSAKI Motohiro 	/*
24044f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
24054f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
24064f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
24074f98a2feSRik van Riel 	 *
24084f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
24094f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
24104f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
24114f98a2feSRik van Riel 	 *
24124f98a2feSRik van Riel 	 * anon in [0], file in [1]
24134f98a2feSRik van Riel 	 */
24142ab051e1SJerome Marchand 
2415fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2416fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2417fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2418fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
24192ab051e1SJerome Marchand 
2420599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
242158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
24226e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
24236e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
24244f98a2feSRik van Riel 	}
24254f98a2feSRik van Riel 
24266e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
24276e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
24286e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
24294f98a2feSRik van Riel 	}
24304f98a2feSRik van Riel 
24314f98a2feSRik van Riel 	/*
243200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
243300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
243400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
24354f98a2feSRik van Riel 	 */
2436fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
24376e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
24384f98a2feSRik van Riel 
2439fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
24406e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2441599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
24424f98a2feSRik van Riel 
244376a33fc3SShaohua Li 	fraction[0] = ap;
244476a33fc3SShaohua Li 	fraction[1] = fp;
244576a33fc3SShaohua Li 	denominator = ap + fp + 1;
244676a33fc3SShaohua Li out:
24476b4f7799SJohannes Weiner 	*lru_pages = 0;
24484111304dSHugh Dickins 	for_each_evictable_lru(lru) {
24494111304dSHugh Dickins 		int file = is_file_lru(lru);
2450d778df51SJohannes Weiner 		unsigned long size;
245176a33fc3SShaohua Li 		unsigned long scan;
245276a33fc3SShaohua Li 
245371ab6cfeSMichal Hocko 		size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2454d778df51SJohannes Weiner 		scan = size >> sc->priority;
2455688035f7SJohannes Weiner 		/*
2456688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2457688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2458688035f7SJohannes Weiner 		 */
2459688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
2460d778df51SJohannes Weiner 			scan = min(size, SWAP_CLUSTER_MAX);
24619a265114SJohannes Weiner 
24629a265114SJohannes Weiner 		switch (scan_balance) {
24639a265114SJohannes Weiner 		case SCAN_EQUAL:
24649a265114SJohannes Weiner 			/* Scan lists relative to size */
24659a265114SJohannes Weiner 			break;
24669a265114SJohannes Weiner 		case SCAN_FRACT:
24679a265114SJohannes Weiner 			/*
24689a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
24699a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
247068600f62SRoman Gushchin 			 * Make sure we don't miss the last page
247168600f62SRoman Gushchin 			 * because of a round-off error.
24729a265114SJohannes Weiner 			 */
247368600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
24746f04f48dSSuleiman Souhlal 						  denominator);
24759a265114SJohannes Weiner 			break;
24769a265114SJohannes Weiner 		case SCAN_FILE:
24779a265114SJohannes Weiner 		case SCAN_ANON:
24789a265114SJohannes Weiner 			/* Scan one type exclusively */
24796b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
24806b4f7799SJohannes Weiner 				size = 0;
24819a265114SJohannes Weiner 				scan = 0;
24826b4f7799SJohannes Weiner 			}
24839a265114SJohannes Weiner 			break;
24849a265114SJohannes Weiner 		default:
24859a265114SJohannes Weiner 			/* Look ma, no brain */
24869a265114SJohannes Weiner 			BUG();
24879a265114SJohannes Weiner 		}
24886b4f7799SJohannes Weiner 
24896b4f7799SJohannes Weiner 		*lru_pages += size;
24904111304dSHugh Dickins 		nr[lru] = scan;
249176a33fc3SShaohua Li 	}
24926e08a369SWu Fengguang }
24934f98a2feSRik van Riel 
24949b4f98cdSJohannes Weiner /*
2495a9dd0a83SMel Gorman  * This is a basic per-node page freer.  Used by both kswapd and direct reclaim.
24969b4f98cdSJohannes Weiner  */
2497a9dd0a83SMel Gorman static void shrink_node_memcg(struct pglist_data *pgdat, struct mem_cgroup *memcg,
24986b4f7799SJohannes Weiner 			      struct scan_control *sc, unsigned long *lru_pages)
24999b4f98cdSJohannes Weiner {
2500ef8f2327SMel Gorman 	struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
25019b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2502e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
25039b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
25049b4f98cdSJohannes Weiner 	enum lru_list lru;
25059b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
25069b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
25079b4f98cdSJohannes Weiner 	struct blk_plug plug;
25081a501907SMel Gorman 	bool scan_adjusted;
25099b4f98cdSJohannes Weiner 
251033377678SVladimir Davydov 	get_scan_count(lruvec, memcg, sc, nr, lru_pages);
25119b4f98cdSJohannes Weiner 
2512e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2513e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2514e82e0561SMel Gorman 
25151a501907SMel Gorman 	/*
25161a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
25171a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
25181a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
25191a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
25201a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
25211a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
25221a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
25231a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
25241a501907SMel Gorman 	 * dropped to zero at the first pass.
25251a501907SMel Gorman 	 */
25261a501907SMel Gorman 	scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
25271a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
25281a501907SMel Gorman 
25299b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
25309b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
25319b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2532e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2533e82e0561SMel Gorman 		unsigned long nr_scanned;
2534e82e0561SMel Gorman 
25359b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
25369b4f98cdSJohannes Weiner 			if (nr[lru]) {
25379b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
25389b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
25399b4f98cdSJohannes Weiner 
25409b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
25412a2e4885SJohannes Weiner 							    lruvec, memcg, sc);
25429b4f98cdSJohannes Weiner 			}
25439b4f98cdSJohannes Weiner 		}
2544e82e0561SMel Gorman 
2545bd041733SMichal Hocko 		cond_resched();
2546bd041733SMichal Hocko 
2547e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2548e82e0561SMel Gorman 			continue;
2549e82e0561SMel Gorman 
25509b4f98cdSJohannes Weiner 		/*
2551e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25521a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2553e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2554e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2555e82e0561SMel Gorman 		 * proportional to the original scan target.
2556e82e0561SMel Gorman 		 */
2557e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2558e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2559e82e0561SMel Gorman 
25601a501907SMel Gorman 		/*
25611a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
25621a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
25631a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
25641a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
25651a501907SMel Gorman 		 */
25661a501907SMel Gorman 		if (!nr_file || !nr_anon)
25671a501907SMel Gorman 			break;
25681a501907SMel Gorman 
2569e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2570e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2571e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2572e82e0561SMel Gorman 			lru = LRU_BASE;
2573e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2574e82e0561SMel Gorman 		} else {
2575e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2576e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2577e82e0561SMel Gorman 			lru = LRU_FILE;
2578e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2579e82e0561SMel Gorman 		}
2580e82e0561SMel Gorman 
2581e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2582e82e0561SMel Gorman 		nr[lru] = 0;
2583e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2584e82e0561SMel Gorman 
2585e82e0561SMel Gorman 		/*
2586e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2587e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2588e82e0561SMel Gorman 		 */
2589e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2590e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2591e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2592e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2593e82e0561SMel Gorman 
2594e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2595e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2596e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2597e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2598e82e0561SMel Gorman 
2599e82e0561SMel Gorman 		scan_adjusted = true;
26009b4f98cdSJohannes Weiner 	}
26019b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
26029b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
26039b4f98cdSJohannes Weiner 
26049b4f98cdSJohannes Weiner 	/*
26059b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
26069b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
26079b4f98cdSJohannes Weiner 	 */
26082a2e4885SJohannes Weiner 	if (inactive_list_is_low(lruvec, false, memcg, sc, true))
26099b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
26109b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
26119b4f98cdSJohannes Weiner }
26129b4f98cdSJohannes Weiner 
261323b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
26149e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
261523b9da55SMel Gorman {
2616d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
261723b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
26189e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
261923b9da55SMel Gorman 		return true;
262023b9da55SMel Gorman 
262123b9da55SMel Gorman 	return false;
262223b9da55SMel Gorman }
262323b9da55SMel Gorman 
26244f98a2feSRik van Riel /*
262523b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
262623b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
262723b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
262823b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
262923b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
26303e7d3449SMel Gorman  */
2631a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
26323e7d3449SMel Gorman 					unsigned long nr_reclaimed,
26333e7d3449SMel Gorman 					unsigned long nr_scanned,
26343e7d3449SMel Gorman 					struct scan_control *sc)
26353e7d3449SMel Gorman {
26363e7d3449SMel Gorman 	unsigned long pages_for_compaction;
26373e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2638a9dd0a83SMel Gorman 	int z;
26393e7d3449SMel Gorman 
26403e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
26419e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
26423e7d3449SMel Gorman 		return false;
26433e7d3449SMel Gorman 
26442876592fSMel Gorman 	/* Consider stopping depending on scan and reclaim activity */
2645dcda9b04SMichal Hocko 	if (sc->gfp_mask & __GFP_RETRY_MAYFAIL) {
26463e7d3449SMel Gorman 		/*
2647dcda9b04SMichal Hocko 		 * For __GFP_RETRY_MAYFAIL allocations, stop reclaiming if the
26482876592fSMel Gorman 		 * full LRU list has been scanned and we are still failing
26492876592fSMel Gorman 		 * to reclaim pages. This full LRU scan is potentially
2650dcda9b04SMichal Hocko 		 * expensive but a __GFP_RETRY_MAYFAIL caller really wants to succeed
26513e7d3449SMel Gorman 		 */
26523e7d3449SMel Gorman 		if (!nr_reclaimed && !nr_scanned)
26533e7d3449SMel Gorman 			return false;
26542876592fSMel Gorman 	} else {
26552876592fSMel Gorman 		/*
2656dcda9b04SMichal Hocko 		 * For non-__GFP_RETRY_MAYFAIL allocations which can presumably
26572876592fSMel Gorman 		 * fail without consequence, stop if we failed to reclaim
26582876592fSMel Gorman 		 * any pages from the last SWAP_CLUSTER_MAX number of
26592876592fSMel Gorman 		 * pages that were scanned. This will return to the
26602876592fSMel Gorman 		 * caller faster at the risk reclaim/compaction and
26612876592fSMel Gorman 		 * the resulting allocation attempt fails
26622876592fSMel Gorman 		 */
26632876592fSMel Gorman 		if (!nr_reclaimed)
26642876592fSMel Gorman 			return false;
26652876592fSMel Gorman 	}
26663e7d3449SMel Gorman 
26673e7d3449SMel Gorman 	/*
26683e7d3449SMel Gorman 	 * If we have not reclaimed enough pages for compaction and the
26693e7d3449SMel Gorman 	 * inactive lists are large enough, continue reclaiming
26703e7d3449SMel Gorman 	 */
26719861a62cSVlastimil Babka 	pages_for_compaction = compact_gap(sc->order);
2672a9dd0a83SMel Gorman 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2673ec8acf20SShaohua Li 	if (get_nr_swap_pages() > 0)
2674a9dd0a83SMel Gorman 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
26753e7d3449SMel Gorman 	if (sc->nr_reclaimed < pages_for_compaction &&
26763e7d3449SMel Gorman 			inactive_lru_pages > pages_for_compaction)
26773e7d3449SMel Gorman 		return true;
26783e7d3449SMel Gorman 
26793e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2680a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2681a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
26826aa303deSMel Gorman 		if (!managed_zone(zone))
2683a9dd0a83SMel Gorman 			continue;
2684a9dd0a83SMel Gorman 
2685a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2686cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
26873e7d3449SMel Gorman 		case COMPACT_CONTINUE:
26883e7d3449SMel Gorman 			return false;
26893e7d3449SMel Gorman 		default:
2690a9dd0a83SMel Gorman 			/* check next zone */
2691a9dd0a83SMel Gorman 			;
26923e7d3449SMel Gorman 		}
26933e7d3449SMel Gorman 	}
2694a9dd0a83SMel Gorman 	return true;
2695a9dd0a83SMel Gorman }
26963e7d3449SMel Gorman 
2697e3c1ac58SAndrey Ryabinin static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2698e3c1ac58SAndrey Ryabinin {
2699e3c1ac58SAndrey Ryabinin 	return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2700e3c1ac58SAndrey Ryabinin 		(memcg && memcg_congested(pgdat, memcg));
2701e3c1ac58SAndrey Ryabinin }
2702e3c1ac58SAndrey Ryabinin 
2703970a39a3SMel Gorman static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2704f16015fbSJohannes Weiner {
2705cb731d6cSVladimir Davydov 	struct reclaim_state *reclaim_state = current->reclaim_state;
27069b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27072344d7e4SJohannes Weiner 	bool reclaimable = false;
27089b4f98cdSJohannes Weiner 
27099b4f98cdSJohannes Weiner 	do {
27105660048cSJohannes Weiner 		struct mem_cgroup *root = sc->target_mem_cgroup;
27115660048cSJohannes Weiner 		struct mem_cgroup_reclaim_cookie reclaim = {
2712ef8f2327SMel Gorman 			.pgdat = pgdat,
27139e3b2f8cSKonstantin Khlebnikov 			.priority = sc->priority,
27145660048cSJohannes Weiner 		};
2715a9dd0a83SMel Gorman 		unsigned long node_lru_pages = 0;
2716694fbc0fSAndrew Morton 		struct mem_cgroup *memcg;
27175660048cSJohannes Weiner 
2718d108c772SAndrey Ryabinin 		memset(&sc->nr, 0, sizeof(sc->nr));
2719d108c772SAndrey Ryabinin 
27209b4f98cdSJohannes Weiner 		nr_reclaimed = sc->nr_reclaimed;
27219b4f98cdSJohannes Weiner 		nr_scanned = sc->nr_scanned;
27229b4f98cdSJohannes Weiner 
2723694fbc0fSAndrew Morton 		memcg = mem_cgroup_iter(root, NULL, &reclaim);
2724694fbc0fSAndrew Morton 		do {
27256b4f7799SJohannes Weiner 			unsigned long lru_pages;
27268e8ae645SJohannes Weiner 			unsigned long reclaimed;
2727cb731d6cSVladimir Davydov 			unsigned long scanned;
27289b4f98cdSJohannes Weiner 
2729bf8d5d52SRoman Gushchin 			switch (mem_cgroup_protected(root, memcg)) {
2730bf8d5d52SRoman Gushchin 			case MEMCG_PROT_MIN:
2731bf8d5d52SRoman Gushchin 				/*
2732bf8d5d52SRoman Gushchin 				 * Hard protection.
2733bf8d5d52SRoman Gushchin 				 * If there is no reclaimable memory, OOM.
2734bf8d5d52SRoman Gushchin 				 */
2735bf8d5d52SRoman Gushchin 				continue;
2736bf8d5d52SRoman Gushchin 			case MEMCG_PROT_LOW:
2737bf8d5d52SRoman Gushchin 				/*
2738bf8d5d52SRoman Gushchin 				 * Soft protection.
2739bf8d5d52SRoman Gushchin 				 * Respect the protection only as long as
2740bf8d5d52SRoman Gushchin 				 * there is an unprotected supply
2741bf8d5d52SRoman Gushchin 				 * of reclaimable memory from other cgroups.
2742bf8d5d52SRoman Gushchin 				 */
2743d6622f63SYisheng Xie 				if (!sc->memcg_low_reclaim) {
2744d6622f63SYisheng Xie 					sc->memcg_low_skipped = 1;
2745241994edSJohannes Weiner 					continue;
2746d6622f63SYisheng Xie 				}
2747e27be240SJohannes Weiner 				memcg_memory_event(memcg, MEMCG_LOW);
2748bf8d5d52SRoman Gushchin 				break;
2749bf8d5d52SRoman Gushchin 			case MEMCG_PROT_NONE:
2750bf8d5d52SRoman Gushchin 				break;
2751241994edSJohannes Weiner 			}
2752241994edSJohannes Weiner 
27538e8ae645SJohannes Weiner 			reclaimed = sc->nr_reclaimed;
2754cb731d6cSVladimir Davydov 			scanned = sc->nr_scanned;
2755a9dd0a83SMel Gorman 			shrink_node_memcg(pgdat, memcg, sc, &lru_pages);
2756a9dd0a83SMel Gorman 			node_lru_pages += lru_pages;
2757f9be23d6SKonstantin Khlebnikov 
2758a9dd0a83SMel Gorman 			shrink_slab(sc->gfp_mask, pgdat->node_id,
27599092c71bSJosef Bacik 				    memcg, sc->priority);
2760cb731d6cSVladimir Davydov 
27618e8ae645SJohannes Weiner 			/* Record the group's reclaim efficiency */
27628e8ae645SJohannes Weiner 			vmpressure(sc->gfp_mask, memcg, false,
27638e8ae645SJohannes Weiner 				   sc->nr_scanned - scanned,
27648e8ae645SJohannes Weiner 				   sc->nr_reclaimed - reclaimed);
27658e8ae645SJohannes Weiner 
27665660048cSJohannes Weiner 			/*
2767a394cb8eSMichal Hocko 			 * Direct reclaim and kswapd have to scan all memory
2768a394cb8eSMichal Hocko 			 * cgroups to fulfill the overall scan target for the
2769a9dd0a83SMel Gorman 			 * node.
2770a394cb8eSMichal Hocko 			 *
2771a394cb8eSMichal Hocko 			 * Limit reclaim, on the other hand, only cares about
2772a394cb8eSMichal Hocko 			 * nr_to_reclaim pages to be reclaimed and it will
2773a394cb8eSMichal Hocko 			 * retry with decreasing priority if one round over the
2774a394cb8eSMichal Hocko 			 * whole hierarchy is not sufficient.
27755660048cSJohannes Weiner 			 */
2776a394cb8eSMichal Hocko 			if (!global_reclaim(sc) &&
2777a394cb8eSMichal Hocko 					sc->nr_reclaimed >= sc->nr_to_reclaim) {
27785660048cSJohannes Weiner 				mem_cgroup_iter_break(root, memcg);
27795660048cSJohannes Weiner 				break;
27805660048cSJohannes Weiner 			}
2781241994edSJohannes Weiner 		} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
278270ddf637SAnton Vorontsov 
27836b4f7799SJohannes Weiner 		if (reclaim_state) {
2784cb731d6cSVladimir Davydov 			sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27856b4f7799SJohannes Weiner 			reclaim_state->reclaimed_slab = 0;
27866b4f7799SJohannes Weiner 		}
27876b4f7799SJohannes Weiner 
27888e8ae645SJohannes Weiner 		/* Record the subtree's reclaim efficiency */
27898e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
279070ddf637SAnton Vorontsov 			   sc->nr_scanned - nr_scanned,
279170ddf637SAnton Vorontsov 			   sc->nr_reclaimed - nr_reclaimed);
279270ddf637SAnton Vorontsov 
27932344d7e4SJohannes Weiner 		if (sc->nr_reclaimed - nr_reclaimed)
27942344d7e4SJohannes Weiner 			reclaimable = true;
27952344d7e4SJohannes Weiner 
2796e3c1ac58SAndrey Ryabinin 		if (current_is_kswapd()) {
2797d108c772SAndrey Ryabinin 			/*
2798e3c1ac58SAndrey Ryabinin 			 * If reclaim is isolating dirty pages under writeback,
2799e3c1ac58SAndrey Ryabinin 			 * it implies that the long-lived page allocation rate
2800e3c1ac58SAndrey Ryabinin 			 * is exceeding the page laundering rate. Either the
2801e3c1ac58SAndrey Ryabinin 			 * global limits are not being effective at throttling
2802e3c1ac58SAndrey Ryabinin 			 * processes due to the page distribution throughout
2803e3c1ac58SAndrey Ryabinin 			 * zones or there is heavy usage of a slow backing
2804e3c1ac58SAndrey Ryabinin 			 * device. The only option is to throttle from reclaim
2805e3c1ac58SAndrey Ryabinin 			 * context which is not ideal as there is no guarantee
2806d108c772SAndrey Ryabinin 			 * the dirtying process is throttled in the same way
2807d108c772SAndrey Ryabinin 			 * balance_dirty_pages() manages.
2808d108c772SAndrey Ryabinin 			 *
2809e3c1ac58SAndrey Ryabinin 			 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2810e3c1ac58SAndrey Ryabinin 			 * count the number of pages under pages flagged for
2811e3c1ac58SAndrey Ryabinin 			 * immediate reclaim and stall if any are encountered
2812e3c1ac58SAndrey Ryabinin 			 * in the nr_immediate check below.
2813d108c772SAndrey Ryabinin 			 */
2814d108c772SAndrey Ryabinin 			if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2815d108c772SAndrey Ryabinin 				set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2816d108c772SAndrey Ryabinin 
2817d108c772SAndrey Ryabinin 			/*
2818d108c772SAndrey Ryabinin 			 * Tag a node as congested if all the dirty pages
2819d108c772SAndrey Ryabinin 			 * scanned were backed by a congested BDI and
2820d108c772SAndrey Ryabinin 			 * wait_iff_congested will stall.
2821d108c772SAndrey Ryabinin 			 */
2822d108c772SAndrey Ryabinin 			if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2823d108c772SAndrey Ryabinin 				set_bit(PGDAT_CONGESTED, &pgdat->flags);
2824d108c772SAndrey Ryabinin 
2825d108c772SAndrey Ryabinin 			/* Allow kswapd to start writing pages during reclaim.*/
2826d108c772SAndrey Ryabinin 			if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2827d108c772SAndrey Ryabinin 				set_bit(PGDAT_DIRTY, &pgdat->flags);
2828d108c772SAndrey Ryabinin 
2829d108c772SAndrey Ryabinin 			/*
2830d108c772SAndrey Ryabinin 			 * If kswapd scans pages marked marked for immediate
2831d108c772SAndrey Ryabinin 			 * reclaim and under writeback (nr_immediate), it
2832d108c772SAndrey Ryabinin 			 * implies that pages are cycling through the LRU
2833d108c772SAndrey Ryabinin 			 * faster than they are written so also forcibly stall.
2834d108c772SAndrey Ryabinin 			 */
2835d108c772SAndrey Ryabinin 			if (sc->nr.immediate)
2836d108c772SAndrey Ryabinin 				congestion_wait(BLK_RW_ASYNC, HZ/10);
2837d108c772SAndrey Ryabinin 		}
2838d108c772SAndrey Ryabinin 
2839d108c772SAndrey Ryabinin 		/*
2840e3c1ac58SAndrey Ryabinin 		 * Legacy memcg will stall in page writeback so avoid forcibly
2841e3c1ac58SAndrey Ryabinin 		 * stalling in wait_iff_congested().
2842e3c1ac58SAndrey Ryabinin 		 */
2843e3c1ac58SAndrey Ryabinin 		if (!global_reclaim(sc) && sane_reclaim(sc) &&
2844e3c1ac58SAndrey Ryabinin 		    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2845e3c1ac58SAndrey Ryabinin 			set_memcg_congestion(pgdat, root, true);
2846e3c1ac58SAndrey Ryabinin 
2847e3c1ac58SAndrey Ryabinin 		/*
2848d108c772SAndrey Ryabinin 		 * Stall direct reclaim for IO completions if underlying BDIs
2849d108c772SAndrey Ryabinin 		 * and node is congested. Allow kswapd to continue until it
2850d108c772SAndrey Ryabinin 		 * starts encountering unqueued dirty pages or cycling through
2851d108c772SAndrey Ryabinin 		 * the LRU too quickly.
2852d108c772SAndrey Ryabinin 		 */
2853d108c772SAndrey Ryabinin 		if (!sc->hibernation_mode && !current_is_kswapd() &&
2854e3c1ac58SAndrey Ryabinin 		   current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2855e3c1ac58SAndrey Ryabinin 			wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2856d108c772SAndrey Ryabinin 
2857a9dd0a83SMel Gorman 	} while (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
28589b4f98cdSJohannes Weiner 					 sc->nr_scanned - nr_scanned, sc));
28592344d7e4SJohannes Weiner 
2860c73322d0SJohannes Weiner 	/*
2861c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2862c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2863c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2864c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2865c73322d0SJohannes Weiner 	 */
2866c73322d0SJohannes Weiner 	if (reclaimable)
2867c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2868c73322d0SJohannes Weiner 
28692344d7e4SJohannes Weiner 	return reclaimable;
2870f16015fbSJohannes Weiner }
2871f16015fbSJohannes Weiner 
287253853e2dSVlastimil Babka /*
2873fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2874fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2875fdd4c614SVlastimil Babka  * should reclaim first.
287653853e2dSVlastimil Babka  */
28774f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2878fe4b1b24SMel Gorman {
287931483b6aSMel Gorman 	unsigned long watermark;
2880fdd4c614SVlastimil Babka 	enum compact_result suitable;
2881fe4b1b24SMel Gorman 
2882fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2883fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2884fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2885fdd4c614SVlastimil Babka 		return true;
2886fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2887fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2888fe4b1b24SMel Gorman 		return false;
2889fe4b1b24SMel Gorman 
2890fdd4c614SVlastimil Babka 	/*
2891fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2892fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2893fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2894fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2895fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2896fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2897fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2898fdd4c614SVlastimil Babka 	 */
2899fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2900fdd4c614SVlastimil Babka 
2901fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2902fe4b1b24SMel Gorman }
2903fe4b1b24SMel Gorman 
29041da177e4SLinus Torvalds /*
29051da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
29061da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
29071da177e4SLinus Torvalds  * request.
29081da177e4SLinus Torvalds  *
29091da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
29101da177e4SLinus Torvalds  * scan then give up on it.
29111da177e4SLinus Torvalds  */
29120a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
29131da177e4SLinus Torvalds {
2914dd1a239fSMel Gorman 	struct zoneref *z;
291554a6eb5cSMel Gorman 	struct zone *zone;
29160608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29170608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2918619d0d76SWeijie Yang 	gfp_t orig_mask;
291979dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
29201cfb419bSKAMEZAWA Hiroyuki 
2921cc715d99SMel Gorman 	/*
2922cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2923cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2924cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2925cc715d99SMel Gorman 	 */
2926619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2927b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2928cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29294f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2930b2e18757SMel Gorman 	}
2931cc715d99SMel Gorman 
2932d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2933b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2934b2e18757SMel Gorman 		/*
29351cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29361cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29371cfb419bSKAMEZAWA Hiroyuki 		 */
293889b5fae5SJohannes Weiner 		if (global_reclaim(sc)) {
2939344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2940344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29411da177e4SLinus Torvalds 				continue;
294265ec02cbSVladimir Davydov 
2943e0887c19SRik van Riel 			/*
2944e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2945e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2946e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2947e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2948e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2949c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2950c7cfa37bSCopot Alexandru 			 * page allocations.
2951e0887c19SRik van Riel 			 */
29520b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29530b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29544f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29550b06496aSJohannes Weiner 				sc->compaction_ready = true;
2956e0887c19SRik van Riel 				continue;
2957e0887c19SRik van Riel 			}
29580b06496aSJohannes Weiner 
29590608f43dSAndrew Morton 			/*
296079dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
296179dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
296279dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
296379dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
296479dafcdcSMel Gorman 			 */
296579dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
296679dafcdcSMel Gorman 				continue;
296779dafcdcSMel Gorman 
296879dafcdcSMel Gorman 			/*
29690608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29700608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29710608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29720608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29730608f43dSAndrew Morton 			 */
29740608f43dSAndrew Morton 			nr_soft_scanned = 0;
2975ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29760608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29770608f43dSAndrew Morton 						&nr_soft_scanned);
29780608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29790608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2980ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2981ac34a1a3SKAMEZAWA Hiroyuki 		}
2982d149e3b2SYing Han 
298379dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
298479dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
298579dafcdcSMel Gorman 			continue;
298679dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2987970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29881da177e4SLinus Torvalds 	}
2989e0c23279SMel Gorman 
299065ec02cbSVladimir Davydov 	/*
2991619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2992619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
2993619d0d76SWeijie Yang 	 */
2994619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
29951da177e4SLinus Torvalds }
29961da177e4SLinus Torvalds 
29972a2e4885SJohannes Weiner static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
29982a2e4885SJohannes Weiner {
29992a2e4885SJohannes Weiner 	struct mem_cgroup *memcg;
30002a2e4885SJohannes Weiner 
30012a2e4885SJohannes Weiner 	memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
30022a2e4885SJohannes Weiner 	do {
30032a2e4885SJohannes Weiner 		unsigned long refaults;
30042a2e4885SJohannes Weiner 		struct lruvec *lruvec;
30052a2e4885SJohannes Weiner 
30062a2e4885SJohannes Weiner 		if (memcg)
3007ccda7f43SJohannes Weiner 			refaults = memcg_page_state(memcg, WORKINGSET_ACTIVATE);
30082a2e4885SJohannes Weiner 		else
30092a2e4885SJohannes Weiner 			refaults = node_page_state(pgdat, WORKINGSET_ACTIVATE);
30102a2e4885SJohannes Weiner 
30112a2e4885SJohannes Weiner 		lruvec = mem_cgroup_lruvec(pgdat, memcg);
30122a2e4885SJohannes Weiner 		lruvec->refaults = refaults;
30132a2e4885SJohannes Weiner 	} while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
30142a2e4885SJohannes Weiner }
30152a2e4885SJohannes Weiner 
30161da177e4SLinus Torvalds /*
30171da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
30181da177e4SLinus Torvalds  *
30191da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
30201da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
30211da177e4SLinus Torvalds  *
30221da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
30231da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
30245b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
30255b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
30265b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
30275b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3028a41f24eaSNishanth Aravamudan  *
3029a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3030a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30311da177e4SLinus Torvalds  */
3032dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30333115cd91SVladimir Davydov 					  struct scan_control *sc)
30341da177e4SLinus Torvalds {
3035241994edSJohannes Weiner 	int initial_priority = sc->priority;
30362a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30372a2e4885SJohannes Weiner 	struct zoneref *z;
30382a2e4885SJohannes Weiner 	struct zone *zone;
3039241994edSJohannes Weiner retry:
3040873b4771SKeika Kobayashi 	delayacct_freepages_start();
3041873b4771SKeika Kobayashi 
304289b5fae5SJohannes Weiner 	if (global_reclaim(sc))
30437cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30441da177e4SLinus Torvalds 
30459e3b2f8cSKonstantin Khlebnikov 	do {
304670ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
304770ddf637SAnton Vorontsov 				sc->priority);
304866e1707bSBalbir Singh 		sc->nr_scanned = 0;
30490a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3050e0c23279SMel Gorman 
3051bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30520b06496aSJohannes Weiner 			break;
30530b06496aSJohannes Weiner 
30540b06496aSJohannes Weiner 		if (sc->compaction_ready)
30550b06496aSJohannes Weiner 			break;
30561da177e4SLinus Torvalds 
30571da177e4SLinus Torvalds 		/*
30580e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30590e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30600e50ce3bSMinchan Kim 		 */
30610e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30620e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30630b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3064bb21c7ceSKOSAKI Motohiro 
30652a2e4885SJohannes Weiner 	last_pgdat = NULL;
30662a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30672a2e4885SJohannes Weiner 					sc->nodemask) {
30682a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30692a2e4885SJohannes Weiner 			continue;
30702a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
30712a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3072e3c1ac58SAndrey Ryabinin 		set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
30732a2e4885SJohannes Weiner 	}
30742a2e4885SJohannes Weiner 
3075873b4771SKeika Kobayashi 	delayacct_freepages_end();
3076873b4771SKeika Kobayashi 
3077bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3078bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3079bb21c7ceSKOSAKI Motohiro 
30800cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30810b06496aSJohannes Weiner 	if (sc->compaction_ready)
30827335084dSMel Gorman 		return 1;
30837335084dSMel Gorman 
3084241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3085d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3086241994edSJohannes Weiner 		sc->priority = initial_priority;
3087d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3088d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3089241994edSJohannes Weiner 		goto retry;
3090241994edSJohannes Weiner 	}
3091241994edSJohannes Weiner 
3092bb21c7ceSKOSAKI Motohiro 	return 0;
30931da177e4SLinus Torvalds }
30941da177e4SLinus Torvalds 
3095c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
30965515061dSMel Gorman {
30975515061dSMel Gorman 	struct zone *zone;
30985515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
30995515061dSMel Gorman 	unsigned long free_pages = 0;
31005515061dSMel Gorman 	int i;
31015515061dSMel Gorman 	bool wmark_ok;
31025515061dSMel Gorman 
3103c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3104c73322d0SJohannes Weiner 		return true;
3105c73322d0SJohannes Weiner 
31065515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
31075515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3108d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3109d450abd8SJohannes Weiner 			continue;
3110d450abd8SJohannes Weiner 
3111d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3112675becceSMel Gorman 			continue;
3113675becceSMel Gorman 
31145515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
31155515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
31165515061dSMel Gorman 	}
31175515061dSMel Gorman 
3118675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3119675becceSMel Gorman 	if (!pfmemalloc_reserve)
3120675becceSMel Gorman 		return true;
3121675becceSMel Gorman 
31225515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31235515061dSMel Gorman 
31245515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31255515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
312638087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
31275515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
31285515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31295515061dSMel Gorman 	}
31305515061dSMel Gorman 
31315515061dSMel Gorman 	return wmark_ok;
31325515061dSMel Gorman }
31335515061dSMel Gorman 
31345515061dSMel Gorman /*
31355515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31365515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31375515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
313850694c28SMel Gorman  * when the low watermark is reached.
313950694c28SMel Gorman  *
314050694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
314150694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31425515061dSMel Gorman  */
314350694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31445515061dSMel Gorman 					nodemask_t *nodemask)
31455515061dSMel Gorman {
3146675becceSMel Gorman 	struct zoneref *z;
31475515061dSMel Gorman 	struct zone *zone;
3148675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31495515061dSMel Gorman 
31505515061dSMel Gorman 	/*
31515515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31525515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31535515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31545515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31555515061dSMel Gorman 	 * processes to block on log_wait_commit().
31565515061dSMel Gorman 	 */
31575515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
315850694c28SMel Gorman 		goto out;
315950694c28SMel Gorman 
316050694c28SMel Gorman 	/*
316150694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
316250694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
316350694c28SMel Gorman 	 */
316450694c28SMel Gorman 	if (fatal_signal_pending(current))
316550694c28SMel Gorman 		goto out;
31665515061dSMel Gorman 
3167675becceSMel Gorman 	/*
3168675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3169675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3170675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3171675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3172675becceSMel Gorman 	 *
3173675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3174675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3175675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3176675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3177675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3178675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3179675becceSMel Gorman 	 * should make reasonable progress.
3180675becceSMel Gorman 	 */
3181675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
318217636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3183675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3184675becceSMel Gorman 			continue;
3185675becceSMel Gorman 
3186675becceSMel Gorman 		/* Throttle based on the first usable node */
31875515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3188c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
318950694c28SMel Gorman 			goto out;
3190675becceSMel Gorman 		break;
3191675becceSMel Gorman 	}
3192675becceSMel Gorman 
3193675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3194675becceSMel Gorman 	if (!pgdat)
3195675becceSMel Gorman 		goto out;
31965515061dSMel Gorman 
319768243e76SMel Gorman 	/* Account for the throttling */
319868243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
319968243e76SMel Gorman 
32005515061dSMel Gorman 	/*
32015515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
32025515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
32035515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
32045515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
32055515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
32065515061dSMel Gorman 	 * second before continuing.
32075515061dSMel Gorman 	 */
32085515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
32095515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3210c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
321150694c28SMel Gorman 
321250694c28SMel Gorman 		goto check_pending;
32135515061dSMel Gorman 	}
32145515061dSMel Gorman 
32155515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
32165515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3217c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
321850694c28SMel Gorman 
321950694c28SMel Gorman check_pending:
322050694c28SMel Gorman 	if (fatal_signal_pending(current))
322150694c28SMel Gorman 		return true;
322250694c28SMel Gorman 
322350694c28SMel Gorman out:
322450694c28SMel Gorman 	return false;
32255515061dSMel Gorman }
32265515061dSMel Gorman 
3227dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3228327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
322966e1707bSBalbir Singh {
323033906bc5SMel Gorman 	unsigned long nr_reclaimed;
323166e1707bSBalbir Singh 	struct scan_control sc = {
323222fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3233f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3234b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3235ee814fe2SJohannes Weiner 		.order = order,
3236ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3237ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3238ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3239a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32402e2e4259SKOSAKI Motohiro 		.may_swap = 1,
324166e1707bSBalbir Singh 	};
324266e1707bSBalbir Singh 
32435515061dSMel Gorman 	/*
3244bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3245bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3246bb451fdfSGreg Thelen 	 */
3247bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3248bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3249bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3250bb451fdfSGreg Thelen 
3251bb451fdfSGreg Thelen 	/*
325250694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
325350694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
325450694c28SMel Gorman 	 * point.
32555515061dSMel Gorman 	 */
3256f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32575515061dSMel Gorman 		return 1;
32585515061dSMel Gorman 
325933906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_begin(order,
326033906bc5SMel Gorman 				sc.may_writepage,
3261f2f43e56SNick Desaulniers 				sc.gfp_mask,
3262e5146b12SMel Gorman 				sc.reclaim_idx);
326333906bc5SMel Gorman 
32643115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
326533906bc5SMel Gorman 
326633906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
326733906bc5SMel Gorman 
326833906bc5SMel Gorman 	return nr_reclaimed;
326966e1707bSBalbir Singh }
327066e1707bSBalbir Singh 
3271c255a458SAndrew Morton #ifdef CONFIG_MEMCG
327266e1707bSBalbir Singh 
3273a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32744e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3275ef8f2327SMel Gorman 						pg_data_t *pgdat,
32760ae5e89cSYing Han 						unsigned long *nr_scanned)
32774e416953SBalbir Singh {
32784e416953SBalbir Singh 	struct scan_control sc = {
3279b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3280ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
32814e416953SBalbir Singh 		.may_writepage = !laptop_mode,
32824e416953SBalbir Singh 		.may_unmap = 1,
3283b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
32844e416953SBalbir Singh 		.may_swap = !noswap,
32854e416953SBalbir Singh 	};
32866b4f7799SJohannes Weiner 	unsigned long lru_pages;
32870ae5e89cSYing Han 
32884e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
32894e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3290bdce6d9eSKOSAKI Motohiro 
32919e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3292bdce6d9eSKOSAKI Motohiro 						      sc.may_writepage,
3293e5146b12SMel Gorman 						      sc.gfp_mask,
3294e5146b12SMel Gorman 						      sc.reclaim_idx);
3295bdce6d9eSKOSAKI Motohiro 
32964e416953SBalbir Singh 	/*
32974e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
32984e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3299a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
33004e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
33014e416953SBalbir Singh 	 * the priority and make it zero.
33024e416953SBalbir Singh 	 */
3303ef8f2327SMel Gorman 	shrink_node_memcg(pgdat, memcg, &sc, &lru_pages);
3304bdce6d9eSKOSAKI Motohiro 
3305bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3306bdce6d9eSKOSAKI Motohiro 
33070ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
33084e416953SBalbir Singh 	return sc.nr_reclaimed;
33094e416953SBalbir Singh }
33104e416953SBalbir Singh 
331172835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3312b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
33138c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3314b70a2a21SJohannes Weiner 					   bool may_swap)
331566e1707bSBalbir Singh {
33164e416953SBalbir Singh 	struct zonelist *zonelist;
3317bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3318eb414681SJohannes Weiner 	unsigned long pflags;
3319889976dbSYing Han 	int nid;
3320499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
332166e1707bSBalbir Singh 	struct scan_control sc = {
3322b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33237dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3324ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3325b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3326ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3327ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
332866e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3329a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3330b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3331a09ed5e0SYing Han 	};
333266e1707bSBalbir Singh 
3333889976dbSYing Han 	/*
3334889976dbSYing Han 	 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3335889976dbSYing Han 	 * take care of from where we get pages. So the node where we start the
3336889976dbSYing Han 	 * scan does not need to be the current node.
3337889976dbSYing Han 	 */
333872835c86SJohannes Weiner 	nid = mem_cgroup_select_victim_node(memcg);
3339889976dbSYing Han 
3340c9634cf0SAneesh Kumar K.V 	zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3341bdce6d9eSKOSAKI Motohiro 
3342bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_begin(0,
3343bdce6d9eSKOSAKI Motohiro 					    sc.may_writepage,
3344e5146b12SMel Gorman 					    sc.gfp_mask,
3345e5146b12SMel Gorman 					    sc.reclaim_idx);
3346bdce6d9eSKOSAKI Motohiro 
3347eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3348499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3349eb414681SJohannes Weiner 
33503115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3351eb414681SJohannes Weiner 
3352499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3353eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3354bdce6d9eSKOSAKI Motohiro 
3355bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3356bdce6d9eSKOSAKI Motohiro 
3357bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
335866e1707bSBalbir Singh }
335966e1707bSBalbir Singh #endif
336066e1707bSBalbir Singh 
33611d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3362ef8f2327SMel Gorman 				struct scan_control *sc)
3363f16015fbSJohannes Weiner {
3364b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3365b95a2f2dSJohannes Weiner 
3366b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3367b95a2f2dSJohannes Weiner 		return;
3368b95a2f2dSJohannes Weiner 
3369b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3370b95a2f2dSJohannes Weiner 	do {
3371ef8f2327SMel Gorman 		struct lruvec *lruvec = mem_cgroup_lruvec(pgdat, memcg);
3372f16015fbSJohannes Weiner 
33732a2e4885SJohannes Weiner 		if (inactive_list_is_low(lruvec, false, memcg, sc, true))
33741a93be0eSKonstantin Khlebnikov 			shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33759e3b2f8cSKonstantin Khlebnikov 					   sc, LRU_ACTIVE_ANON);
3376b95a2f2dSJohannes Weiner 
3377b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3378b95a2f2dSJohannes Weiner 	} while (memcg);
3379f16015fbSJohannes Weiner }
3380f16015fbSJohannes Weiner 
3381e716f2ebSMel Gorman /*
3382e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3383e716f2ebSMel Gorman  * and classzone_idx
3384e716f2ebSMel Gorman  */
3385e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
338660cefed4SJohannes Weiner {
3387e716f2ebSMel Gorman 	int i;
3388e716f2ebSMel Gorman 	unsigned long mark = -1;
3389e716f2ebSMel Gorman 	struct zone *zone;
339060cefed4SJohannes Weiner 
3391e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3392e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
33936256c6b4SMel Gorman 
3394e716f2ebSMel Gorman 		if (!managed_zone(zone))
3395e716f2ebSMel Gorman 			continue;
3396e716f2ebSMel Gorman 
3397e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3398e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
33996256c6b4SMel Gorman 			return true;
340060cefed4SJohannes Weiner 	}
340160cefed4SJohannes Weiner 
3402e716f2ebSMel Gorman 	/*
3403e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3404e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3405e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3406e716f2ebSMel Gorman 	 */
3407e716f2ebSMel Gorman 	if (mark == -1)
3408e716f2ebSMel Gorman 		return true;
3409e716f2ebSMel Gorman 
3410e716f2ebSMel Gorman 	return false;
3411e716f2ebSMel Gorman }
3412e716f2ebSMel Gorman 
3413631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3414631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3415631b6e08SMel Gorman {
3416631b6e08SMel Gorman 	clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3417631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3418631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3419631b6e08SMel Gorman }
3420631b6e08SMel Gorman 
34211741c877SMel Gorman /*
34225515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34235515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34245515061dSMel Gorman  *
34255515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34265515061dSMel Gorman  */
3427d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3428f50de2d3SMel Gorman {
34295515061dSMel Gorman 	/*
34309e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3431c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34329e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34339e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34349e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34359e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34369e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34379e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34389e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34399e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34409e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34415515061dSMel Gorman 	 */
34429e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
34439e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3444f50de2d3SMel Gorman 
3445c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3446c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3447c73322d0SJohannes Weiner 		return true;
3448c73322d0SJohannes Weiner 
3449e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3450631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3451333b0a45SShantanu Goel 		return true;
34521d82de61SMel Gorman 	}
34531d82de61SMel Gorman 
3454333b0a45SShantanu Goel 	return false;
3455f50de2d3SMel Gorman }
3456f50de2d3SMel Gorman 
34571da177e4SLinus Torvalds /*
34581d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
34591d82de61SMel Gorman  * zone that is currently unbalanced.
3460b8e83b94SMel Gorman  *
3461b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3462283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3463283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
346475485363SMel Gorman  */
34651d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3466accf6242SVlastimil Babka 			       struct scan_control *sc)
346775485363SMel Gorman {
34681d82de61SMel Gorman 	struct zone *zone;
34691d82de61SMel Gorman 	int z;
347075485363SMel Gorman 
34711d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
34721d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3473970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
34741d82de61SMel Gorman 		zone = pgdat->node_zones + z;
34756aa303deSMel Gorman 		if (!managed_zone(zone))
34761d82de61SMel Gorman 			continue;
34777c954f6dSMel Gorman 
34781d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
34797c954f6dSMel Gorman 	}
34807c954f6dSMel Gorman 
34811d82de61SMel Gorman 	/*
34821d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
34831d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
34841d82de61SMel Gorman 	 */
3485970a39a3SMel Gorman 	shrink_node(pgdat, sc);
34861d82de61SMel Gorman 
34871d82de61SMel Gorman 	/*
34881d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
34891d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
34901d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
34911d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
34921d82de61SMel Gorman 	 * can direct reclaim/compact.
34931d82de61SMel Gorman 	 */
34949861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
34951d82de61SMel Gorman 		sc->order = 0;
34961d82de61SMel Gorman 
3497b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
349875485363SMel Gorman }
349975485363SMel Gorman 
350075485363SMel Gorman /*
35011d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35021d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35031d82de61SMel Gorman  * balanced.
35041da177e4SLinus Torvalds  *
35051d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35061da177e4SLinus Torvalds  *
35071da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
350841858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35091d82de61SMel Gorman  * found to have free_pages <= high_wmark_pages(zone), any page is that zone
35101d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35111d82de61SMel Gorman  * balanced.
35121da177e4SLinus Torvalds  */
3513accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
35141da177e4SLinus Torvalds {
35151da177e4SLinus Torvalds 	int i;
35160608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35170608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3518eb414681SJohannes Weiner 	unsigned long pflags;
35191d82de61SMel Gorman 	struct zone *zone;
3520179e9639SAndrew Morton 	struct scan_control sc = {
3521179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3522ee814fe2SJohannes Weiner 		.order = order,
3523b8e83b94SMel Gorman 		.priority = DEF_PRIORITY,
3524ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3525a6dc60f8SJohannes Weiner 		.may_unmap = 1,
35262e2e4259SKOSAKI Motohiro 		.may_swap = 1,
3527179e9639SAndrew Morton 	};
352893781325SOmar Sandoval 
3529eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
353093781325SOmar Sandoval 	__fs_reclaim_acquire();
353193781325SOmar Sandoval 
3532f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35331da177e4SLinus Torvalds 
35349e3b2f8cSKonstantin Khlebnikov 	do {
3535c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3536b8e83b94SMel Gorman 		bool raise_priority = true;
353793781325SOmar Sandoval 		bool ret;
3538b8e83b94SMel Gorman 
353984c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
35401da177e4SLinus Torvalds 
354186c79f6bSMel Gorman 		/*
354284c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
354384c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
354484c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
354584c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
354684c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
354784c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
354884c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
354984c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
355086c79f6bSMel Gorman 		 */
355186c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
355286c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
355386c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
35546aa303deSMel Gorman 				if (!managed_zone(zone))
355586c79f6bSMel Gorman 					continue;
355686c79f6bSMel Gorman 
3557970a39a3SMel Gorman 				sc.reclaim_idx = i;
355886c79f6bSMel Gorman 				break;
355986c79f6bSMel Gorman 			}
356086c79f6bSMel Gorman 		}
356186c79f6bSMel Gorman 
356286c79f6bSMel Gorman 		/*
3563e716f2ebSMel Gorman 		 * Only reclaim if there are no eligible zones. Note that
3564e716f2ebSMel Gorman 		 * sc.reclaim_idx is not used as buffer_heads_over_limit may
3565e716f2ebSMel Gorman 		 * have adjusted it.
356686c79f6bSMel Gorman 		 */
3567e716f2ebSMel Gorman 		if (pgdat_balanced(pgdat, sc.order, classzone_idx))
35681da177e4SLinus Torvalds 			goto out;
3569e1dbeda6SAndrew Morton 
35701da177e4SLinus Torvalds 		/*
35711d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
35721d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
35731d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
35741d82de61SMel Gorman 		 * about consistent aging.
35751d82de61SMel Gorman 		 */
3576ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
35771d82de61SMel Gorman 
35781d82de61SMel Gorman 		/*
3579b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3580b7ea3c41SMel Gorman 		 * even in laptop mode.
3581b7ea3c41SMel Gorman 		 */
3582047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3583b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3584b7ea3c41SMel Gorman 
35851d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
35861da177e4SLinus Torvalds 		sc.nr_scanned = 0;
35870608f43dSAndrew Morton 		nr_soft_scanned = 0;
3588ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
35891d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
35900608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
35910608f43dSAndrew Morton 
359232a4330dSRik van Riel 		/*
35931d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
35941d82de61SMel Gorman 		 * enough pages are already being scanned that that high
35951d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
359632a4330dSRik van Riel 		 */
3597970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3598b8e83b94SMel Gorman 			raise_priority = false;
3599d7868daeSMel Gorman 
36005515061dSMel Gorman 		/*
36015515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
36025515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
36035515061dSMel Gorman 		 * able to safely make forward progress. Wake them
36045515061dSMel Gorman 		 */
36055515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3606c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3607cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
36085515061dSMel Gorman 
3609b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
361093781325SOmar Sandoval 		__fs_reclaim_release();
361193781325SOmar Sandoval 		ret = try_to_freeze();
361293781325SOmar Sandoval 		__fs_reclaim_acquire();
361393781325SOmar Sandoval 		if (ret || kthread_should_stop())
3614b8e83b94SMel Gorman 			break;
3615b8e83b94SMel Gorman 
3616b8e83b94SMel Gorman 		/*
3617b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3618b8e83b94SMel Gorman 		 * progress in reclaiming pages
3619b8e83b94SMel Gorman 		 */
3620c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3621c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3622b8e83b94SMel Gorman 			sc.priority--;
36231d82de61SMel Gorman 	} while (sc.priority >= 1);
36241da177e4SLinus Torvalds 
3625c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3626c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3627c73322d0SJohannes Weiner 
3628b8e83b94SMel Gorman out:
36292a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
363093781325SOmar Sandoval 	__fs_reclaim_release();
3631eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
36320abdee2bSMel Gorman 	/*
36331d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
36341d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
36351d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
36361d82de61SMel Gorman 	 * remain at the higher level.
36370abdee2bSMel Gorman 	 */
36381d82de61SMel Gorman 	return sc.order;
36391da177e4SLinus Torvalds }
36401da177e4SLinus Torvalds 
3641e716f2ebSMel Gorman /*
3642e716f2ebSMel Gorman  * pgdat->kswapd_classzone_idx is the highest zone index that a recent
3643e716f2ebSMel Gorman  * allocation request woke kswapd for. When kswapd has not woken recently,
3644e716f2ebSMel Gorman  * the value is MAX_NR_ZONES which is not a valid index. This compares a
3645e716f2ebSMel Gorman  * given classzone and returns it or the highest classzone index kswapd
3646e716f2ebSMel Gorman  * was recently woke for.
3647e716f2ebSMel Gorman  */
3648e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3649e716f2ebSMel Gorman 					   enum zone_type classzone_idx)
3650e716f2ebSMel Gorman {
3651e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3652e716f2ebSMel Gorman 		return classzone_idx;
3653e716f2ebSMel Gorman 
3654e716f2ebSMel Gorman 	return max(pgdat->kswapd_classzone_idx, classzone_idx);
3655e716f2ebSMel Gorman }
3656e716f2ebSMel Gorman 
365738087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
365838087d9bSMel Gorman 				unsigned int classzone_idx)
3659f0bc0a60SKOSAKI Motohiro {
3660f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3661f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3662f0bc0a60SKOSAKI Motohiro 
3663f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3664f0bc0a60SKOSAKI Motohiro 		return;
3665f0bc0a60SKOSAKI Motohiro 
3666f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3667f0bc0a60SKOSAKI Motohiro 
3668333b0a45SShantanu Goel 	/*
3669333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3670333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3671333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3672333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3673333b0a45SShantanu Goel 	 * succeed.
3674333b0a45SShantanu Goel 	 */
3675d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3676fd901c95SVlastimil Babka 		/*
3677fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3678fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3679fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3680fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3681fd901c95SVlastimil Babka 		 */
3682fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3683fd901c95SVlastimil Babka 
3684fd901c95SVlastimil Babka 		/*
3685fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3686fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3687fd901c95SVlastimil Babka 		 */
368838087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3689fd901c95SVlastimil Babka 
3690f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
369138087d9bSMel Gorman 
369238087d9bSMel Gorman 		/*
369338087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
369438087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
369538087d9bSMel Gorman 		 * the previous request that slept prematurely.
369638087d9bSMel Gorman 		 */
369738087d9bSMel Gorman 		if (remaining) {
3698e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
369938087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
370038087d9bSMel Gorman 		}
370138087d9bSMel Gorman 
3702f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3703f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3704f0bc0a60SKOSAKI Motohiro 	}
3705f0bc0a60SKOSAKI Motohiro 
3706f0bc0a60SKOSAKI Motohiro 	/*
3707f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3708f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3709f0bc0a60SKOSAKI Motohiro 	 */
3710d9f21d42SMel Gorman 	if (!remaining &&
3711d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3712f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3713f0bc0a60SKOSAKI Motohiro 
3714f0bc0a60SKOSAKI Motohiro 		/*
3715f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3716f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3717f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3718f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3719f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3720f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3721f0bc0a60SKOSAKI Motohiro 		 */
3722f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
37231c7e7f6cSAaditya Kumar 
37241c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3725f0bc0a60SKOSAKI Motohiro 			schedule();
37261c7e7f6cSAaditya Kumar 
3727f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3728f0bc0a60SKOSAKI Motohiro 	} else {
3729f0bc0a60SKOSAKI Motohiro 		if (remaining)
3730f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3731f0bc0a60SKOSAKI Motohiro 		else
3732f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3733f0bc0a60SKOSAKI Motohiro 	}
3734f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3735f0bc0a60SKOSAKI Motohiro }
3736f0bc0a60SKOSAKI Motohiro 
37371da177e4SLinus Torvalds /*
37381da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
37391da177e4SLinus Torvalds  * from the init process.
37401da177e4SLinus Torvalds  *
37411da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
37421da177e4SLinus Torvalds  * free memory available even if there is no other activity
37431da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
37441da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
37451da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
37461da177e4SLinus Torvalds  *
37471da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
37481da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
37491da177e4SLinus Torvalds  */
37501da177e4SLinus Torvalds static int kswapd(void *p)
37511da177e4SLinus Torvalds {
3752e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3753e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
37541da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
37551da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3756f0bc0a60SKOSAKI Motohiro 
37571da177e4SLinus Torvalds 	struct reclaim_state reclaim_state = {
37581da177e4SLinus Torvalds 		.reclaimed_slab = 0,
37591da177e4SLinus Torvalds 	};
3760a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
37611da177e4SLinus Torvalds 
3762174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3763c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
37641da177e4SLinus Torvalds 	current->reclaim_state = &reclaim_state;
37651da177e4SLinus Torvalds 
37661da177e4SLinus Torvalds 	/*
37671da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
37681da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
37691da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
37701da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
37711da177e4SLinus Torvalds 	 *
37721da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
37731da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
37741da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
37751da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
37761da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
37771da177e4SLinus Torvalds 	 */
3778930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
377983144186SRafael J. Wysocki 	set_freezable();
37801da177e4SLinus Torvalds 
3781e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3782e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
37831da177e4SLinus Torvalds 	for ( ; ; ) {
37846f6313d4SJeff Liu 		bool ret;
37853e1d1d28SChristoph Lameter 
3786e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3787e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3788e716f2ebSMel Gorman 
378938087d9bSMel Gorman kswapd_try_sleep:
379038087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
379138087d9bSMel Gorman 					classzone_idx);
3792215ddd66SMel Gorman 
379338087d9bSMel Gorman 		/* Read the new order and classzone_idx */
379438087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3795e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, 0);
379638087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3797e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
37981da177e4SLinus Torvalds 
37998fe23e05SDavid Rientjes 		ret = try_to_freeze();
38008fe23e05SDavid Rientjes 		if (kthread_should_stop())
38018fe23e05SDavid Rientjes 			break;
38028fe23e05SDavid Rientjes 
38038fe23e05SDavid Rientjes 		/*
38048fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
38058fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3806b1296cc4SRafael J. Wysocki 		 */
380738087d9bSMel Gorman 		if (ret)
380838087d9bSMel Gorman 			continue;
38091d82de61SMel Gorman 
381038087d9bSMel Gorman 		/*
381138087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
381238087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
381338087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
381438087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
381538087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
381638087d9bSMel Gorman 		 * request (alloc_order).
381738087d9bSMel Gorman 		 */
3818e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3819e5146b12SMel Gorman 						alloc_order);
382038087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
382138087d9bSMel Gorman 		if (reclaim_order < alloc_order)
382238087d9bSMel Gorman 			goto kswapd_try_sleep;
382333906bc5SMel Gorman 	}
3824b0a8cc58STakamori Yamaguchi 
382571abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3826b0a8cc58STakamori Yamaguchi 	current->reclaim_state = NULL;
382771abdc15SJohannes Weiner 
38281da177e4SLinus Torvalds 	return 0;
38291da177e4SLinus Torvalds }
38301da177e4SLinus Torvalds 
38311da177e4SLinus Torvalds /*
38325ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
38335ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
38345ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
38355ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
38365ecd9d40SDavid Rientjes  * needed.
38371da177e4SLinus Torvalds  */
38385ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
38395ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
38401da177e4SLinus Torvalds {
38411da177e4SLinus Torvalds 	pg_data_t *pgdat;
38421da177e4SLinus Torvalds 
38436aa303deSMel Gorman 	if (!managed_zone(zone))
38441da177e4SLinus Torvalds 		return;
38451da177e4SLinus Torvalds 
38465ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
38471da177e4SLinus Torvalds 		return;
384888f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3849e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat,
3850e716f2ebSMel Gorman 							   classzone_idx);
385138087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
38528d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
38531da177e4SLinus Torvalds 		return;
3854e1a55637SMel Gorman 
38555ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
38565ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
38575ecd9d40SDavid Rientjes 	    pgdat_balanced(pgdat, order, classzone_idx)) {
38585ecd9d40SDavid Rientjes 		/*
38595ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
38605ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
38615ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
38625ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
38635ecd9d40SDavid Rientjes 		 * ratelimit its work.
38645ecd9d40SDavid Rientjes 		 */
38655ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
38665ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3867c73322d0SJohannes Weiner 		return;
38685ecd9d40SDavid Rientjes 	}
3869c73322d0SJohannes Weiner 
38705ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
38715ecd9d40SDavid Rientjes 				      gfp_flags);
38728d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
38731da177e4SLinus Torvalds }
38741da177e4SLinus Torvalds 
3875c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
38761da177e4SLinus Torvalds /*
38777b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3878d6277db4SRafael J. Wysocki  * freed pages.
3879d6277db4SRafael J. Wysocki  *
3880d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
3881d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
3882d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
38831da177e4SLinus Torvalds  */
38847b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
38851da177e4SLinus Torvalds {
3886d6277db4SRafael J. Wysocki 	struct reclaim_state reclaim_state;
3887d6277db4SRafael J. Wysocki 	struct scan_control sc = {
38887b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
3889ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
3890b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
38919e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
3892ee814fe2SJohannes Weiner 		.may_writepage = 1,
3893ee814fe2SJohannes Weiner 		.may_unmap = 1,
3894ee814fe2SJohannes Weiner 		.may_swap = 1,
3895ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
38961da177e4SLinus Torvalds 	};
38977b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
38987b51755cSKOSAKI Motohiro 	struct task_struct *p = current;
38997b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3900499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
39011da177e4SLinus Torvalds 
3902d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
390393781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
3904d6277db4SRafael J. Wysocki 	reclaim_state.reclaimed_slab = 0;
39057b51755cSKOSAKI Motohiro 	p->reclaim_state = &reclaim_state;
3906d6277db4SRafael J. Wysocki 
39073115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3908d6277db4SRafael J. Wysocki 
39097b51755cSKOSAKI Motohiro 	p->reclaim_state = NULL;
3910499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
391193781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
3912d6277db4SRafael J. Wysocki 
39137b51755cSKOSAKI Motohiro 	return nr_reclaimed;
39141da177e4SLinus Torvalds }
3915c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
39161da177e4SLinus Torvalds 
39171da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
39181da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
39191da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
39201da177e4SLinus Torvalds    restore their cpu bindings. */
3921517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
39221da177e4SLinus Torvalds {
392358c0a4a7SYasunori Goto 	int nid;
39241da177e4SLinus Torvalds 
392548fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
3926c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
3927a70f7302SRusty Russell 		const struct cpumask *mask;
3928a70f7302SRusty Russell 
3929a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
3930c5f59f08SMike Travis 
39313e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
39321da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
3933c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
39341da177e4SLinus Torvalds 	}
3935517bbed9SSebastian Andrzej Siewior 	return 0;
39361da177e4SLinus Torvalds }
39371da177e4SLinus Torvalds 
39383218ae14SYasunori Goto /*
39393218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
39403218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
39413218ae14SYasunori Goto  */
39423218ae14SYasunori Goto int kswapd_run(int nid)
39433218ae14SYasunori Goto {
39443218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
39453218ae14SYasunori Goto 	int ret = 0;
39463218ae14SYasunori Goto 
39473218ae14SYasunori Goto 	if (pgdat->kswapd)
39483218ae14SYasunori Goto 		return 0;
39493218ae14SYasunori Goto 
39503218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
39513218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
39523218ae14SYasunori Goto 		/* failure at boot is fatal */
3953c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
3954d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
3955d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
3956d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
39573218ae14SYasunori Goto 	}
39583218ae14SYasunori Goto 	return ret;
39593218ae14SYasunori Goto }
39603218ae14SYasunori Goto 
39618fe23e05SDavid Rientjes /*
3962d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3963bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
39648fe23e05SDavid Rientjes  */
39658fe23e05SDavid Rientjes void kswapd_stop(int nid)
39668fe23e05SDavid Rientjes {
39678fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
39688fe23e05SDavid Rientjes 
3969d8adde17SJiang Liu 	if (kswapd) {
39708fe23e05SDavid Rientjes 		kthread_stop(kswapd);
3971d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
3972d8adde17SJiang Liu 	}
39738fe23e05SDavid Rientjes }
39748fe23e05SDavid Rientjes 
39751da177e4SLinus Torvalds static int __init kswapd_init(void)
39761da177e4SLinus Torvalds {
3977517bbed9SSebastian Andrzej Siewior 	int nid, ret;
397869e05944SAndrew Morton 
39791da177e4SLinus Torvalds 	swap_setup();
398048fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
39813218ae14SYasunori Goto  		kswapd_run(nid);
3982517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3983517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
3984517bbed9SSebastian Andrzej Siewior 					NULL);
3985517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
39861da177e4SLinus Torvalds 	return 0;
39871da177e4SLinus Torvalds }
39881da177e4SLinus Torvalds 
39891da177e4SLinus Torvalds module_init(kswapd_init)
39909eeff239SChristoph Lameter 
39919eeff239SChristoph Lameter #ifdef CONFIG_NUMA
39929eeff239SChristoph Lameter /*
3993a5f5f91dSMel Gorman  * Node reclaim mode
39949eeff239SChristoph Lameter  *
3995a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
39969eeff239SChristoph Lameter  * the watermarks.
39979eeff239SChristoph Lameter  */
3998a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
39999eeff239SChristoph Lameter 
40001b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
40017d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
40021b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
400395bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
40041b2ffb78SChristoph Lameter 
40059eeff239SChristoph Lameter /*
4006a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4007a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4008a92f7126SChristoph Lameter  * a zone.
4009a92f7126SChristoph Lameter  */
4010a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4011a92f7126SChristoph Lameter 
40129eeff239SChristoph Lameter /*
4013a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
40149614634fSChristoph Lameter  * occur.
40159614634fSChristoph Lameter  */
40169614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
40179614634fSChristoph Lameter 
40189614634fSChristoph Lameter /*
40190ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
40200ff38490SChristoph Lameter  * slab reclaim needs to occur.
40210ff38490SChristoph Lameter  */
40220ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
40230ff38490SChristoph Lameter 
402411fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
402590afa5deSMel Gorman {
402611fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
402711fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
402811fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
402990afa5deSMel Gorman 
403090afa5deSMel Gorman 	/*
403190afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
403290afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
403390afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
403490afa5deSMel Gorman 	 */
403590afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
403690afa5deSMel Gorman }
403790afa5deSMel Gorman 
403890afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4039a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
404090afa5deSMel Gorman {
4041d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4042d031a157SAlexandru Moise 	unsigned long delta = 0;
404390afa5deSMel Gorman 
404490afa5deSMel Gorman 	/*
404595bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
404690afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
404711fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
404890afa5deSMel Gorman 	 * a better estimate
404990afa5deSMel Gorman 	 */
4050a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4051a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
405290afa5deSMel Gorman 	else
4053a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
405490afa5deSMel Gorman 
405590afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4056a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4057a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
405890afa5deSMel Gorman 
405990afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
406090afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
406190afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
406290afa5deSMel Gorman 
406390afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
406490afa5deSMel Gorman }
406590afa5deSMel Gorman 
40660ff38490SChristoph Lameter /*
4067a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
40689eeff239SChristoph Lameter  */
4069a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
40709eeff239SChristoph Lameter {
40717fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
407269e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
40739eeff239SChristoph Lameter 	struct task_struct *p = current;
40749eeff239SChristoph Lameter 	struct reclaim_state reclaim_state;
4075499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4076179e9639SAndrew Morton 	struct scan_control sc = {
407762b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4078f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4079bd2f6199SJohannes Weiner 		.order = order,
4080a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4081a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4082a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4083ee814fe2SJohannes Weiner 		.may_swap = 1,
4084f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4085179e9639SAndrew Morton 	};
40869eeff239SChristoph Lameter 
40879eeff239SChristoph Lameter 	cond_resched();
408893781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4089d4f7796eSChristoph Lameter 	/*
409095bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4091d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
409295bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4093d4f7796eSChristoph Lameter 	 */
4094499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4095499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
40969eeff239SChristoph Lameter 	reclaim_state.reclaimed_slab = 0;
40979eeff239SChristoph Lameter 	p->reclaim_state = &reclaim_state;
4098c84db23cSChristoph Lameter 
4099a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4100a92f7126SChristoph Lameter 		/*
4101894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
41020ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4103a92f7126SChristoph Lameter 		 */
4104a92f7126SChristoph Lameter 		do {
4105970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
41069e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
41070ff38490SChristoph Lameter 	}
4108a92f7126SChristoph Lameter 
41099eeff239SChristoph Lameter 	p->reclaim_state = NULL;
4110499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4111499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
411293781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4113a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
41149eeff239SChristoph Lameter }
4115179e9639SAndrew Morton 
4116a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4117179e9639SAndrew Morton {
4118d773ed6bSDavid Rientjes 	int ret;
4119179e9639SAndrew Morton 
4120179e9639SAndrew Morton 	/*
4121a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
41220ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
412334aa1330SChristoph Lameter 	 *
41249614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
41259614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4126a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4127a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
41289614634fSChristoph Lameter 	 * unmapped file backed pages.
4129179e9639SAndrew Morton 	 */
4130a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4131385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4132a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4133179e9639SAndrew Morton 
4134179e9639SAndrew Morton 	/*
4135d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4136179e9639SAndrew Morton 	 */
4137d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4138a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4139179e9639SAndrew Morton 
4140179e9639SAndrew Morton 	/*
4141a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4142179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4143179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4144179e9639SAndrew Morton 	 * as wide as possible.
4145179e9639SAndrew Morton 	 */
4146a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4147a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4148d773ed6bSDavid Rientjes 
4149a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4150a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4151fa5e084eSMel Gorman 
4152a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4153a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4154d773ed6bSDavid Rientjes 
415524cf7251SMel Gorman 	if (!ret)
415624cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
415724cf7251SMel Gorman 
4158d773ed6bSDavid Rientjes 	return ret;
4159179e9639SAndrew Morton }
41609eeff239SChristoph Lameter #endif
4161894bc310SLee Schermerhorn 
4162894bc310SLee Schermerhorn /*
4163894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4164894bc310SLee Schermerhorn  * @page: the page to test
4165894bc310SLee Schermerhorn  *
4166894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
416739b5f29aSHugh Dickins  * lists vs unevictable list.
4168894bc310SLee Schermerhorn  *
4169894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4170ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4171b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4172ba9ddf49SLee Schermerhorn  *
4173894bc310SLee Schermerhorn  */
417439b5f29aSHugh Dickins int page_evictable(struct page *page)
4175894bc310SLee Schermerhorn {
4176e92bb4ddSHuang Ying 	int ret;
4177e92bb4ddSHuang Ying 
4178e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4179e92bb4ddSHuang Ying 	rcu_read_lock();
4180e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4181e92bb4ddSHuang Ying 	rcu_read_unlock();
4182e92bb4ddSHuang Ying 	return ret;
4183894bc310SLee Schermerhorn }
418489e004eaSLee Schermerhorn 
418585046579SHugh Dickins #ifdef CONFIG_SHMEM
418689e004eaSLee Schermerhorn /**
418724513264SHugh Dickins  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
418824513264SHugh Dickins  * @pages:	array of pages to check
418924513264SHugh Dickins  * @nr_pages:	number of pages to check
419089e004eaSLee Schermerhorn  *
419124513264SHugh Dickins  * Checks pages for evictability and moves them to the appropriate lru list.
419285046579SHugh Dickins  *
419385046579SHugh Dickins  * This function is only used for SysV IPC SHM_UNLOCK.
419489e004eaSLee Schermerhorn  */
419524513264SHugh Dickins void check_move_unevictable_pages(struct page **pages, int nr_pages)
419689e004eaSLee Schermerhorn {
4197925b7673SJohannes Weiner 	struct lruvec *lruvec;
4198785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
419924513264SHugh Dickins 	int pgscanned = 0;
420024513264SHugh Dickins 	int pgrescued = 0;
420189e004eaSLee Schermerhorn 	int i;
420289e004eaSLee Schermerhorn 
420324513264SHugh Dickins 	for (i = 0; i < nr_pages; i++) {
420424513264SHugh Dickins 		struct page *page = pages[i];
4205785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
420689e004eaSLee Schermerhorn 
420724513264SHugh Dickins 		pgscanned++;
4208785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4209785b99feSMel Gorman 			if (pgdat)
4210785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4211785b99feSMel Gorman 			pgdat = pagepgdat;
4212785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
421389e004eaSLee Schermerhorn 		}
4214785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
421589e004eaSLee Schermerhorn 
421624513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
421724513264SHugh Dickins 			continue;
421889e004eaSLee Schermerhorn 
421939b5f29aSHugh Dickins 		if (page_evictable(page)) {
422024513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
422124513264SHugh Dickins 
4222309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
422324513264SHugh Dickins 			ClearPageUnevictable(page);
4224fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4225fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
422624513264SHugh Dickins 			pgrescued++;
422789e004eaSLee Schermerhorn 		}
422889e004eaSLee Schermerhorn 	}
422924513264SHugh Dickins 
4230785b99feSMel Gorman 	if (pgdat) {
423124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
423224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4233785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
423424513264SHugh Dickins 	}
423585046579SHugh Dickins }
423685046579SHugh Dickins #endif /* CONFIG_SHMEM */
4237