xref: /openbmc/linux/mm/vmscan.c (revision 6c9e0907fc8bc978e97bb78bbbc6e9bc8fc51cb3)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/vmscan.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie.
81da177e4SLinus Torvalds  *  kswapd added: 7.1.96  sct
91da177e4SLinus Torvalds  *  Removed kswapd_ctl limits, and swap out as many pages as needed
101da177e4SLinus Torvalds  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
111da177e4SLinus Torvalds  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
121da177e4SLinus Torvalds  *  Multiqueue VM started 5.8.00, Rik van Riel.
131da177e4SLinus Torvalds  */
141da177e4SLinus Torvalds 
15b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16b1de0d13SMitchel Humpherys 
171da177e4SLinus Torvalds #include <linux/mm.h>
185b3cc15aSIngo Molnar #include <linux/sched/mm.h>
191da177e4SLinus Torvalds #include <linux/module.h>
205a0e3ad6STejun Heo #include <linux/gfp.h>
211da177e4SLinus Torvalds #include <linux/kernel_stat.h>
221da177e4SLinus Torvalds #include <linux/swap.h>
231da177e4SLinus Torvalds #include <linux/pagemap.h>
241da177e4SLinus Torvalds #include <linux/init.h>
251da177e4SLinus Torvalds #include <linux/highmem.h>
2670ddf637SAnton Vorontsov #include <linux/vmpressure.h>
27e129b5c2SAndrew Morton #include <linux/vmstat.h>
281da177e4SLinus Torvalds #include <linux/file.h>
291da177e4SLinus Torvalds #include <linux/writeback.h>
301da177e4SLinus Torvalds #include <linux/blkdev.h>
311da177e4SLinus Torvalds #include <linux/buffer_head.h>	/* for try_to_release_page(),
321da177e4SLinus Torvalds 					buffer_heads_over_limit */
331da177e4SLinus Torvalds #include <linux/mm_inline.h>
341da177e4SLinus Torvalds #include <linux/backing-dev.h>
351da177e4SLinus Torvalds #include <linux/rmap.h>
361da177e4SLinus Torvalds #include <linux/topology.h>
371da177e4SLinus Torvalds #include <linux/cpu.h>
381da177e4SLinus Torvalds #include <linux/cpuset.h>
393e7d3449SMel Gorman #include <linux/compaction.h>
401da177e4SLinus Torvalds #include <linux/notifier.h>
411da177e4SLinus Torvalds #include <linux/rwsem.h>
42248a0301SRafael J. Wysocki #include <linux/delay.h>
433218ae14SYasunori Goto #include <linux/kthread.h>
447dfb7103SNigel Cunningham #include <linux/freezer.h>
4566e1707bSBalbir Singh #include <linux/memcontrol.h>
46873b4771SKeika Kobayashi #include <linux/delayacct.h>
47af936a16SLee Schermerhorn #include <linux/sysctl.h>
48929bea7cSKOSAKI Motohiro #include <linux/oom.h>
4964e3d12fSKuo-Hsin Yang #include <linux/pagevec.h>
50268bb0ceSLinus Torvalds #include <linux/prefetch.h>
51b1de0d13SMitchel Humpherys #include <linux/printk.h>
52f9fe48beSRoss Zwisler #include <linux/dax.h>
53eb414681SJohannes Weiner #include <linux/psi.h>
541da177e4SLinus Torvalds 
551da177e4SLinus Torvalds #include <asm/tlbflush.h>
561da177e4SLinus Torvalds #include <asm/div64.h>
571da177e4SLinus Torvalds 
581da177e4SLinus Torvalds #include <linux/swapops.h>
59117aad1eSRafael Aquini #include <linux/balloon_compaction.h>
601da177e4SLinus Torvalds 
610f8053a5SNick Piggin #include "internal.h"
620f8053a5SNick Piggin 
6333906bc5SMel Gorman #define CREATE_TRACE_POINTS
6433906bc5SMel Gorman #include <trace/events/vmscan.h>
6533906bc5SMel Gorman 
661da177e4SLinus Torvalds struct scan_control {
6722fba335SKOSAKI Motohiro 	/* How many pages shrink_list() should reclaim */
6822fba335SKOSAKI Motohiro 	unsigned long nr_to_reclaim;
6922fba335SKOSAKI Motohiro 
70ee814fe2SJohannes Weiner 	/*
71ee814fe2SJohannes Weiner 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
72ee814fe2SJohannes Weiner 	 * are scanned.
73ee814fe2SJohannes Weiner 	 */
74ee814fe2SJohannes Weiner 	nodemask_t	*nodemask;
759e3b2f8cSKonstantin Khlebnikov 
765f53e762SKOSAKI Motohiro 	/*
77f16015fbSJohannes Weiner 	 * The memory cgroup that hit its limit and as a result is the
78f16015fbSJohannes Weiner 	 * primary target of this reclaim invocation.
79f16015fbSJohannes Weiner 	 */
80f16015fbSJohannes Weiner 	struct mem_cgroup *target_mem_cgroup;
8166e1707bSBalbir Singh 
82b91ac374SJohannes Weiner 	/* Can active pages be deactivated as part of reclaim? */
83b91ac374SJohannes Weiner #define DEACTIVATE_ANON 1
84b91ac374SJohannes Weiner #define DEACTIVATE_FILE 2
85b91ac374SJohannes Weiner 	unsigned int may_deactivate:2;
86b91ac374SJohannes Weiner 	unsigned int force_deactivate:1;
87b91ac374SJohannes Weiner 	unsigned int skipped_deactivate:1;
88b91ac374SJohannes Weiner 
891276ad68SJohannes Weiner 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
90ee814fe2SJohannes Weiner 	unsigned int may_writepage:1;
91ee814fe2SJohannes Weiner 
92ee814fe2SJohannes Weiner 	/* Can mapped pages be reclaimed? */
93ee814fe2SJohannes Weiner 	unsigned int may_unmap:1;
94ee814fe2SJohannes Weiner 
95ee814fe2SJohannes Weiner 	/* Can pages be swapped as part of reclaim? */
96ee814fe2SJohannes Weiner 	unsigned int may_swap:1;
97ee814fe2SJohannes Weiner 
98d6622f63SYisheng Xie 	/*
99d6622f63SYisheng Xie 	 * Cgroups are not reclaimed below their configured memory.low,
100d6622f63SYisheng Xie 	 * unless we threaten to OOM. If any cgroups are skipped due to
101d6622f63SYisheng Xie 	 * memory.low and nothing was reclaimed, go back for memory.low.
102d6622f63SYisheng Xie 	 */
103d6622f63SYisheng Xie 	unsigned int memcg_low_reclaim:1;
104d6622f63SYisheng Xie 	unsigned int memcg_low_skipped:1;
105241994edSJohannes Weiner 
106ee814fe2SJohannes Weiner 	unsigned int hibernation_mode:1;
107ee814fe2SJohannes Weiner 
108ee814fe2SJohannes Weiner 	/* One of the zones is ready for compaction */
109ee814fe2SJohannes Weiner 	unsigned int compaction_ready:1;
110ee814fe2SJohannes Weiner 
111b91ac374SJohannes Weiner 	/* There is easily reclaimable cold cache in the current node */
112b91ac374SJohannes Weiner 	unsigned int cache_trim_mode:1;
113b91ac374SJohannes Weiner 
11453138ceaSJohannes Weiner 	/* The file pages on the current node are dangerously low */
11553138ceaSJohannes Weiner 	unsigned int file_is_tiny:1;
11653138ceaSJohannes Weiner 
117bb451fdfSGreg Thelen 	/* Allocation order */
118bb451fdfSGreg Thelen 	s8 order;
119bb451fdfSGreg Thelen 
120bb451fdfSGreg Thelen 	/* Scan (total_size >> priority) pages at once */
121bb451fdfSGreg Thelen 	s8 priority;
122bb451fdfSGreg Thelen 
123bb451fdfSGreg Thelen 	/* The highest zone to isolate pages for reclaim from */
124bb451fdfSGreg Thelen 	s8 reclaim_idx;
125bb451fdfSGreg Thelen 
126bb451fdfSGreg Thelen 	/* This context's GFP mask */
127bb451fdfSGreg Thelen 	gfp_t gfp_mask;
128bb451fdfSGreg Thelen 
129ee814fe2SJohannes Weiner 	/* Incremented by the number of inactive pages that were scanned */
130ee814fe2SJohannes Weiner 	unsigned long nr_scanned;
131ee814fe2SJohannes Weiner 
132ee814fe2SJohannes Weiner 	/* Number of pages freed so far during a call to shrink_zones() */
133ee814fe2SJohannes Weiner 	unsigned long nr_reclaimed;
134d108c772SAndrey Ryabinin 
135d108c772SAndrey Ryabinin 	struct {
136d108c772SAndrey Ryabinin 		unsigned int dirty;
137d108c772SAndrey Ryabinin 		unsigned int unqueued_dirty;
138d108c772SAndrey Ryabinin 		unsigned int congested;
139d108c772SAndrey Ryabinin 		unsigned int writeback;
140d108c772SAndrey Ryabinin 		unsigned int immediate;
141d108c772SAndrey Ryabinin 		unsigned int file_taken;
142d108c772SAndrey Ryabinin 		unsigned int taken;
143d108c772SAndrey Ryabinin 	} nr;
144e5ca8071SYafang Shao 
145e5ca8071SYafang Shao 	/* for recording the reclaimed slab by now */
146e5ca8071SYafang Shao 	struct reclaim_state reclaim_state;
1471da177e4SLinus Torvalds };
1481da177e4SLinus Torvalds 
1491da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCH
1501da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field)			\
1511da177e4SLinus Torvalds 	do {								\
1521da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1531da177e4SLinus Torvalds 			struct page *prev;				\
1541da177e4SLinus Torvalds 									\
1551da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1561da177e4SLinus Torvalds 			prefetch(&prev->_field);			\
1571da177e4SLinus Torvalds 		}							\
1581da177e4SLinus Torvalds 	} while (0)
1591da177e4SLinus Torvalds #else
1601da177e4SLinus Torvalds #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
1611da177e4SLinus Torvalds #endif
1621da177e4SLinus Torvalds 
1631da177e4SLinus Torvalds #ifdef ARCH_HAS_PREFETCHW
1641da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field)			\
1651da177e4SLinus Torvalds 	do {								\
1661da177e4SLinus Torvalds 		if ((_page)->lru.prev != _base) {			\
1671da177e4SLinus Torvalds 			struct page *prev;				\
1681da177e4SLinus Torvalds 									\
1691da177e4SLinus Torvalds 			prev = lru_to_page(&(_page->lru));		\
1701da177e4SLinus Torvalds 			prefetchw(&prev->_field);			\
1711da177e4SLinus Torvalds 		}							\
1721da177e4SLinus Torvalds 	} while (0)
1731da177e4SLinus Torvalds #else
1741da177e4SLinus Torvalds #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
1751da177e4SLinus Torvalds #endif
1761da177e4SLinus Torvalds 
1771da177e4SLinus Torvalds /*
1781da177e4SLinus Torvalds  * From 0 .. 100.  Higher means more swappy.
1791da177e4SLinus Torvalds  */
1801da177e4SLinus Torvalds int vm_swappiness = 60;
181d0480be4SWang Sheng-Hui /*
182d0480be4SWang Sheng-Hui  * The total number of pages which are beyond the high watermark within all
183d0480be4SWang Sheng-Hui  * zones.
184d0480be4SWang Sheng-Hui  */
185d0480be4SWang Sheng-Hui unsigned long vm_total_pages;
1861da177e4SLinus Torvalds 
1870a432dcbSYang Shi static void set_task_reclaim_state(struct task_struct *task,
1880a432dcbSYang Shi 				   struct reclaim_state *rs)
1890a432dcbSYang Shi {
1900a432dcbSYang Shi 	/* Check for an overwrite */
1910a432dcbSYang Shi 	WARN_ON_ONCE(rs && task->reclaim_state);
1920a432dcbSYang Shi 
1930a432dcbSYang Shi 	/* Check for the nulling of an already-nulled member */
1940a432dcbSYang Shi 	WARN_ON_ONCE(!rs && !task->reclaim_state);
1950a432dcbSYang Shi 
1960a432dcbSYang Shi 	task->reclaim_state = rs;
1970a432dcbSYang Shi }
1980a432dcbSYang Shi 
1991da177e4SLinus Torvalds static LIST_HEAD(shrinker_list);
2001da177e4SLinus Torvalds static DECLARE_RWSEM(shrinker_rwsem);
2011da177e4SLinus Torvalds 
2020a432dcbSYang Shi #ifdef CONFIG_MEMCG
2037e010df5SKirill Tkhai /*
2047e010df5SKirill Tkhai  * We allow subsystems to populate their shrinker-related
2057e010df5SKirill Tkhai  * LRU lists before register_shrinker_prepared() is called
2067e010df5SKirill Tkhai  * for the shrinker, since we don't want to impose
2077e010df5SKirill Tkhai  * restrictions on their internal registration order.
2087e010df5SKirill Tkhai  * In this case shrink_slab_memcg() may find corresponding
2097e010df5SKirill Tkhai  * bit is set in the shrinkers map.
2107e010df5SKirill Tkhai  *
2117e010df5SKirill Tkhai  * This value is used by the function to detect registering
2127e010df5SKirill Tkhai  * shrinkers and to skip do_shrink_slab() calls for them.
2137e010df5SKirill Tkhai  */
2147e010df5SKirill Tkhai #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
2157e010df5SKirill Tkhai 
216b4c2b231SKirill Tkhai static DEFINE_IDR(shrinker_idr);
217b4c2b231SKirill Tkhai static int shrinker_nr_max;
218b4c2b231SKirill Tkhai 
219b4c2b231SKirill Tkhai static int prealloc_memcg_shrinker(struct shrinker *shrinker)
220b4c2b231SKirill Tkhai {
221b4c2b231SKirill Tkhai 	int id, ret = -ENOMEM;
222b4c2b231SKirill Tkhai 
223b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
224b4c2b231SKirill Tkhai 	/* This may call shrinker, so it must use down_read_trylock() */
2257e010df5SKirill Tkhai 	id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
226b4c2b231SKirill Tkhai 	if (id < 0)
227b4c2b231SKirill Tkhai 		goto unlock;
228b4c2b231SKirill Tkhai 
2290a4465d3SKirill Tkhai 	if (id >= shrinker_nr_max) {
2300a4465d3SKirill Tkhai 		if (memcg_expand_shrinker_maps(id)) {
2310a4465d3SKirill Tkhai 			idr_remove(&shrinker_idr, id);
2320a4465d3SKirill Tkhai 			goto unlock;
2330a4465d3SKirill Tkhai 		}
2340a4465d3SKirill Tkhai 
235b4c2b231SKirill Tkhai 		shrinker_nr_max = id + 1;
2360a4465d3SKirill Tkhai 	}
237b4c2b231SKirill Tkhai 	shrinker->id = id;
238b4c2b231SKirill Tkhai 	ret = 0;
239b4c2b231SKirill Tkhai unlock:
240b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
241b4c2b231SKirill Tkhai 	return ret;
242b4c2b231SKirill Tkhai }
243b4c2b231SKirill Tkhai 
244b4c2b231SKirill Tkhai static void unregister_memcg_shrinker(struct shrinker *shrinker)
245b4c2b231SKirill Tkhai {
246b4c2b231SKirill Tkhai 	int id = shrinker->id;
247b4c2b231SKirill Tkhai 
248b4c2b231SKirill Tkhai 	BUG_ON(id < 0);
249b4c2b231SKirill Tkhai 
250b4c2b231SKirill Tkhai 	down_write(&shrinker_rwsem);
251b4c2b231SKirill Tkhai 	idr_remove(&shrinker_idr, id);
252b4c2b231SKirill Tkhai 	up_write(&shrinker_rwsem);
253b4c2b231SKirill Tkhai }
254b4c2b231SKirill Tkhai 
255b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
25689b5fae5SJohannes Weiner {
257b5ead35eSJohannes Weiner 	return sc->target_mem_cgroup;
25889b5fae5SJohannes Weiner }
25997c9341fSTejun Heo 
26097c9341fSTejun Heo /**
261b5ead35eSJohannes Weiner  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
26297c9341fSTejun Heo  * @sc: scan_control in question
26397c9341fSTejun Heo  *
26497c9341fSTejun Heo  * The normal page dirty throttling mechanism in balance_dirty_pages() is
26597c9341fSTejun Heo  * completely broken with the legacy memcg and direct stalling in
26697c9341fSTejun Heo  * shrink_page_list() is used for throttling instead, which lacks all the
26797c9341fSTejun Heo  * niceties such as fairness, adaptive pausing, bandwidth proportional
26897c9341fSTejun Heo  * allocation and configurability.
26997c9341fSTejun Heo  *
27097c9341fSTejun Heo  * This function tests whether the vmscan currently in progress can assume
27197c9341fSTejun Heo  * that the normal dirty throttling mechanism is operational.
27297c9341fSTejun Heo  */
273b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
27497c9341fSTejun Heo {
275b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
27697c9341fSTejun Heo 		return true;
27797c9341fSTejun Heo #ifdef CONFIG_CGROUP_WRITEBACK
27869234aceSLinus Torvalds 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
27997c9341fSTejun Heo 		return true;
28097c9341fSTejun Heo #endif
28197c9341fSTejun Heo 	return false;
28297c9341fSTejun Heo }
28391a45470SKAMEZAWA Hiroyuki #else
2840a432dcbSYang Shi static int prealloc_memcg_shrinker(struct shrinker *shrinker)
2850a432dcbSYang Shi {
2860a432dcbSYang Shi 	return 0;
2870a432dcbSYang Shi }
2880a432dcbSYang Shi 
2890a432dcbSYang Shi static void unregister_memcg_shrinker(struct shrinker *shrinker)
2900a432dcbSYang Shi {
2910a432dcbSYang Shi }
2920a432dcbSYang Shi 
293b5ead35eSJohannes Weiner static bool cgroup_reclaim(struct scan_control *sc)
29489b5fae5SJohannes Weiner {
295b5ead35eSJohannes Weiner 	return false;
29689b5fae5SJohannes Weiner }
29797c9341fSTejun Heo 
298b5ead35eSJohannes Weiner static bool writeback_throttling_sane(struct scan_control *sc)
29997c9341fSTejun Heo {
30097c9341fSTejun Heo 	return true;
30197c9341fSTejun Heo }
30291a45470SKAMEZAWA Hiroyuki #endif
30391a45470SKAMEZAWA Hiroyuki 
3045a1c84b4SMel Gorman /*
3055a1c84b4SMel Gorman  * This misses isolated pages which are not accounted for to save counters.
3065a1c84b4SMel Gorman  * As the data only determines if reclaim or compaction continues, it is
3075a1c84b4SMel Gorman  * not expected that isolated pages will be a dominating factor.
3085a1c84b4SMel Gorman  */
3095a1c84b4SMel Gorman unsigned long zone_reclaimable_pages(struct zone *zone)
3105a1c84b4SMel Gorman {
3115a1c84b4SMel Gorman 	unsigned long nr;
3125a1c84b4SMel Gorman 
3135a1c84b4SMel Gorman 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
3145a1c84b4SMel Gorman 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
3155a1c84b4SMel Gorman 	if (get_nr_swap_pages() > 0)
3165a1c84b4SMel Gorman 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
3175a1c84b4SMel Gorman 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
3185a1c84b4SMel Gorman 
3195a1c84b4SMel Gorman 	return nr;
3205a1c84b4SMel Gorman }
3215a1c84b4SMel Gorman 
322fd538803SMichal Hocko /**
323fd538803SMichal Hocko  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
324fd538803SMichal Hocko  * @lruvec: lru vector
325fd538803SMichal Hocko  * @lru: lru to use
326fd538803SMichal Hocko  * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
327fd538803SMichal Hocko  */
328fd538803SMichal Hocko unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
329c9f299d9SKOSAKI Motohiro {
330de3b0150SJohannes Weiner 	unsigned long size = 0;
331fd538803SMichal Hocko 	int zid;
332a3d8e054SKOSAKI Motohiro 
333de3b0150SJohannes Weiner 	for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
334fd538803SMichal Hocko 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
335fd538803SMichal Hocko 
336fd538803SMichal Hocko 		if (!managed_zone(zone))
337fd538803SMichal Hocko 			continue;
338fd538803SMichal Hocko 
339fd538803SMichal Hocko 		if (!mem_cgroup_disabled())
340de3b0150SJohannes Weiner 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
341fd538803SMichal Hocko 		else
342de3b0150SJohannes Weiner 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
343c9f299d9SKOSAKI Motohiro 	}
344de3b0150SJohannes Weiner 	return size;
345b4536f0cSMichal Hocko }
346b4536f0cSMichal Hocko 
3471da177e4SLinus Torvalds /*
3481d3d4437SGlauber Costa  * Add a shrinker callback to be called from the vm.
3491da177e4SLinus Torvalds  */
3508e04944fSTetsuo Handa int prealloc_shrinker(struct shrinker *shrinker)
3511da177e4SLinus Torvalds {
352b9726c26SAlexey Dobriyan 	unsigned int size = sizeof(*shrinker->nr_deferred);
3531d3d4437SGlauber Costa 
3541d3d4437SGlauber Costa 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
3551d3d4437SGlauber Costa 		size *= nr_node_ids;
3561d3d4437SGlauber Costa 
3571d3d4437SGlauber Costa 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
3581d3d4437SGlauber Costa 	if (!shrinker->nr_deferred)
3591d3d4437SGlauber Costa 		return -ENOMEM;
360b4c2b231SKirill Tkhai 
361b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
362b4c2b231SKirill Tkhai 		if (prealloc_memcg_shrinker(shrinker))
363b4c2b231SKirill Tkhai 			goto free_deferred;
364b4c2b231SKirill Tkhai 	}
365b4c2b231SKirill Tkhai 
3668e04944fSTetsuo Handa 	return 0;
367b4c2b231SKirill Tkhai 
368b4c2b231SKirill Tkhai free_deferred:
369b4c2b231SKirill Tkhai 	kfree(shrinker->nr_deferred);
370b4c2b231SKirill Tkhai 	shrinker->nr_deferred = NULL;
371b4c2b231SKirill Tkhai 	return -ENOMEM;
3728e04944fSTetsuo Handa }
3731d3d4437SGlauber Costa 
3748e04944fSTetsuo Handa void free_prealloced_shrinker(struct shrinker *shrinker)
3758e04944fSTetsuo Handa {
376b4c2b231SKirill Tkhai 	if (!shrinker->nr_deferred)
377b4c2b231SKirill Tkhai 		return;
378b4c2b231SKirill Tkhai 
379b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
380b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
381b4c2b231SKirill Tkhai 
3828e04944fSTetsuo Handa 	kfree(shrinker->nr_deferred);
3838e04944fSTetsuo Handa 	shrinker->nr_deferred = NULL;
3848e04944fSTetsuo Handa }
3858e04944fSTetsuo Handa 
3868e04944fSTetsuo Handa void register_shrinker_prepared(struct shrinker *shrinker)
3878e04944fSTetsuo Handa {
3881da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
3891da177e4SLinus Torvalds 	list_add_tail(&shrinker->list, &shrinker_list);
39042a9a53bSYang Shi #ifdef CONFIG_MEMCG
3918df4a44cSKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
3927e010df5SKirill Tkhai 		idr_replace(&shrinker_idr, shrinker, shrinker->id);
3937e010df5SKirill Tkhai #endif
3941da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
3958e04944fSTetsuo Handa }
3968e04944fSTetsuo Handa 
3978e04944fSTetsuo Handa int register_shrinker(struct shrinker *shrinker)
3988e04944fSTetsuo Handa {
3998e04944fSTetsuo Handa 	int err = prealloc_shrinker(shrinker);
4008e04944fSTetsuo Handa 
4018e04944fSTetsuo Handa 	if (err)
4028e04944fSTetsuo Handa 		return err;
4038e04944fSTetsuo Handa 	register_shrinker_prepared(shrinker);
4041d3d4437SGlauber Costa 	return 0;
4051da177e4SLinus Torvalds }
4068e1f936bSRusty Russell EXPORT_SYMBOL(register_shrinker);
4071da177e4SLinus Torvalds 
4081da177e4SLinus Torvalds /*
4091da177e4SLinus Torvalds  * Remove one
4101da177e4SLinus Torvalds  */
4118e1f936bSRusty Russell void unregister_shrinker(struct shrinker *shrinker)
4121da177e4SLinus Torvalds {
413bb422a73STetsuo Handa 	if (!shrinker->nr_deferred)
414bb422a73STetsuo Handa 		return;
415b4c2b231SKirill Tkhai 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
416b4c2b231SKirill Tkhai 		unregister_memcg_shrinker(shrinker);
4171da177e4SLinus Torvalds 	down_write(&shrinker_rwsem);
4181da177e4SLinus Torvalds 	list_del(&shrinker->list);
4191da177e4SLinus Torvalds 	up_write(&shrinker_rwsem);
420ae393321SAndrew Vagin 	kfree(shrinker->nr_deferred);
421bb422a73STetsuo Handa 	shrinker->nr_deferred = NULL;
4221da177e4SLinus Torvalds }
4238e1f936bSRusty Russell EXPORT_SYMBOL(unregister_shrinker);
4241da177e4SLinus Torvalds 
4251da177e4SLinus Torvalds #define SHRINK_BATCH 128
4261d3d4437SGlauber Costa 
427cb731d6cSVladimir Davydov static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
4289092c71bSJosef Bacik 				    struct shrinker *shrinker, int priority)
4291da177e4SLinus Torvalds {
43024f7c6b9SDave Chinner 	unsigned long freed = 0;
4311da177e4SLinus Torvalds 	unsigned long long delta;
432635697c6SKonstantin Khlebnikov 	long total_scan;
433d5bc5fd3SVladimir Davydov 	long freeable;
434acf92b48SDave Chinner 	long nr;
435acf92b48SDave Chinner 	long new_nr;
4361d3d4437SGlauber Costa 	int nid = shrinkctl->nid;
437e9299f50SDave Chinner 	long batch_size = shrinker->batch ? shrinker->batch
438e9299f50SDave Chinner 					  : SHRINK_BATCH;
4395f33a080SShaohua Li 	long scanned = 0, next_deferred;
4401da177e4SLinus Torvalds 
441ac7fb3adSKirill Tkhai 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
442ac7fb3adSKirill Tkhai 		nid = 0;
443ac7fb3adSKirill Tkhai 
444d5bc5fd3SVladimir Davydov 	freeable = shrinker->count_objects(shrinker, shrinkctl);
4459b996468SKirill Tkhai 	if (freeable == 0 || freeable == SHRINK_EMPTY)
4469b996468SKirill Tkhai 		return freeable;
447635697c6SKonstantin Khlebnikov 
448acf92b48SDave Chinner 	/*
449acf92b48SDave Chinner 	 * copy the current shrinker scan count into a local variable
450acf92b48SDave Chinner 	 * and zero it so that other concurrent shrinker invocations
451acf92b48SDave Chinner 	 * don't also do this scanning work.
452acf92b48SDave Chinner 	 */
4531d3d4437SGlauber Costa 	nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
454acf92b48SDave Chinner 
455acf92b48SDave Chinner 	total_scan = nr;
4564b85afbdSJohannes Weiner 	if (shrinker->seeks) {
4579092c71bSJosef Bacik 		delta = freeable >> priority;
4589092c71bSJosef Bacik 		delta *= 4;
4599092c71bSJosef Bacik 		do_div(delta, shrinker->seeks);
4604b85afbdSJohannes Weiner 	} else {
4614b85afbdSJohannes Weiner 		/*
4624b85afbdSJohannes Weiner 		 * These objects don't require any IO to create. Trim
4634b85afbdSJohannes Weiner 		 * them aggressively under memory pressure to keep
4644b85afbdSJohannes Weiner 		 * them from causing refetches in the IO caches.
4654b85afbdSJohannes Weiner 		 */
4664b85afbdSJohannes Weiner 		delta = freeable / 2;
4674b85afbdSJohannes Weiner 	}
468172b06c3SRoman Gushchin 
469acf92b48SDave Chinner 	total_scan += delta;
470acf92b48SDave Chinner 	if (total_scan < 0) {
471d75f773cSSakari Ailus 		pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
472a0b02131SDave Chinner 		       shrinker->scan_objects, total_scan);
473d5bc5fd3SVladimir Davydov 		total_scan = freeable;
4745f33a080SShaohua Li 		next_deferred = nr;
4755f33a080SShaohua Li 	} else
4765f33a080SShaohua Li 		next_deferred = total_scan;
477ea164d73SAndrea Arcangeli 
478ea164d73SAndrea Arcangeli 	/*
4793567b59aSDave Chinner 	 * We need to avoid excessive windup on filesystem shrinkers
4803567b59aSDave Chinner 	 * due to large numbers of GFP_NOFS allocations causing the
4813567b59aSDave Chinner 	 * shrinkers to return -1 all the time. This results in a large
4823567b59aSDave Chinner 	 * nr being built up so when a shrink that can do some work
4833567b59aSDave Chinner 	 * comes along it empties the entire cache due to nr >>>
484d5bc5fd3SVladimir Davydov 	 * freeable. This is bad for sustaining a working set in
4853567b59aSDave Chinner 	 * memory.
4863567b59aSDave Chinner 	 *
4873567b59aSDave Chinner 	 * Hence only allow the shrinker to scan the entire cache when
4883567b59aSDave Chinner 	 * a large delta change is calculated directly.
4893567b59aSDave Chinner 	 */
490d5bc5fd3SVladimir Davydov 	if (delta < freeable / 4)
491d5bc5fd3SVladimir Davydov 		total_scan = min(total_scan, freeable / 2);
4923567b59aSDave Chinner 
4933567b59aSDave Chinner 	/*
494ea164d73SAndrea Arcangeli 	 * Avoid risking looping forever due to too large nr value:
495ea164d73SAndrea Arcangeli 	 * never try to free more than twice the estimate number of
496ea164d73SAndrea Arcangeli 	 * freeable entries.
497ea164d73SAndrea Arcangeli 	 */
498d5bc5fd3SVladimir Davydov 	if (total_scan > freeable * 2)
499d5bc5fd3SVladimir Davydov 		total_scan = freeable * 2;
5001da177e4SLinus Torvalds 
50124f7c6b9SDave Chinner 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
5029092c71bSJosef Bacik 				   freeable, delta, total_scan, priority);
50309576073SDave Chinner 
5040b1fb40aSVladimir Davydov 	/*
5050b1fb40aSVladimir Davydov 	 * Normally, we should not scan less than batch_size objects in one
5060b1fb40aSVladimir Davydov 	 * pass to avoid too frequent shrinker calls, but if the slab has less
5070b1fb40aSVladimir Davydov 	 * than batch_size objects in total and we are really tight on memory,
5080b1fb40aSVladimir Davydov 	 * we will try to reclaim all available objects, otherwise we can end
5090b1fb40aSVladimir Davydov 	 * up failing allocations although there are plenty of reclaimable
5100b1fb40aSVladimir Davydov 	 * objects spread over several slabs with usage less than the
5110b1fb40aSVladimir Davydov 	 * batch_size.
5120b1fb40aSVladimir Davydov 	 *
5130b1fb40aSVladimir Davydov 	 * We detect the "tight on memory" situations by looking at the total
5140b1fb40aSVladimir Davydov 	 * number of objects we want to scan (total_scan). If it is greater
515d5bc5fd3SVladimir Davydov 	 * than the total number of objects on slab (freeable), we must be
5160b1fb40aSVladimir Davydov 	 * scanning at high prio and therefore should try to reclaim as much as
5170b1fb40aSVladimir Davydov 	 * possible.
5180b1fb40aSVladimir Davydov 	 */
5190b1fb40aSVladimir Davydov 	while (total_scan >= batch_size ||
520d5bc5fd3SVladimir Davydov 	       total_scan >= freeable) {
52124f7c6b9SDave Chinner 		unsigned long ret;
5220b1fb40aSVladimir Davydov 		unsigned long nr_to_scan = min(batch_size, total_scan);
5231da177e4SLinus Torvalds 
5240b1fb40aSVladimir Davydov 		shrinkctl->nr_to_scan = nr_to_scan;
525d460acb5SChris Wilson 		shrinkctl->nr_scanned = nr_to_scan;
52624f7c6b9SDave Chinner 		ret = shrinker->scan_objects(shrinker, shrinkctl);
52724f7c6b9SDave Chinner 		if (ret == SHRINK_STOP)
5281da177e4SLinus Torvalds 			break;
52924f7c6b9SDave Chinner 		freed += ret;
53024f7c6b9SDave Chinner 
531d460acb5SChris Wilson 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
532d460acb5SChris Wilson 		total_scan -= shrinkctl->nr_scanned;
533d460acb5SChris Wilson 		scanned += shrinkctl->nr_scanned;
5341da177e4SLinus Torvalds 
5351da177e4SLinus Torvalds 		cond_resched();
5361da177e4SLinus Torvalds 	}
5371da177e4SLinus Torvalds 
5385f33a080SShaohua Li 	if (next_deferred >= scanned)
5395f33a080SShaohua Li 		next_deferred -= scanned;
5405f33a080SShaohua Li 	else
5415f33a080SShaohua Li 		next_deferred = 0;
542acf92b48SDave Chinner 	/*
543acf92b48SDave Chinner 	 * move the unused scan count back into the shrinker in a
544acf92b48SDave Chinner 	 * manner that handles concurrent updates. If we exhausted the
545acf92b48SDave Chinner 	 * scan, there is no need to do an update.
546acf92b48SDave Chinner 	 */
5475f33a080SShaohua Li 	if (next_deferred > 0)
5485f33a080SShaohua Li 		new_nr = atomic_long_add_return(next_deferred,
5491d3d4437SGlauber Costa 						&shrinker->nr_deferred[nid]);
55083aeeadaSKonstantin Khlebnikov 	else
5511d3d4437SGlauber Costa 		new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
552acf92b48SDave Chinner 
553df9024a8SDave Hansen 	trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
5541d3d4437SGlauber Costa 	return freed;
5551d3d4437SGlauber Costa }
5561d3d4437SGlauber Costa 
5570a432dcbSYang Shi #ifdef CONFIG_MEMCG
558b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
559b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
560b0dedc49SKirill Tkhai {
561b0dedc49SKirill Tkhai 	struct memcg_shrinker_map *map;
562b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
563b8e57efaSKirill Tkhai 	int i;
564b0dedc49SKirill Tkhai 
5650a432dcbSYang Shi 	if (!mem_cgroup_online(memcg))
566b0dedc49SKirill Tkhai 		return 0;
567b0dedc49SKirill Tkhai 
568b0dedc49SKirill Tkhai 	if (!down_read_trylock(&shrinker_rwsem))
569b0dedc49SKirill Tkhai 		return 0;
570b0dedc49SKirill Tkhai 
571b0dedc49SKirill Tkhai 	map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
572b0dedc49SKirill Tkhai 					true);
573b0dedc49SKirill Tkhai 	if (unlikely(!map))
574b0dedc49SKirill Tkhai 		goto unlock;
575b0dedc49SKirill Tkhai 
576b0dedc49SKirill Tkhai 	for_each_set_bit(i, map->map, shrinker_nr_max) {
577b0dedc49SKirill Tkhai 		struct shrink_control sc = {
578b0dedc49SKirill Tkhai 			.gfp_mask = gfp_mask,
579b0dedc49SKirill Tkhai 			.nid = nid,
580b0dedc49SKirill Tkhai 			.memcg = memcg,
581b0dedc49SKirill Tkhai 		};
582b0dedc49SKirill Tkhai 		struct shrinker *shrinker;
583b0dedc49SKirill Tkhai 
584b0dedc49SKirill Tkhai 		shrinker = idr_find(&shrinker_idr, i);
5857e010df5SKirill Tkhai 		if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
5867e010df5SKirill Tkhai 			if (!shrinker)
587b0dedc49SKirill Tkhai 				clear_bit(i, map->map);
588b0dedc49SKirill Tkhai 			continue;
589b0dedc49SKirill Tkhai 		}
590b0dedc49SKirill Tkhai 
5910a432dcbSYang Shi 		/* Call non-slab shrinkers even though kmem is disabled */
5920a432dcbSYang Shi 		if (!memcg_kmem_enabled() &&
5930a432dcbSYang Shi 		    !(shrinker->flags & SHRINKER_NONSLAB))
5940a432dcbSYang Shi 			continue;
5950a432dcbSYang Shi 
596b0dedc49SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
597f90280d6SKirill Tkhai 		if (ret == SHRINK_EMPTY) {
598f90280d6SKirill Tkhai 			clear_bit(i, map->map);
599f90280d6SKirill Tkhai 			/*
600f90280d6SKirill Tkhai 			 * After the shrinker reported that it had no objects to
601f90280d6SKirill Tkhai 			 * free, but before we cleared the corresponding bit in
602f90280d6SKirill Tkhai 			 * the memcg shrinker map, a new object might have been
603f90280d6SKirill Tkhai 			 * added. To make sure, we have the bit set in this
604f90280d6SKirill Tkhai 			 * case, we invoke the shrinker one more time and reset
605f90280d6SKirill Tkhai 			 * the bit if it reports that it is not empty anymore.
606f90280d6SKirill Tkhai 			 * The memory barrier here pairs with the barrier in
607f90280d6SKirill Tkhai 			 * memcg_set_shrinker_bit():
608f90280d6SKirill Tkhai 			 *
609f90280d6SKirill Tkhai 			 * list_lru_add()     shrink_slab_memcg()
610f90280d6SKirill Tkhai 			 *   list_add_tail()    clear_bit()
611f90280d6SKirill Tkhai 			 *   <MB>               <MB>
612f90280d6SKirill Tkhai 			 *   set_bit()          do_shrink_slab()
613f90280d6SKirill Tkhai 			 */
614f90280d6SKirill Tkhai 			smp_mb__after_atomic();
615f90280d6SKirill Tkhai 			ret = do_shrink_slab(&sc, shrinker, priority);
6169b996468SKirill Tkhai 			if (ret == SHRINK_EMPTY)
6179b996468SKirill Tkhai 				ret = 0;
618f90280d6SKirill Tkhai 			else
619f90280d6SKirill Tkhai 				memcg_set_shrinker_bit(memcg, nid, i);
620f90280d6SKirill Tkhai 		}
621b0dedc49SKirill Tkhai 		freed += ret;
622b0dedc49SKirill Tkhai 
623b0dedc49SKirill Tkhai 		if (rwsem_is_contended(&shrinker_rwsem)) {
624b0dedc49SKirill Tkhai 			freed = freed ? : 1;
625b0dedc49SKirill Tkhai 			break;
626b0dedc49SKirill Tkhai 		}
627b0dedc49SKirill Tkhai 	}
628b0dedc49SKirill Tkhai unlock:
629b0dedc49SKirill Tkhai 	up_read(&shrinker_rwsem);
630b0dedc49SKirill Tkhai 	return freed;
631b0dedc49SKirill Tkhai }
6320a432dcbSYang Shi #else /* CONFIG_MEMCG */
633b0dedc49SKirill Tkhai static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
634b0dedc49SKirill Tkhai 			struct mem_cgroup *memcg, int priority)
635b0dedc49SKirill Tkhai {
636b0dedc49SKirill Tkhai 	return 0;
637b0dedc49SKirill Tkhai }
6380a432dcbSYang Shi #endif /* CONFIG_MEMCG */
639b0dedc49SKirill Tkhai 
6406b4f7799SJohannes Weiner /**
641cb731d6cSVladimir Davydov  * shrink_slab - shrink slab caches
6426b4f7799SJohannes Weiner  * @gfp_mask: allocation context
6436b4f7799SJohannes Weiner  * @nid: node whose slab caches to target
644cb731d6cSVladimir Davydov  * @memcg: memory cgroup whose slab caches to target
6459092c71bSJosef Bacik  * @priority: the reclaim priority
6461d3d4437SGlauber Costa  *
6476b4f7799SJohannes Weiner  * Call the shrink functions to age shrinkable caches.
6481d3d4437SGlauber Costa  *
6496b4f7799SJohannes Weiner  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
6506b4f7799SJohannes Weiner  * unaware shrinkers will receive a node id of 0 instead.
6511d3d4437SGlauber Costa  *
652aeed1d32SVladimir Davydov  * @memcg specifies the memory cgroup to target. Unaware shrinkers
653aeed1d32SVladimir Davydov  * are called only if it is the root cgroup.
654cb731d6cSVladimir Davydov  *
6559092c71bSJosef Bacik  * @priority is sc->priority, we take the number of objects and >> by priority
6569092c71bSJosef Bacik  * in order to get the scan target.
6571d3d4437SGlauber Costa  *
6586b4f7799SJohannes Weiner  * Returns the number of reclaimed slab objects.
6591d3d4437SGlauber Costa  */
660cb731d6cSVladimir Davydov static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
661cb731d6cSVladimir Davydov 				 struct mem_cgroup *memcg,
6629092c71bSJosef Bacik 				 int priority)
6631d3d4437SGlauber Costa {
664b8e57efaSKirill Tkhai 	unsigned long ret, freed = 0;
6651d3d4437SGlauber Costa 	struct shrinker *shrinker;
6661d3d4437SGlauber Costa 
667fa1e512fSYang Shi 	/*
668fa1e512fSYang Shi 	 * The root memcg might be allocated even though memcg is disabled
669fa1e512fSYang Shi 	 * via "cgroup_disable=memory" boot parameter.  This could make
670fa1e512fSYang Shi 	 * mem_cgroup_is_root() return false, then just run memcg slab
671fa1e512fSYang Shi 	 * shrink, but skip global shrink.  This may result in premature
672fa1e512fSYang Shi 	 * oom.
673fa1e512fSYang Shi 	 */
674fa1e512fSYang Shi 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
675b0dedc49SKirill Tkhai 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
676cb731d6cSVladimir Davydov 
677e830c63aSTetsuo Handa 	if (!down_read_trylock(&shrinker_rwsem))
6781d3d4437SGlauber Costa 		goto out;
6791d3d4437SGlauber Costa 
6801d3d4437SGlauber Costa 	list_for_each_entry(shrinker, &shrinker_list, list) {
6816b4f7799SJohannes Weiner 		struct shrink_control sc = {
6826b4f7799SJohannes Weiner 			.gfp_mask = gfp_mask,
6836b4f7799SJohannes Weiner 			.nid = nid,
684cb731d6cSVladimir Davydov 			.memcg = memcg,
6856b4f7799SJohannes Weiner 		};
6866b4f7799SJohannes Weiner 
6879b996468SKirill Tkhai 		ret = do_shrink_slab(&sc, shrinker, priority);
6889b996468SKirill Tkhai 		if (ret == SHRINK_EMPTY)
6899b996468SKirill Tkhai 			ret = 0;
6909b996468SKirill Tkhai 		freed += ret;
691e496612cSMinchan Kim 		/*
692e496612cSMinchan Kim 		 * Bail out if someone want to register a new shrinker to
693e496612cSMinchan Kim 		 * prevent the regsitration from being stalled for long periods
694e496612cSMinchan Kim 		 * by parallel ongoing shrinking.
695e496612cSMinchan Kim 		 */
696e496612cSMinchan Kim 		if (rwsem_is_contended(&shrinker_rwsem)) {
697e496612cSMinchan Kim 			freed = freed ? : 1;
698e496612cSMinchan Kim 			break;
699e496612cSMinchan Kim 		}
700ec97097bSVladimir Davydov 	}
7011d3d4437SGlauber Costa 
7021da177e4SLinus Torvalds 	up_read(&shrinker_rwsem);
703f06590bdSMinchan Kim out:
704f06590bdSMinchan Kim 	cond_resched();
70524f7c6b9SDave Chinner 	return freed;
7061da177e4SLinus Torvalds }
7071da177e4SLinus Torvalds 
708cb731d6cSVladimir Davydov void drop_slab_node(int nid)
709cb731d6cSVladimir Davydov {
710cb731d6cSVladimir Davydov 	unsigned long freed;
711cb731d6cSVladimir Davydov 
712cb731d6cSVladimir Davydov 	do {
713cb731d6cSVladimir Davydov 		struct mem_cgroup *memcg = NULL;
714cb731d6cSVladimir Davydov 
715cb731d6cSVladimir Davydov 		freed = 0;
716aeed1d32SVladimir Davydov 		memcg = mem_cgroup_iter(NULL, NULL, NULL);
717cb731d6cSVladimir Davydov 		do {
7189092c71bSJosef Bacik 			freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
719cb731d6cSVladimir Davydov 		} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
720cb731d6cSVladimir Davydov 	} while (freed > 10);
721cb731d6cSVladimir Davydov }
722cb731d6cSVladimir Davydov 
723cb731d6cSVladimir Davydov void drop_slab(void)
724cb731d6cSVladimir Davydov {
725cb731d6cSVladimir Davydov 	int nid;
726cb731d6cSVladimir Davydov 
727cb731d6cSVladimir Davydov 	for_each_online_node(nid)
728cb731d6cSVladimir Davydov 		drop_slab_node(nid);
729cb731d6cSVladimir Davydov }
730cb731d6cSVladimir Davydov 
7311da177e4SLinus Torvalds static inline int is_page_cache_freeable(struct page *page)
7321da177e4SLinus Torvalds {
733ceddc3a5SJohannes Weiner 	/*
734ceddc3a5SJohannes Weiner 	 * A freeable page cache page is referenced only by the caller
73567891fffSMatthew Wilcox 	 * that isolated the page, the page cache and optional buffer
73667891fffSMatthew Wilcox 	 * heads at page->private.
737ceddc3a5SJohannes Weiner 	 */
73867891fffSMatthew Wilcox 	int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
739bd4c82c2SHuang Ying 		HPAGE_PMD_NR : 1;
74067891fffSMatthew Wilcox 	return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
7411da177e4SLinus Torvalds }
7421da177e4SLinus Torvalds 
743cb16556dSYang Shi static int may_write_to_inode(struct inode *inode)
7441da177e4SLinus Torvalds {
745930d9152SChristoph Lameter 	if (current->flags & PF_SWAPWRITE)
7461da177e4SLinus Torvalds 		return 1;
747703c2708STejun Heo 	if (!inode_write_congested(inode))
7481da177e4SLinus Torvalds 		return 1;
749703c2708STejun Heo 	if (inode_to_bdi(inode) == current->backing_dev_info)
7501da177e4SLinus Torvalds 		return 1;
7511da177e4SLinus Torvalds 	return 0;
7521da177e4SLinus Torvalds }
7531da177e4SLinus Torvalds 
7541da177e4SLinus Torvalds /*
7551da177e4SLinus Torvalds  * We detected a synchronous write error writing a page out.  Probably
7561da177e4SLinus Torvalds  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
7571da177e4SLinus Torvalds  * fsync(), msync() or close().
7581da177e4SLinus Torvalds  *
7591da177e4SLinus Torvalds  * The tricky part is that after writepage we cannot touch the mapping: nothing
7601da177e4SLinus Torvalds  * prevents it from being freed up.  But we have a ref on the page and once
7611da177e4SLinus Torvalds  * that page is locked, the mapping is pinned.
7621da177e4SLinus Torvalds  *
7631da177e4SLinus Torvalds  * We're allowed to run sleeping lock_page() here because we know the caller has
7641da177e4SLinus Torvalds  * __GFP_FS.
7651da177e4SLinus Torvalds  */
7661da177e4SLinus Torvalds static void handle_write_error(struct address_space *mapping,
7671da177e4SLinus Torvalds 				struct page *page, int error)
7681da177e4SLinus Torvalds {
7697eaceaccSJens Axboe 	lock_page(page);
7703e9f45bdSGuillaume Chazarain 	if (page_mapping(page) == mapping)
7713e9f45bdSGuillaume Chazarain 		mapping_set_error(mapping, error);
7721da177e4SLinus Torvalds 	unlock_page(page);
7731da177e4SLinus Torvalds }
7741da177e4SLinus Torvalds 
77504e62a29SChristoph Lameter /* possible outcome of pageout() */
77604e62a29SChristoph Lameter typedef enum {
77704e62a29SChristoph Lameter 	/* failed to write page out, page is locked */
77804e62a29SChristoph Lameter 	PAGE_KEEP,
77904e62a29SChristoph Lameter 	/* move page to the active list, page is locked */
78004e62a29SChristoph Lameter 	PAGE_ACTIVATE,
78104e62a29SChristoph Lameter 	/* page has been sent to the disk successfully, page is unlocked */
78204e62a29SChristoph Lameter 	PAGE_SUCCESS,
78304e62a29SChristoph Lameter 	/* page is clean and locked */
78404e62a29SChristoph Lameter 	PAGE_CLEAN,
78504e62a29SChristoph Lameter } pageout_t;
78604e62a29SChristoph Lameter 
7871da177e4SLinus Torvalds /*
7881742f19fSAndrew Morton  * pageout is called by shrink_page_list() for each dirty page.
7891742f19fSAndrew Morton  * Calls ->writepage().
7901da177e4SLinus Torvalds  */
791cb16556dSYang Shi static pageout_t pageout(struct page *page, struct address_space *mapping)
7921da177e4SLinus Torvalds {
7931da177e4SLinus Torvalds 	/*
7941da177e4SLinus Torvalds 	 * If the page is dirty, only perform writeback if that write
7951da177e4SLinus Torvalds 	 * will be non-blocking.  To prevent this allocation from being
7961da177e4SLinus Torvalds 	 * stalled by pagecache activity.  But note that there may be
7971da177e4SLinus Torvalds 	 * stalls if we need to run get_block().  We could test
7981da177e4SLinus Torvalds 	 * PagePrivate for that.
7991da177e4SLinus Torvalds 	 *
8008174202bSAl Viro 	 * If this process is currently in __generic_file_write_iter() against
8011da177e4SLinus Torvalds 	 * this page's queue, we can perform writeback even if that
8021da177e4SLinus Torvalds 	 * will block.
8031da177e4SLinus Torvalds 	 *
8041da177e4SLinus Torvalds 	 * If the page is swapcache, write it back even if that would
8051da177e4SLinus Torvalds 	 * block, for some throttling. This happens by accident, because
8061da177e4SLinus Torvalds 	 * swap_backing_dev_info is bust: it doesn't reflect the
8071da177e4SLinus Torvalds 	 * congestion state of the swapdevs.  Easy to fix, if needed.
8081da177e4SLinus Torvalds 	 */
8091da177e4SLinus Torvalds 	if (!is_page_cache_freeable(page))
8101da177e4SLinus Torvalds 		return PAGE_KEEP;
8111da177e4SLinus Torvalds 	if (!mapping) {
8121da177e4SLinus Torvalds 		/*
8131da177e4SLinus Torvalds 		 * Some data journaling orphaned pages can have
8141da177e4SLinus Torvalds 		 * page->mapping == NULL while being dirty with clean buffers.
8151da177e4SLinus Torvalds 		 */
816266cf658SDavid Howells 		if (page_has_private(page)) {
8171da177e4SLinus Torvalds 			if (try_to_free_buffers(page)) {
8181da177e4SLinus Torvalds 				ClearPageDirty(page);
819b1de0d13SMitchel Humpherys 				pr_info("%s: orphaned page\n", __func__);
8201da177e4SLinus Torvalds 				return PAGE_CLEAN;
8211da177e4SLinus Torvalds 			}
8221da177e4SLinus Torvalds 		}
8231da177e4SLinus Torvalds 		return PAGE_KEEP;
8241da177e4SLinus Torvalds 	}
8251da177e4SLinus Torvalds 	if (mapping->a_ops->writepage == NULL)
8261da177e4SLinus Torvalds 		return PAGE_ACTIVATE;
827cb16556dSYang Shi 	if (!may_write_to_inode(mapping->host))
8281da177e4SLinus Torvalds 		return PAGE_KEEP;
8291da177e4SLinus Torvalds 
8301da177e4SLinus Torvalds 	if (clear_page_dirty_for_io(page)) {
8311da177e4SLinus Torvalds 		int res;
8321da177e4SLinus Torvalds 		struct writeback_control wbc = {
8331da177e4SLinus Torvalds 			.sync_mode = WB_SYNC_NONE,
8341da177e4SLinus Torvalds 			.nr_to_write = SWAP_CLUSTER_MAX,
835111ebb6eSOGAWA Hirofumi 			.range_start = 0,
836111ebb6eSOGAWA Hirofumi 			.range_end = LLONG_MAX,
8371da177e4SLinus Torvalds 			.for_reclaim = 1,
8381da177e4SLinus Torvalds 		};
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds 		SetPageReclaim(page);
8411da177e4SLinus Torvalds 		res = mapping->a_ops->writepage(page, &wbc);
8421da177e4SLinus Torvalds 		if (res < 0)
8431da177e4SLinus Torvalds 			handle_write_error(mapping, page, res);
844994fc28cSZach Brown 		if (res == AOP_WRITEPAGE_ACTIVATE) {
8451da177e4SLinus Torvalds 			ClearPageReclaim(page);
8461da177e4SLinus Torvalds 			return PAGE_ACTIVATE;
8471da177e4SLinus Torvalds 		}
848c661b078SAndy Whitcroft 
8491da177e4SLinus Torvalds 		if (!PageWriteback(page)) {
8501da177e4SLinus Torvalds 			/* synchronous write or broken a_ops? */
8511da177e4SLinus Torvalds 			ClearPageReclaim(page);
8521da177e4SLinus Torvalds 		}
8533aa23851Syalin wang 		trace_mm_vmscan_writepage(page);
854c4a25635SMel Gorman 		inc_node_page_state(page, NR_VMSCAN_WRITE);
8551da177e4SLinus Torvalds 		return PAGE_SUCCESS;
8561da177e4SLinus Torvalds 	}
8571da177e4SLinus Torvalds 
8581da177e4SLinus Torvalds 	return PAGE_CLEAN;
8591da177e4SLinus Torvalds }
8601da177e4SLinus Torvalds 
861a649fd92SAndrew Morton /*
862e286781dSNick Piggin  * Same as remove_mapping, but if the page is removed from the mapping, it
863e286781dSNick Piggin  * gets returned with a refcount of 0.
864a649fd92SAndrew Morton  */
865a528910eSJohannes Weiner static int __remove_mapping(struct address_space *mapping, struct page *page,
866b910718aSJohannes Weiner 			    bool reclaimed, struct mem_cgroup *target_memcg)
86749d2e9ccSChristoph Lameter {
868c4843a75SGreg Thelen 	unsigned long flags;
869bd4c82c2SHuang Ying 	int refcount;
870c4843a75SGreg Thelen 
87128e4d965SNick Piggin 	BUG_ON(!PageLocked(page));
87228e4d965SNick Piggin 	BUG_ON(mapping != page_mapping(page));
87349d2e9ccSChristoph Lameter 
874b93b0163SMatthew Wilcox 	xa_lock_irqsave(&mapping->i_pages, flags);
87549d2e9ccSChristoph Lameter 	/*
8760fd0e6b0SNick Piggin 	 * The non racy check for a busy page.
8770fd0e6b0SNick Piggin 	 *
8780fd0e6b0SNick Piggin 	 * Must be careful with the order of the tests. When someone has
8790fd0e6b0SNick Piggin 	 * a ref to the page, it may be possible that they dirty it then
8800fd0e6b0SNick Piggin 	 * drop the reference. So if PageDirty is tested before page_count
8810fd0e6b0SNick Piggin 	 * here, then the following race may occur:
8820fd0e6b0SNick Piggin 	 *
8830fd0e6b0SNick Piggin 	 * get_user_pages(&page);
8840fd0e6b0SNick Piggin 	 * [user mapping goes away]
8850fd0e6b0SNick Piggin 	 * write_to(page);
8860fd0e6b0SNick Piggin 	 *				!PageDirty(page)    [good]
8870fd0e6b0SNick Piggin 	 * SetPageDirty(page);
8880fd0e6b0SNick Piggin 	 * put_page(page);
8890fd0e6b0SNick Piggin 	 *				!page_count(page)   [good, discard it]
8900fd0e6b0SNick Piggin 	 *
8910fd0e6b0SNick Piggin 	 * [oops, our write_to data is lost]
8920fd0e6b0SNick Piggin 	 *
8930fd0e6b0SNick Piggin 	 * Reversing the order of the tests ensures such a situation cannot
8940fd0e6b0SNick Piggin 	 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
8950139aa7bSJoonsoo Kim 	 * load is not satisfied before that of page->_refcount.
8960fd0e6b0SNick Piggin 	 *
8970fd0e6b0SNick Piggin 	 * Note that if SetPageDirty is always performed via set_page_dirty,
898b93b0163SMatthew Wilcox 	 * and thus under the i_pages lock, then this ordering is not required.
89949d2e9ccSChristoph Lameter 	 */
900906d278dSWilliam Kucharski 	refcount = 1 + compound_nr(page);
901bd4c82c2SHuang Ying 	if (!page_ref_freeze(page, refcount))
90249d2e9ccSChristoph Lameter 		goto cannot_free;
9031c4c3b99SJiang Biao 	/* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
904e286781dSNick Piggin 	if (unlikely(PageDirty(page))) {
905bd4c82c2SHuang Ying 		page_ref_unfreeze(page, refcount);
90649d2e9ccSChristoph Lameter 		goto cannot_free;
907e286781dSNick Piggin 	}
90849d2e9ccSChristoph Lameter 
90949d2e9ccSChristoph Lameter 	if (PageSwapCache(page)) {
91049d2e9ccSChristoph Lameter 		swp_entry_t swap = { .val = page_private(page) };
9110a31bc97SJohannes Weiner 		mem_cgroup_swapout(page, swap);
9124e17ec25SMatthew Wilcox 		__delete_from_swap_cache(page, swap);
913b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
91475f6d6d2SMinchan Kim 		put_swap_page(page, swap);
915e286781dSNick Piggin 	} else {
9166072d13cSLinus Torvalds 		void (*freepage)(struct page *);
917a528910eSJohannes Weiner 		void *shadow = NULL;
9186072d13cSLinus Torvalds 
9196072d13cSLinus Torvalds 		freepage = mapping->a_ops->freepage;
920a528910eSJohannes Weiner 		/*
921a528910eSJohannes Weiner 		 * Remember a shadow entry for reclaimed file cache in
922a528910eSJohannes Weiner 		 * order to detect refaults, thus thrashing, later on.
923a528910eSJohannes Weiner 		 *
924a528910eSJohannes Weiner 		 * But don't store shadows in an address space that is
925a528910eSJohannes Weiner 		 * already exiting.  This is not just an optizimation,
926a528910eSJohannes Weiner 		 * inode reclaim needs to empty out the radix tree or
927a528910eSJohannes Weiner 		 * the nodes are lost.  Don't plant shadows behind its
928a528910eSJohannes Weiner 		 * back.
929f9fe48beSRoss Zwisler 		 *
930f9fe48beSRoss Zwisler 		 * We also don't store shadows for DAX mappings because the
931f9fe48beSRoss Zwisler 		 * only page cache pages found in these are zero pages
932f9fe48beSRoss Zwisler 		 * covering holes, and because we don't want to mix DAX
933f9fe48beSRoss Zwisler 		 * exceptional entries and shadow exceptional entries in the
934b93b0163SMatthew Wilcox 		 * same address_space.
935a528910eSJohannes Weiner 		 */
936a528910eSJohannes Weiner 		if (reclaimed && page_is_file_cache(page) &&
937f9fe48beSRoss Zwisler 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
938b910718aSJohannes Weiner 			shadow = workingset_eviction(page, target_memcg);
93962cccb8cSJohannes Weiner 		__delete_from_page_cache(page, shadow);
940b93b0163SMatthew Wilcox 		xa_unlock_irqrestore(&mapping->i_pages, flags);
9416072d13cSLinus Torvalds 
9426072d13cSLinus Torvalds 		if (freepage != NULL)
9436072d13cSLinus Torvalds 			freepage(page);
944e286781dSNick Piggin 	}
945e286781dSNick Piggin 
94649d2e9ccSChristoph Lameter 	return 1;
94749d2e9ccSChristoph Lameter 
94849d2e9ccSChristoph Lameter cannot_free:
949b93b0163SMatthew Wilcox 	xa_unlock_irqrestore(&mapping->i_pages, flags);
95049d2e9ccSChristoph Lameter 	return 0;
95149d2e9ccSChristoph Lameter }
95249d2e9ccSChristoph Lameter 
9531da177e4SLinus Torvalds /*
954e286781dSNick Piggin  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
955e286781dSNick Piggin  * someone else has a ref on the page, abort and return 0.  If it was
956e286781dSNick Piggin  * successfully detached, return 1.  Assumes the caller has a single ref on
957e286781dSNick Piggin  * this page.
958e286781dSNick Piggin  */
959e286781dSNick Piggin int remove_mapping(struct address_space *mapping, struct page *page)
960e286781dSNick Piggin {
961b910718aSJohannes Weiner 	if (__remove_mapping(mapping, page, false, NULL)) {
962e286781dSNick Piggin 		/*
963e286781dSNick Piggin 		 * Unfreezing the refcount with 1 rather than 2 effectively
964e286781dSNick Piggin 		 * drops the pagecache ref for us without requiring another
965e286781dSNick Piggin 		 * atomic operation.
966e286781dSNick Piggin 		 */
967fe896d18SJoonsoo Kim 		page_ref_unfreeze(page, 1);
968e286781dSNick Piggin 		return 1;
969e286781dSNick Piggin 	}
970e286781dSNick Piggin 	return 0;
971e286781dSNick Piggin }
972e286781dSNick Piggin 
973894bc310SLee Schermerhorn /**
974894bc310SLee Schermerhorn  * putback_lru_page - put previously isolated page onto appropriate LRU list
975894bc310SLee Schermerhorn  * @page: page to be put back to appropriate lru list
976894bc310SLee Schermerhorn  *
977894bc310SLee Schermerhorn  * Add previously isolated @page to appropriate LRU list.
978894bc310SLee Schermerhorn  * Page may still be unevictable for other reasons.
979894bc310SLee Schermerhorn  *
980894bc310SLee Schermerhorn  * lru_lock must not be held, interrupts must be enabled.
981894bc310SLee Schermerhorn  */
982894bc310SLee Schermerhorn void putback_lru_page(struct page *page)
983894bc310SLee Schermerhorn {
984c53954a0SMel Gorman 	lru_cache_add(page);
985894bc310SLee Schermerhorn 	put_page(page);		/* drop ref from isolate */
986894bc310SLee Schermerhorn }
987894bc310SLee Schermerhorn 
988dfc8d636SJohannes Weiner enum page_references {
989dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM,
990dfc8d636SJohannes Weiner 	PAGEREF_RECLAIM_CLEAN,
99164574746SJohannes Weiner 	PAGEREF_KEEP,
992dfc8d636SJohannes Weiner 	PAGEREF_ACTIVATE,
993dfc8d636SJohannes Weiner };
994dfc8d636SJohannes Weiner 
995dfc8d636SJohannes Weiner static enum page_references page_check_references(struct page *page,
996dfc8d636SJohannes Weiner 						  struct scan_control *sc)
997dfc8d636SJohannes Weiner {
99864574746SJohannes Weiner 	int referenced_ptes, referenced_page;
999dfc8d636SJohannes Weiner 	unsigned long vm_flags;
1000dfc8d636SJohannes Weiner 
1001c3ac9a8aSJohannes Weiner 	referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1002c3ac9a8aSJohannes Weiner 					  &vm_flags);
100364574746SJohannes Weiner 	referenced_page = TestClearPageReferenced(page);
1004dfc8d636SJohannes Weiner 
1005dfc8d636SJohannes Weiner 	/*
1006dfc8d636SJohannes Weiner 	 * Mlock lost the isolation race with us.  Let try_to_unmap()
1007dfc8d636SJohannes Weiner 	 * move the page to the unevictable list.
1008dfc8d636SJohannes Weiner 	 */
1009dfc8d636SJohannes Weiner 	if (vm_flags & VM_LOCKED)
1010dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM;
1011dfc8d636SJohannes Weiner 
101264574746SJohannes Weiner 	if (referenced_ptes) {
1013e4898273SMichal Hocko 		if (PageSwapBacked(page))
101464574746SJohannes Weiner 			return PAGEREF_ACTIVATE;
101564574746SJohannes Weiner 		/*
101664574746SJohannes Weiner 		 * All mapped pages start out with page table
101764574746SJohannes Weiner 		 * references from the instantiating fault, so we need
101864574746SJohannes Weiner 		 * to look twice if a mapped file page is used more
101964574746SJohannes Weiner 		 * than once.
102064574746SJohannes Weiner 		 *
102164574746SJohannes Weiner 		 * Mark it and spare it for another trip around the
102264574746SJohannes Weiner 		 * inactive list.  Another page table reference will
102364574746SJohannes Weiner 		 * lead to its activation.
102464574746SJohannes Weiner 		 *
102564574746SJohannes Weiner 		 * Note: the mark is set for activated pages as well
102664574746SJohannes Weiner 		 * so that recently deactivated but used pages are
102764574746SJohannes Weiner 		 * quickly recovered.
102864574746SJohannes Weiner 		 */
102964574746SJohannes Weiner 		SetPageReferenced(page);
103064574746SJohannes Weiner 
103134dbc67aSKonstantin Khlebnikov 		if (referenced_page || referenced_ptes > 1)
1032dfc8d636SJohannes Weiner 			return PAGEREF_ACTIVATE;
1033dfc8d636SJohannes Weiner 
1034c909e993SKonstantin Khlebnikov 		/*
1035c909e993SKonstantin Khlebnikov 		 * Activate file-backed executable pages after first usage.
1036c909e993SKonstantin Khlebnikov 		 */
1037c909e993SKonstantin Khlebnikov 		if (vm_flags & VM_EXEC)
1038c909e993SKonstantin Khlebnikov 			return PAGEREF_ACTIVATE;
1039c909e993SKonstantin Khlebnikov 
104064574746SJohannes Weiner 		return PAGEREF_KEEP;
104164574746SJohannes Weiner 	}
104264574746SJohannes Weiner 
1043dfc8d636SJohannes Weiner 	/* Reclaim if clean, defer dirty pages to writeback */
10442e30244aSKOSAKI Motohiro 	if (referenced_page && !PageSwapBacked(page))
1045dfc8d636SJohannes Weiner 		return PAGEREF_RECLAIM_CLEAN;
104664574746SJohannes Weiner 
104764574746SJohannes Weiner 	return PAGEREF_RECLAIM;
1048dfc8d636SJohannes Weiner }
1049dfc8d636SJohannes Weiner 
1050e2be15f6SMel Gorman /* Check if a page is dirty or under writeback */
1051e2be15f6SMel Gorman static void page_check_dirty_writeback(struct page *page,
1052e2be15f6SMel Gorman 				       bool *dirty, bool *writeback)
1053e2be15f6SMel Gorman {
1054b4597226SMel Gorman 	struct address_space *mapping;
1055b4597226SMel Gorman 
1056e2be15f6SMel Gorman 	/*
1057e2be15f6SMel Gorman 	 * Anonymous pages are not handled by flushers and must be written
1058e2be15f6SMel Gorman 	 * from reclaim context. Do not stall reclaim based on them
1059e2be15f6SMel Gorman 	 */
1060802a3a92SShaohua Li 	if (!page_is_file_cache(page) ||
1061802a3a92SShaohua Li 	    (PageAnon(page) && !PageSwapBacked(page))) {
1062e2be15f6SMel Gorman 		*dirty = false;
1063e2be15f6SMel Gorman 		*writeback = false;
1064e2be15f6SMel Gorman 		return;
1065e2be15f6SMel Gorman 	}
1066e2be15f6SMel Gorman 
1067e2be15f6SMel Gorman 	/* By default assume that the page flags are accurate */
1068e2be15f6SMel Gorman 	*dirty = PageDirty(page);
1069e2be15f6SMel Gorman 	*writeback = PageWriteback(page);
1070b4597226SMel Gorman 
1071b4597226SMel Gorman 	/* Verify dirty/writeback state if the filesystem supports it */
1072b4597226SMel Gorman 	if (!page_has_private(page))
1073b4597226SMel Gorman 		return;
1074b4597226SMel Gorman 
1075b4597226SMel Gorman 	mapping = page_mapping(page);
1076b4597226SMel Gorman 	if (mapping && mapping->a_ops->is_dirty_writeback)
1077b4597226SMel Gorman 		mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1078e2be15f6SMel Gorman }
1079e2be15f6SMel Gorman 
1080e286781dSNick Piggin /*
10811742f19fSAndrew Morton  * shrink_page_list() returns the number of reclaimed pages
10821da177e4SLinus Torvalds  */
10831742f19fSAndrew Morton static unsigned long shrink_page_list(struct list_head *page_list,
1084599d0c95SMel Gorman 				      struct pglist_data *pgdat,
1085f84f6e2bSMel Gorman 				      struct scan_control *sc,
108602c6de8dSMinchan Kim 				      enum ttu_flags ttu_flags,
10873c710c1aSMichal Hocko 				      struct reclaim_stat *stat,
10888940b34aSMinchan Kim 				      bool ignore_references)
10891da177e4SLinus Torvalds {
10901da177e4SLinus Torvalds 	LIST_HEAD(ret_pages);
1091abe4c3b5SMel Gorman 	LIST_HEAD(free_pages);
10923c710c1aSMichal Hocko 	unsigned nr_reclaimed = 0;
1093886cf190SKirill Tkhai 	unsigned pgactivate = 0;
10941da177e4SLinus Torvalds 
1095060f005fSKirill Tkhai 	memset(stat, 0, sizeof(*stat));
10961da177e4SLinus Torvalds 	cond_resched();
10971da177e4SLinus Torvalds 
10981da177e4SLinus Torvalds 	while (!list_empty(page_list)) {
10991da177e4SLinus Torvalds 		struct address_space *mapping;
11001da177e4SLinus Torvalds 		struct page *page;
11011da177e4SLinus Torvalds 		int may_enter_fs;
11028940b34aSMinchan Kim 		enum page_references references = PAGEREF_RECLAIM;
1103e2be15f6SMel Gorman 		bool dirty, writeback;
110498879b3bSYang Shi 		unsigned int nr_pages;
11051da177e4SLinus Torvalds 
11061da177e4SLinus Torvalds 		cond_resched();
11071da177e4SLinus Torvalds 
11081da177e4SLinus Torvalds 		page = lru_to_page(page_list);
11091da177e4SLinus Torvalds 		list_del(&page->lru);
11101da177e4SLinus Torvalds 
1111529ae9aaSNick Piggin 		if (!trylock_page(page))
11121da177e4SLinus Torvalds 			goto keep;
11131da177e4SLinus Torvalds 
1114309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
11151da177e4SLinus Torvalds 
1116d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
111798879b3bSYang Shi 
111898879b3bSYang Shi 		/* Account the number of base pages even though THP */
111998879b3bSYang Shi 		sc->nr_scanned += nr_pages;
112080e43426SChristoph Lameter 
112139b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page)))
1122ad6b6704SMinchan Kim 			goto activate_locked;
1123894bc310SLee Schermerhorn 
1124a6dc60f8SJohannes Weiner 		if (!sc->may_unmap && page_mapped(page))
112580e43426SChristoph Lameter 			goto keep_locked;
112680e43426SChristoph Lameter 
1127c661b078SAndy Whitcroft 		may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1128c661b078SAndy Whitcroft 			(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1129c661b078SAndy Whitcroft 
1130e62e384eSMichal Hocko 		/*
1131894befecSAndrey Ryabinin 		 * The number of dirty pages determines if a node is marked
1132e2be15f6SMel Gorman 		 * reclaim_congested which affects wait_iff_congested. kswapd
1133e2be15f6SMel Gorman 		 * will stall and start writing pages if the tail of the LRU
1134e2be15f6SMel Gorman 		 * is all dirty unqueued pages.
1135e2be15f6SMel Gorman 		 */
1136e2be15f6SMel Gorman 		page_check_dirty_writeback(page, &dirty, &writeback);
1137e2be15f6SMel Gorman 		if (dirty || writeback)
1138060f005fSKirill Tkhai 			stat->nr_dirty++;
1139e2be15f6SMel Gorman 
1140e2be15f6SMel Gorman 		if (dirty && !writeback)
1141060f005fSKirill Tkhai 			stat->nr_unqueued_dirty++;
1142e2be15f6SMel Gorman 
1143d04e8acdSMel Gorman 		/*
1144d04e8acdSMel Gorman 		 * Treat this page as congested if the underlying BDI is or if
1145d04e8acdSMel Gorman 		 * pages are cycling through the LRU so quickly that the
1146d04e8acdSMel Gorman 		 * pages marked for immediate reclaim are making it to the
1147d04e8acdSMel Gorman 		 * end of the LRU a second time.
1148d04e8acdSMel Gorman 		 */
1149e2be15f6SMel Gorman 		mapping = page_mapping(page);
11501da58ee2SJamie Liu 		if (((dirty || writeback) && mapping &&
1151703c2708STejun Heo 		     inode_write_congested(mapping->host)) ||
1152d04e8acdSMel Gorman 		    (writeback && PageReclaim(page)))
1153060f005fSKirill Tkhai 			stat->nr_congested++;
1154e2be15f6SMel Gorman 
1155e2be15f6SMel Gorman 		/*
1156283aba9fSMel Gorman 		 * If a page at the tail of the LRU is under writeback, there
1157283aba9fSMel Gorman 		 * are three cases to consider.
1158e62e384eSMichal Hocko 		 *
1159283aba9fSMel Gorman 		 * 1) If reclaim is encountering an excessive number of pages
1160283aba9fSMel Gorman 		 *    under writeback and this page is both under writeback and
1161283aba9fSMel Gorman 		 *    PageReclaim then it indicates that pages are being queued
1162283aba9fSMel Gorman 		 *    for IO but are being recycled through the LRU before the
1163283aba9fSMel Gorman 		 *    IO can complete. Waiting on the page itself risks an
1164283aba9fSMel Gorman 		 *    indefinite stall if it is impossible to writeback the
1165283aba9fSMel Gorman 		 *    page due to IO error or disconnected storage so instead
1166b1a6f21eSMel Gorman 		 *    note that the LRU is being scanned too quickly and the
1167b1a6f21eSMel Gorman 		 *    caller can stall after page list has been processed.
1168c3b94f44SHugh Dickins 		 *
116997c9341fSTejun Heo 		 * 2) Global or new memcg reclaim encounters a page that is
1170ecf5fc6eSMichal Hocko 		 *    not marked for immediate reclaim, or the caller does not
1171ecf5fc6eSMichal Hocko 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1172ecf5fc6eSMichal Hocko 		 *    not to fs). In this case mark the page for immediate
117397c9341fSTejun Heo 		 *    reclaim and continue scanning.
1174283aba9fSMel Gorman 		 *
1175ecf5fc6eSMichal Hocko 		 *    Require may_enter_fs because we would wait on fs, which
1176ecf5fc6eSMichal Hocko 		 *    may not have submitted IO yet. And the loop driver might
1177283aba9fSMel Gorman 		 *    enter reclaim, and deadlock if it waits on a page for
1178283aba9fSMel Gorman 		 *    which it is needed to do the write (loop masks off
1179283aba9fSMel Gorman 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1180283aba9fSMel Gorman 		 *    would probably show more reasons.
1181283aba9fSMel Gorman 		 *
11827fadc820SHugh Dickins 		 * 3) Legacy memcg encounters a page that is already marked
1183283aba9fSMel Gorman 		 *    PageReclaim. memcg does not have any dirty pages
1184283aba9fSMel Gorman 		 *    throttling so we could easily OOM just because too many
1185283aba9fSMel Gorman 		 *    pages are in writeback and there is nothing else to
1186283aba9fSMel Gorman 		 *    reclaim. Wait for the writeback to complete.
1187c55e8d03SJohannes Weiner 		 *
1188c55e8d03SJohannes Weiner 		 * In cases 1) and 2) we activate the pages to get them out of
1189c55e8d03SJohannes Weiner 		 * the way while we continue scanning for clean pages on the
1190c55e8d03SJohannes Weiner 		 * inactive list and refilling from the active list. The
1191c55e8d03SJohannes Weiner 		 * observation here is that waiting for disk writes is more
1192c55e8d03SJohannes Weiner 		 * expensive than potentially causing reloads down the line.
1193c55e8d03SJohannes Weiner 		 * Since they're marked for immediate reclaim, they won't put
1194c55e8d03SJohannes Weiner 		 * memory pressure on the cache working set any longer than it
1195c55e8d03SJohannes Weiner 		 * takes to write them to disk.
1196e62e384eSMichal Hocko 		 */
1197283aba9fSMel Gorman 		if (PageWriteback(page)) {
1198283aba9fSMel Gorman 			/* Case 1 above */
1199283aba9fSMel Gorman 			if (current_is_kswapd() &&
1200283aba9fSMel Gorman 			    PageReclaim(page) &&
1201599d0c95SMel Gorman 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1202060f005fSKirill Tkhai 				stat->nr_immediate++;
1203c55e8d03SJohannes Weiner 				goto activate_locked;
1204283aba9fSMel Gorman 
1205283aba9fSMel Gorman 			/* Case 2 above */
1206b5ead35eSJohannes Weiner 			} else if (writeback_throttling_sane(sc) ||
1207ecf5fc6eSMichal Hocko 			    !PageReclaim(page) || !may_enter_fs) {
1208c3b94f44SHugh Dickins 				/*
1209c3b94f44SHugh Dickins 				 * This is slightly racy - end_page_writeback()
1210c3b94f44SHugh Dickins 				 * might have just cleared PageReclaim, then
1211c3b94f44SHugh Dickins 				 * setting PageReclaim here end up interpreted
1212c3b94f44SHugh Dickins 				 * as PageReadahead - but that does not matter
1213c3b94f44SHugh Dickins 				 * enough to care.  What we do want is for this
1214c3b94f44SHugh Dickins 				 * page to have PageReclaim set next time memcg
1215c3b94f44SHugh Dickins 				 * reclaim reaches the tests above, so it will
1216c3b94f44SHugh Dickins 				 * then wait_on_page_writeback() to avoid OOM;
1217c3b94f44SHugh Dickins 				 * and it's also appropriate in global reclaim.
1218c3b94f44SHugh Dickins 				 */
1219c3b94f44SHugh Dickins 				SetPageReclaim(page);
1220060f005fSKirill Tkhai 				stat->nr_writeback++;
1221c55e8d03SJohannes Weiner 				goto activate_locked;
1222283aba9fSMel Gorman 
1223283aba9fSMel Gorman 			/* Case 3 above */
1224283aba9fSMel Gorman 			} else {
12257fadc820SHugh Dickins 				unlock_page(page);
1226c3b94f44SHugh Dickins 				wait_on_page_writeback(page);
12277fadc820SHugh Dickins 				/* then go back and try same page again */
12287fadc820SHugh Dickins 				list_add_tail(&page->lru, page_list);
12297fadc820SHugh Dickins 				continue;
1230e62e384eSMichal Hocko 			}
1231283aba9fSMel Gorman 		}
12321da177e4SLinus Torvalds 
12338940b34aSMinchan Kim 		if (!ignore_references)
12346a18adb3SKonstantin Khlebnikov 			references = page_check_references(page, sc);
123502c6de8dSMinchan Kim 
1236dfc8d636SJohannes Weiner 		switch (references) {
1237dfc8d636SJohannes Weiner 		case PAGEREF_ACTIVATE:
12381da177e4SLinus Torvalds 			goto activate_locked;
123964574746SJohannes Weiner 		case PAGEREF_KEEP:
124098879b3bSYang Shi 			stat->nr_ref_keep += nr_pages;
124164574746SJohannes Weiner 			goto keep_locked;
1242dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM:
1243dfc8d636SJohannes Weiner 		case PAGEREF_RECLAIM_CLEAN:
1244dfc8d636SJohannes Weiner 			; /* try to reclaim the page below */
1245dfc8d636SJohannes Weiner 		}
12461da177e4SLinus Torvalds 
12471da177e4SLinus Torvalds 		/*
12481da177e4SLinus Torvalds 		 * Anonymous process memory has backing store?
12491da177e4SLinus Torvalds 		 * Try to allocate it some swap space here.
1250802a3a92SShaohua Li 		 * Lazyfree page could be freed directly
12511da177e4SLinus Torvalds 		 */
1252bd4c82c2SHuang Ying 		if (PageAnon(page) && PageSwapBacked(page)) {
1253bd4c82c2SHuang Ying 			if (!PageSwapCache(page)) {
125463eb6b93SHugh Dickins 				if (!(sc->gfp_mask & __GFP_IO))
125563eb6b93SHugh Dickins 					goto keep_locked;
1256747552b1SHuang Ying 				if (PageTransHuge(page)) {
1257b8f593cdSHuang Ying 					/* cannot split THP, skip it */
1258747552b1SHuang Ying 					if (!can_split_huge_page(page, NULL))
1259b8f593cdSHuang Ying 						goto activate_locked;
1260747552b1SHuang Ying 					/*
1261747552b1SHuang Ying 					 * Split pages without a PMD map right
1262747552b1SHuang Ying 					 * away. Chances are some or all of the
1263747552b1SHuang Ying 					 * tail pages can be freed without IO.
1264747552b1SHuang Ying 					 */
1265747552b1SHuang Ying 					if (!compound_mapcount(page) &&
1266bd4c82c2SHuang Ying 					    split_huge_page_to_list(page,
1267bd4c82c2SHuang Ying 								    page_list))
1268747552b1SHuang Ying 						goto activate_locked;
1269747552b1SHuang Ying 				}
12700f074658SMinchan Kim 				if (!add_to_swap(page)) {
12710f074658SMinchan Kim 					if (!PageTransHuge(page))
127298879b3bSYang Shi 						goto activate_locked_split;
1273bd4c82c2SHuang Ying 					/* Fallback to swap normal pages */
1274bd4c82c2SHuang Ying 					if (split_huge_page_to_list(page,
1275bd4c82c2SHuang Ying 								    page_list))
12760f074658SMinchan Kim 						goto activate_locked;
1277fe490cc0SHuang Ying #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1278fe490cc0SHuang Ying 					count_vm_event(THP_SWPOUT_FALLBACK);
1279fe490cc0SHuang Ying #endif
12800f074658SMinchan Kim 					if (!add_to_swap(page))
128198879b3bSYang Shi 						goto activate_locked_split;
12820f074658SMinchan Kim 				}
12830f074658SMinchan Kim 
128463eb6b93SHugh Dickins 				may_enter_fs = 1;
12851da177e4SLinus Torvalds 
1286e2be15f6SMel Gorman 				/* Adding to swap updated mapping */
12871da177e4SLinus Torvalds 				mapping = page_mapping(page);
1288bd4c82c2SHuang Ying 			}
12897751b2daSKirill A. Shutemov 		} else if (unlikely(PageTransHuge(page))) {
12907751b2daSKirill A. Shutemov 			/* Split file THP */
12917751b2daSKirill A. Shutemov 			if (split_huge_page_to_list(page, page_list))
12927751b2daSKirill A. Shutemov 				goto keep_locked;
1293e2be15f6SMel Gorman 		}
12941da177e4SLinus Torvalds 
12951da177e4SLinus Torvalds 		/*
129698879b3bSYang Shi 		 * THP may get split above, need minus tail pages and update
129798879b3bSYang Shi 		 * nr_pages to avoid accounting tail pages twice.
129898879b3bSYang Shi 		 *
129998879b3bSYang Shi 		 * The tail pages that are added into swap cache successfully
130098879b3bSYang Shi 		 * reach here.
130198879b3bSYang Shi 		 */
130298879b3bSYang Shi 		if ((nr_pages > 1) && !PageTransHuge(page)) {
130398879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
130498879b3bSYang Shi 			nr_pages = 1;
130598879b3bSYang Shi 		}
130698879b3bSYang Shi 
130798879b3bSYang Shi 		/*
13081da177e4SLinus Torvalds 		 * The page is mapped into the page tables of one or more
13091da177e4SLinus Torvalds 		 * processes. Try to unmap it here.
13101da177e4SLinus Torvalds 		 */
1311802a3a92SShaohua Li 		if (page_mapped(page)) {
1312bd4c82c2SHuang Ying 			enum ttu_flags flags = ttu_flags | TTU_BATCH_FLUSH;
1313bd4c82c2SHuang Ying 
1314bd4c82c2SHuang Ying 			if (unlikely(PageTransHuge(page)))
1315bd4c82c2SHuang Ying 				flags |= TTU_SPLIT_HUGE_PMD;
1316bd4c82c2SHuang Ying 			if (!try_to_unmap(page, flags)) {
131798879b3bSYang Shi 				stat->nr_unmap_fail += nr_pages;
13181da177e4SLinus Torvalds 				goto activate_locked;
13191da177e4SLinus Torvalds 			}
13201da177e4SLinus Torvalds 		}
13211da177e4SLinus Torvalds 
13221da177e4SLinus Torvalds 		if (PageDirty(page)) {
1323ee72886dSMel Gorman 			/*
13244eda4823SJohannes Weiner 			 * Only kswapd can writeback filesystem pages
13254eda4823SJohannes Weiner 			 * to avoid risk of stack overflow. But avoid
13264eda4823SJohannes Weiner 			 * injecting inefficient single-page IO into
13274eda4823SJohannes Weiner 			 * flusher writeback as much as possible: only
13284eda4823SJohannes Weiner 			 * write pages when we've encountered many
13294eda4823SJohannes Weiner 			 * dirty pages, and when we've already scanned
13304eda4823SJohannes Weiner 			 * the rest of the LRU for clean pages and see
13314eda4823SJohannes Weiner 			 * the same dirty pages again (PageReclaim).
1332ee72886dSMel Gorman 			 */
1333f84f6e2bSMel Gorman 			if (page_is_file_cache(page) &&
13344eda4823SJohannes Weiner 			    (!current_is_kswapd() || !PageReclaim(page) ||
1335599d0c95SMel Gorman 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
133649ea7eb6SMel Gorman 				/*
133749ea7eb6SMel Gorman 				 * Immediately reclaim when written back.
133849ea7eb6SMel Gorman 				 * Similar in principal to deactivate_page()
133949ea7eb6SMel Gorman 				 * except we already have the page isolated
134049ea7eb6SMel Gorman 				 * and know it's dirty
134149ea7eb6SMel Gorman 				 */
1342c4a25635SMel Gorman 				inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
134349ea7eb6SMel Gorman 				SetPageReclaim(page);
134449ea7eb6SMel Gorman 
1345c55e8d03SJohannes Weiner 				goto activate_locked;
1346ee72886dSMel Gorman 			}
1347ee72886dSMel Gorman 
1348dfc8d636SJohannes Weiner 			if (references == PAGEREF_RECLAIM_CLEAN)
13491da177e4SLinus Torvalds 				goto keep_locked;
13504dd4b920SAndrew Morton 			if (!may_enter_fs)
13511da177e4SLinus Torvalds 				goto keep_locked;
135252a8363eSChristoph Lameter 			if (!sc->may_writepage)
13531da177e4SLinus Torvalds 				goto keep_locked;
13541da177e4SLinus Torvalds 
1355d950c947SMel Gorman 			/*
1356d950c947SMel Gorman 			 * Page is dirty. Flush the TLB if a writable entry
1357d950c947SMel Gorman 			 * potentially exists to avoid CPU writes after IO
1358d950c947SMel Gorman 			 * starts and then write it out here.
1359d950c947SMel Gorman 			 */
1360d950c947SMel Gorman 			try_to_unmap_flush_dirty();
1361cb16556dSYang Shi 			switch (pageout(page, mapping)) {
13621da177e4SLinus Torvalds 			case PAGE_KEEP:
13631da177e4SLinus Torvalds 				goto keep_locked;
13641da177e4SLinus Torvalds 			case PAGE_ACTIVATE:
13651da177e4SLinus Torvalds 				goto activate_locked;
13661da177e4SLinus Torvalds 			case PAGE_SUCCESS:
13677d3579e8SKOSAKI Motohiro 				if (PageWriteback(page))
136841ac1999SMel Gorman 					goto keep;
13697d3579e8SKOSAKI Motohiro 				if (PageDirty(page))
13701da177e4SLinus Torvalds 					goto keep;
13717d3579e8SKOSAKI Motohiro 
13721da177e4SLinus Torvalds 				/*
13731da177e4SLinus Torvalds 				 * A synchronous write - probably a ramdisk.  Go
13741da177e4SLinus Torvalds 				 * ahead and try to reclaim the page.
13751da177e4SLinus Torvalds 				 */
1376529ae9aaSNick Piggin 				if (!trylock_page(page))
13771da177e4SLinus Torvalds 					goto keep;
13781da177e4SLinus Torvalds 				if (PageDirty(page) || PageWriteback(page))
13791da177e4SLinus Torvalds 					goto keep_locked;
13801da177e4SLinus Torvalds 				mapping = page_mapping(page);
13811da177e4SLinus Torvalds 			case PAGE_CLEAN:
13821da177e4SLinus Torvalds 				; /* try to free the page below */
13831da177e4SLinus Torvalds 			}
13841da177e4SLinus Torvalds 		}
13851da177e4SLinus Torvalds 
13861da177e4SLinus Torvalds 		/*
13871da177e4SLinus Torvalds 		 * If the page has buffers, try to free the buffer mappings
13881da177e4SLinus Torvalds 		 * associated with this page. If we succeed we try to free
13891da177e4SLinus Torvalds 		 * the page as well.
13901da177e4SLinus Torvalds 		 *
13911da177e4SLinus Torvalds 		 * We do this even if the page is PageDirty().
13921da177e4SLinus Torvalds 		 * try_to_release_page() does not perform I/O, but it is
13931da177e4SLinus Torvalds 		 * possible for a page to have PageDirty set, but it is actually
13941da177e4SLinus Torvalds 		 * clean (all its buffers are clean).  This happens if the
13951da177e4SLinus Torvalds 		 * buffers were written out directly, with submit_bh(). ext3
13961da177e4SLinus Torvalds 		 * will do this, as well as the blockdev mapping.
13971da177e4SLinus Torvalds 		 * try_to_release_page() will discover that cleanness and will
13981da177e4SLinus Torvalds 		 * drop the buffers and mark the page clean - it can be freed.
13991da177e4SLinus Torvalds 		 *
14001da177e4SLinus Torvalds 		 * Rarely, pages can have buffers and no ->mapping.  These are
14011da177e4SLinus Torvalds 		 * the pages which were not successfully invalidated in
14021da177e4SLinus Torvalds 		 * truncate_complete_page().  We try to drop those buffers here
14031da177e4SLinus Torvalds 		 * and if that worked, and the page is no longer mapped into
14041da177e4SLinus Torvalds 		 * process address space (page_count == 1) it can be freed.
14051da177e4SLinus Torvalds 		 * Otherwise, leave the page on the LRU so it is swappable.
14061da177e4SLinus Torvalds 		 */
1407266cf658SDavid Howells 		if (page_has_private(page)) {
14081da177e4SLinus Torvalds 			if (!try_to_release_page(page, sc->gfp_mask))
14091da177e4SLinus Torvalds 				goto activate_locked;
1410e286781dSNick Piggin 			if (!mapping && page_count(page) == 1) {
1411e286781dSNick Piggin 				unlock_page(page);
1412e286781dSNick Piggin 				if (put_page_testzero(page))
14131da177e4SLinus Torvalds 					goto free_it;
1414e286781dSNick Piggin 				else {
1415e286781dSNick Piggin 					/*
1416e286781dSNick Piggin 					 * rare race with speculative reference.
1417e286781dSNick Piggin 					 * the speculative reference will free
1418e286781dSNick Piggin 					 * this page shortly, so we may
1419e286781dSNick Piggin 					 * increment nr_reclaimed here (and
1420e286781dSNick Piggin 					 * leave it off the LRU).
1421e286781dSNick Piggin 					 */
1422e286781dSNick Piggin 					nr_reclaimed++;
1423e286781dSNick Piggin 					continue;
1424e286781dSNick Piggin 				}
1425e286781dSNick Piggin 			}
14261da177e4SLinus Torvalds 		}
14271da177e4SLinus Torvalds 
1428802a3a92SShaohua Li 		if (PageAnon(page) && !PageSwapBacked(page)) {
1429802a3a92SShaohua Li 			/* follow __remove_mapping for reference */
1430802a3a92SShaohua Li 			if (!page_ref_freeze(page, 1))
143149d2e9ccSChristoph Lameter 				goto keep_locked;
1432802a3a92SShaohua Li 			if (PageDirty(page)) {
1433802a3a92SShaohua Li 				page_ref_unfreeze(page, 1);
1434802a3a92SShaohua Li 				goto keep_locked;
1435802a3a92SShaohua Li 			}
14361da177e4SLinus Torvalds 
1437802a3a92SShaohua Li 			count_vm_event(PGLAZYFREED);
14382262185cSRoman Gushchin 			count_memcg_page_event(page, PGLAZYFREED);
1439b910718aSJohannes Weiner 		} else if (!mapping || !__remove_mapping(mapping, page, true,
1440b910718aSJohannes Weiner 							 sc->target_mem_cgroup))
1441802a3a92SShaohua Li 			goto keep_locked;
14429a1ea439SHugh Dickins 
14439a1ea439SHugh Dickins 		unlock_page(page);
1444e286781dSNick Piggin free_it:
144598879b3bSYang Shi 		/*
144698879b3bSYang Shi 		 * THP may get swapped out in a whole, need account
144798879b3bSYang Shi 		 * all base pages.
144898879b3bSYang Shi 		 */
144998879b3bSYang Shi 		nr_reclaimed += nr_pages;
1450abe4c3b5SMel Gorman 
1451abe4c3b5SMel Gorman 		/*
1452abe4c3b5SMel Gorman 		 * Is there need to periodically free_page_list? It would
1453abe4c3b5SMel Gorman 		 * appear not as the counts should be low
1454abe4c3b5SMel Gorman 		 */
14557ae88534SYang Shi 		if (unlikely(PageTransHuge(page)))
1456bd4c82c2SHuang Ying 			(*get_compound_page_dtor(page))(page);
14577ae88534SYang Shi 		else
1458abe4c3b5SMel Gorman 			list_add(&page->lru, &free_pages);
14591da177e4SLinus Torvalds 		continue;
14601da177e4SLinus Torvalds 
146198879b3bSYang Shi activate_locked_split:
146298879b3bSYang Shi 		/*
146398879b3bSYang Shi 		 * The tail pages that are failed to add into swap cache
146498879b3bSYang Shi 		 * reach here.  Fixup nr_scanned and nr_pages.
146598879b3bSYang Shi 		 */
146698879b3bSYang Shi 		if (nr_pages > 1) {
146798879b3bSYang Shi 			sc->nr_scanned -= (nr_pages - 1);
146898879b3bSYang Shi 			nr_pages = 1;
146998879b3bSYang Shi 		}
14701da177e4SLinus Torvalds activate_locked:
147168a22394SRik van Riel 		/* Not a candidate for swapping, so reclaim swap space. */
1472ad6b6704SMinchan Kim 		if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1473ad6b6704SMinchan Kim 						PageMlocked(page)))
1474a2c43eedSHugh Dickins 			try_to_free_swap(page);
1475309381feSSasha Levin 		VM_BUG_ON_PAGE(PageActive(page), page);
1476ad6b6704SMinchan Kim 		if (!PageMlocked(page)) {
1477886cf190SKirill Tkhai 			int type = page_is_file_cache(page);
14781da177e4SLinus Torvalds 			SetPageActive(page);
147998879b3bSYang Shi 			stat->nr_activate[type] += nr_pages;
14802262185cSRoman Gushchin 			count_memcg_page_event(page, PGACTIVATE);
1481ad6b6704SMinchan Kim 		}
14821da177e4SLinus Torvalds keep_locked:
14831da177e4SLinus Torvalds 		unlock_page(page);
14841da177e4SLinus Torvalds keep:
14851da177e4SLinus Torvalds 		list_add(&page->lru, &ret_pages);
1486309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
14871da177e4SLinus Torvalds 	}
1488abe4c3b5SMel Gorman 
148998879b3bSYang Shi 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
149098879b3bSYang Shi 
1491747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&free_pages);
149272b252aeSMel Gorman 	try_to_unmap_flush();
14932d4894b5SMel Gorman 	free_unref_page_list(&free_pages);
1494abe4c3b5SMel Gorman 
14951da177e4SLinus Torvalds 	list_splice(&ret_pages, page_list);
1496886cf190SKirill Tkhai 	count_vm_events(PGACTIVATE, pgactivate);
14970a31bc97SJohannes Weiner 
149805ff5137SAndrew Morton 	return nr_reclaimed;
14991da177e4SLinus Torvalds }
15001da177e4SLinus Torvalds 
150102c6de8dSMinchan Kim unsigned long reclaim_clean_pages_from_list(struct zone *zone,
150202c6de8dSMinchan Kim 					    struct list_head *page_list)
150302c6de8dSMinchan Kim {
150402c6de8dSMinchan Kim 	struct scan_control sc = {
150502c6de8dSMinchan Kim 		.gfp_mask = GFP_KERNEL,
150602c6de8dSMinchan Kim 		.priority = DEF_PRIORITY,
150702c6de8dSMinchan Kim 		.may_unmap = 1,
150802c6de8dSMinchan Kim 	};
1509060f005fSKirill Tkhai 	struct reclaim_stat dummy_stat;
15103c710c1aSMichal Hocko 	unsigned long ret;
151102c6de8dSMinchan Kim 	struct page *page, *next;
151202c6de8dSMinchan Kim 	LIST_HEAD(clean_pages);
151302c6de8dSMinchan Kim 
151402c6de8dSMinchan Kim 	list_for_each_entry_safe(page, next, page_list, lru) {
1515117aad1eSRafael Aquini 		if (page_is_file_cache(page) && !PageDirty(page) &&
1516a58f2cefSMinchan Kim 		    !__PageMovable(page) && !PageUnevictable(page)) {
151702c6de8dSMinchan Kim 			ClearPageActive(page);
151802c6de8dSMinchan Kim 			list_move(&page->lru, &clean_pages);
151902c6de8dSMinchan Kim 		}
152002c6de8dSMinchan Kim 	}
152102c6de8dSMinchan Kim 
1522599d0c95SMel Gorman 	ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1523060f005fSKirill Tkhai 			TTU_IGNORE_ACCESS, &dummy_stat, true);
152402c6de8dSMinchan Kim 	list_splice(&clean_pages, page_list);
1525599d0c95SMel Gorman 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
152602c6de8dSMinchan Kim 	return ret;
152702c6de8dSMinchan Kim }
152802c6de8dSMinchan Kim 
15295ad333ebSAndy Whitcroft /*
15305ad333ebSAndy Whitcroft  * Attempt to remove the specified page from its LRU.  Only take this page
15315ad333ebSAndy Whitcroft  * if it is of the appropriate PageActive status.  Pages which are being
15325ad333ebSAndy Whitcroft  * freed elsewhere are also ignored.
15335ad333ebSAndy Whitcroft  *
15345ad333ebSAndy Whitcroft  * page:	page to consider
15355ad333ebSAndy Whitcroft  * mode:	one of the LRU isolation modes defined above
15365ad333ebSAndy Whitcroft  *
15375ad333ebSAndy Whitcroft  * returns 0 on success, -ve errno on failure.
15385ad333ebSAndy Whitcroft  */
1539f3fd4a61SKonstantin Khlebnikov int __isolate_lru_page(struct page *page, isolate_mode_t mode)
15405ad333ebSAndy Whitcroft {
15415ad333ebSAndy Whitcroft 	int ret = -EINVAL;
15425ad333ebSAndy Whitcroft 
15435ad333ebSAndy Whitcroft 	/* Only take pages on the LRU. */
15445ad333ebSAndy Whitcroft 	if (!PageLRU(page))
15455ad333ebSAndy Whitcroft 		return ret;
15465ad333ebSAndy Whitcroft 
1547e46a2879SMinchan Kim 	/* Compaction should not handle unevictable pages but CMA can do so */
1548e46a2879SMinchan Kim 	if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1549894bc310SLee Schermerhorn 		return ret;
1550894bc310SLee Schermerhorn 
15515ad333ebSAndy Whitcroft 	ret = -EBUSY;
155208e552c6SKAMEZAWA Hiroyuki 
1553c8244935SMel Gorman 	/*
1554c8244935SMel Gorman 	 * To minimise LRU disruption, the caller can indicate that it only
1555c8244935SMel Gorman 	 * wants to isolate pages it will be able to operate on without
1556c8244935SMel Gorman 	 * blocking - clean pages for the most part.
1557c8244935SMel Gorman 	 *
1558c8244935SMel Gorman 	 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1559c8244935SMel Gorman 	 * that it is possible to migrate without blocking
1560c8244935SMel Gorman 	 */
15611276ad68SJohannes Weiner 	if (mode & ISOLATE_ASYNC_MIGRATE) {
1562c8244935SMel Gorman 		/* All the caller can do on PageWriteback is block */
1563c8244935SMel Gorman 		if (PageWriteback(page))
156439deaf85SMinchan Kim 			return ret;
156539deaf85SMinchan Kim 
1566c8244935SMel Gorman 		if (PageDirty(page)) {
1567c8244935SMel Gorman 			struct address_space *mapping;
156869d763fcSMel Gorman 			bool migrate_dirty;
1569c8244935SMel Gorman 
1570c8244935SMel Gorman 			/*
1571c8244935SMel Gorman 			 * Only pages without mappings or that have a
1572c8244935SMel Gorman 			 * ->migratepage callback are possible to migrate
157369d763fcSMel Gorman 			 * without blocking. However, we can be racing with
157469d763fcSMel Gorman 			 * truncation so it's necessary to lock the page
157569d763fcSMel Gorman 			 * to stabilise the mapping as truncation holds
157669d763fcSMel Gorman 			 * the page lock until after the page is removed
157769d763fcSMel Gorman 			 * from the page cache.
1578c8244935SMel Gorman 			 */
157969d763fcSMel Gorman 			if (!trylock_page(page))
158069d763fcSMel Gorman 				return ret;
158169d763fcSMel Gorman 
1582c8244935SMel Gorman 			mapping = page_mapping(page);
1583145e1a71SHugh Dickins 			migrate_dirty = !mapping || mapping->a_ops->migratepage;
158469d763fcSMel Gorman 			unlock_page(page);
158569d763fcSMel Gorman 			if (!migrate_dirty)
1586c8244935SMel Gorman 				return ret;
1587c8244935SMel Gorman 		}
1588c8244935SMel Gorman 	}
1589c8244935SMel Gorman 
1590f80c0673SMinchan Kim 	if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1591f80c0673SMinchan Kim 		return ret;
1592f80c0673SMinchan Kim 
15935ad333ebSAndy Whitcroft 	if (likely(get_page_unless_zero(page))) {
15945ad333ebSAndy Whitcroft 		/*
15955ad333ebSAndy Whitcroft 		 * Be careful not to clear PageLRU until after we're
15965ad333ebSAndy Whitcroft 		 * sure the page is not being freed elsewhere -- the
15975ad333ebSAndy Whitcroft 		 * page release code relies on it.
15985ad333ebSAndy Whitcroft 		 */
15995ad333ebSAndy Whitcroft 		ClearPageLRU(page);
16005ad333ebSAndy Whitcroft 		ret = 0;
16015ad333ebSAndy Whitcroft 	}
16025ad333ebSAndy Whitcroft 
16035ad333ebSAndy Whitcroft 	return ret;
16045ad333ebSAndy Whitcroft }
16055ad333ebSAndy Whitcroft 
16067ee36a14SMel Gorman 
16077ee36a14SMel Gorman /*
16087ee36a14SMel Gorman  * Update LRU sizes after isolating pages. The LRU size updates must
16097ee36a14SMel Gorman  * be complete before mem_cgroup_update_lru_size due to a santity check.
16107ee36a14SMel Gorman  */
16117ee36a14SMel Gorman static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1612b4536f0cSMichal Hocko 			enum lru_list lru, unsigned long *nr_zone_taken)
16137ee36a14SMel Gorman {
16147ee36a14SMel Gorman 	int zid;
16157ee36a14SMel Gorman 
16167ee36a14SMel Gorman 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
16177ee36a14SMel Gorman 		if (!nr_zone_taken[zid])
16187ee36a14SMel Gorman 			continue;
16197ee36a14SMel Gorman 
16207ee36a14SMel Gorman 		__update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1621b4536f0cSMichal Hocko #ifdef CONFIG_MEMCG
1622b4536f0cSMichal Hocko 		mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1623b4536f0cSMichal Hocko #endif
16247ee36a14SMel Gorman 	}
16257ee36a14SMel Gorman 
16267ee36a14SMel Gorman }
16277ee36a14SMel Gorman 
1628f4b7e272SAndrey Ryabinin /**
1629f4b7e272SAndrey Ryabinin  * pgdat->lru_lock is heavily contended.  Some of the functions that
16301da177e4SLinus Torvalds  * shrink the lists perform better by taking out a batch of pages
16311da177e4SLinus Torvalds  * and working on them outside the LRU lock.
16321da177e4SLinus Torvalds  *
16331da177e4SLinus Torvalds  * For pagecache intensive workloads, this function is the hottest
16341da177e4SLinus Torvalds  * spot in the kernel (apart from copy_*_user functions).
16351da177e4SLinus Torvalds  *
16361da177e4SLinus Torvalds  * Appropriate locks must be held before calling this function.
16371da177e4SLinus Torvalds  *
1638791b48b6SMinchan Kim  * @nr_to_scan:	The number of eligible pages to look through on the list.
16395dc35979SKonstantin Khlebnikov  * @lruvec:	The LRU vector to pull pages from.
16401da177e4SLinus Torvalds  * @dst:	The temp list to put pages on to.
1641f626012dSHugh Dickins  * @nr_scanned:	The number of pages that were scanned.
1642fe2c2a10SRik van Riel  * @sc:		The scan_control struct for this reclaim session
16435ad333ebSAndy Whitcroft  * @mode:	One of the LRU isolation modes
16443cb99451SKonstantin Khlebnikov  * @lru:	LRU list id for isolating
16451da177e4SLinus Torvalds  *
16461da177e4SLinus Torvalds  * returns how many pages were moved onto *@dst.
16471da177e4SLinus Torvalds  */
164869e05944SAndrew Morton static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
16495dc35979SKonstantin Khlebnikov 		struct lruvec *lruvec, struct list_head *dst,
1650fe2c2a10SRik van Riel 		unsigned long *nr_scanned, struct scan_control *sc,
1651a9e7c39fSKirill Tkhai 		enum lru_list lru)
16521da177e4SLinus Torvalds {
165375b00af7SHugh Dickins 	struct list_head *src = &lruvec->lists[lru];
165469e05944SAndrew Morton 	unsigned long nr_taken = 0;
1655599d0c95SMel Gorman 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
16567cc30fcfSMel Gorman 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
16573db65812SJohannes Weiner 	unsigned long skipped = 0;
1658791b48b6SMinchan Kim 	unsigned long scan, total_scan, nr_pages;
1659b2e18757SMel Gorman 	LIST_HEAD(pages_skipped);
1660a9e7c39fSKirill Tkhai 	isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
16611da177e4SLinus Torvalds 
166298879b3bSYang Shi 	total_scan = 0;
1663791b48b6SMinchan Kim 	scan = 0;
166498879b3bSYang Shi 	while (scan < nr_to_scan && !list_empty(src)) {
16655ad333ebSAndy Whitcroft 		struct page *page;
16665ad333ebSAndy Whitcroft 
16671da177e4SLinus Torvalds 		page = lru_to_page(src);
16681da177e4SLinus Torvalds 		prefetchw_prev_lru_page(page, src, flags);
16691da177e4SLinus Torvalds 
1670309381feSSasha Levin 		VM_BUG_ON_PAGE(!PageLRU(page), page);
16718d438f96SNick Piggin 
1672d8c6546bSMatthew Wilcox (Oracle) 		nr_pages = compound_nr(page);
167398879b3bSYang Shi 		total_scan += nr_pages;
167498879b3bSYang Shi 
1675b2e18757SMel Gorman 		if (page_zonenum(page) > sc->reclaim_idx) {
1676b2e18757SMel Gorman 			list_move(&page->lru, &pages_skipped);
167798879b3bSYang Shi 			nr_skipped[page_zonenum(page)] += nr_pages;
1678b2e18757SMel Gorman 			continue;
1679b2e18757SMel Gorman 		}
1680b2e18757SMel Gorman 
1681791b48b6SMinchan Kim 		/*
1682791b48b6SMinchan Kim 		 * Do not count skipped pages because that makes the function
1683791b48b6SMinchan Kim 		 * return with no isolated pages if the LRU mostly contains
1684791b48b6SMinchan Kim 		 * ineligible pages.  This causes the VM to not reclaim any
1685791b48b6SMinchan Kim 		 * pages, triggering a premature OOM.
168698879b3bSYang Shi 		 *
168798879b3bSYang Shi 		 * Account all tail pages of THP.  This would not cause
168898879b3bSYang Shi 		 * premature OOM since __isolate_lru_page() returns -EBUSY
168998879b3bSYang Shi 		 * only when the page is being freed somewhere else.
1690791b48b6SMinchan Kim 		 */
169198879b3bSYang Shi 		scan += nr_pages;
1692f3fd4a61SKonstantin Khlebnikov 		switch (__isolate_lru_page(page, mode)) {
16935ad333ebSAndy Whitcroft 		case 0:
1694599d0c95SMel Gorman 			nr_taken += nr_pages;
1695599d0c95SMel Gorman 			nr_zone_taken[page_zonenum(page)] += nr_pages;
16965ad333ebSAndy Whitcroft 			list_move(&page->lru, dst);
16975ad333ebSAndy Whitcroft 			break;
16987c8ee9a8SNick Piggin 
16995ad333ebSAndy Whitcroft 		case -EBUSY:
17005ad333ebSAndy Whitcroft 			/* else it is being freed elsewhere */
17015ad333ebSAndy Whitcroft 			list_move(&page->lru, src);
17025ad333ebSAndy Whitcroft 			continue;
17035ad333ebSAndy Whitcroft 
17045ad333ebSAndy Whitcroft 		default:
17055ad333ebSAndy Whitcroft 			BUG();
17065ad333ebSAndy Whitcroft 		}
17075ad333ebSAndy Whitcroft 	}
17081da177e4SLinus Torvalds 
1709b2e18757SMel Gorman 	/*
1710b2e18757SMel Gorman 	 * Splice any skipped pages to the start of the LRU list. Note that
1711b2e18757SMel Gorman 	 * this disrupts the LRU order when reclaiming for lower zones but
1712b2e18757SMel Gorman 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1713b2e18757SMel Gorman 	 * scanning would soon rescan the same pages to skip and put the
1714b2e18757SMel Gorman 	 * system at risk of premature OOM.
1715b2e18757SMel Gorman 	 */
17167cc30fcfSMel Gorman 	if (!list_empty(&pages_skipped)) {
17177cc30fcfSMel Gorman 		int zid;
17187cc30fcfSMel Gorman 
17193db65812SJohannes Weiner 		list_splice(&pages_skipped, src);
17207cc30fcfSMel Gorman 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
17217cc30fcfSMel Gorman 			if (!nr_skipped[zid])
17227cc30fcfSMel Gorman 				continue;
17237cc30fcfSMel Gorman 
17247cc30fcfSMel Gorman 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
17251265e3a6SMichal Hocko 			skipped += nr_skipped[zid];
17267cc30fcfSMel Gorman 		}
17277cc30fcfSMel Gorman 	}
1728791b48b6SMinchan Kim 	*nr_scanned = total_scan;
17291265e3a6SMichal Hocko 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1730791b48b6SMinchan Kim 				    total_scan, skipped, nr_taken, mode, lru);
1731b4536f0cSMichal Hocko 	update_lru_sizes(lruvec, lru, nr_zone_taken);
17321da177e4SLinus Torvalds 	return nr_taken;
17331da177e4SLinus Torvalds }
17341da177e4SLinus Torvalds 
173562695a84SNick Piggin /**
173662695a84SNick Piggin  * isolate_lru_page - tries to isolate a page from its LRU list
173762695a84SNick Piggin  * @page: page to isolate from its LRU list
173862695a84SNick Piggin  *
173962695a84SNick Piggin  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
174062695a84SNick Piggin  * vmstat statistic corresponding to whatever LRU list the page was on.
174162695a84SNick Piggin  *
174262695a84SNick Piggin  * Returns 0 if the page was removed from an LRU list.
174362695a84SNick Piggin  * Returns -EBUSY if the page was not on an LRU list.
174462695a84SNick Piggin  *
174562695a84SNick Piggin  * The returned page will have PageLRU() cleared.  If it was found on
1746894bc310SLee Schermerhorn  * the active list, it will have PageActive set.  If it was found on
1747894bc310SLee Schermerhorn  * the unevictable list, it will have the PageUnevictable bit set. That flag
1748894bc310SLee Schermerhorn  * may need to be cleared by the caller before letting the page go.
174962695a84SNick Piggin  *
175062695a84SNick Piggin  * The vmstat statistic corresponding to the list on which the page was
175162695a84SNick Piggin  * found will be decremented.
175262695a84SNick Piggin  *
175362695a84SNick Piggin  * Restrictions:
1754a5d09bedSMike Rapoport  *
175562695a84SNick Piggin  * (1) Must be called with an elevated refcount on the page. This is a
175662695a84SNick Piggin  *     fundamentnal difference from isolate_lru_pages (which is called
175762695a84SNick Piggin  *     without a stable reference).
175862695a84SNick Piggin  * (2) the lru_lock must not be held.
175962695a84SNick Piggin  * (3) interrupts must be enabled.
176062695a84SNick Piggin  */
176162695a84SNick Piggin int isolate_lru_page(struct page *page)
176262695a84SNick Piggin {
176362695a84SNick Piggin 	int ret = -EBUSY;
176462695a84SNick Piggin 
1765309381feSSasha Levin 	VM_BUG_ON_PAGE(!page_count(page), page);
1766cf2a82eeSKirill A. Shutemov 	WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
17670c917313SKonstantin Khlebnikov 
176862695a84SNick Piggin 	if (PageLRU(page)) {
1769f4b7e272SAndrey Ryabinin 		pg_data_t *pgdat = page_pgdat(page);
1770fa9add64SHugh Dickins 		struct lruvec *lruvec;
177162695a84SNick Piggin 
1772f4b7e272SAndrey Ryabinin 		spin_lock_irq(&pgdat->lru_lock);
1773f4b7e272SAndrey Ryabinin 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
17740c917313SKonstantin Khlebnikov 		if (PageLRU(page)) {
1775894bc310SLee Schermerhorn 			int lru = page_lru(page);
17760c917313SKonstantin Khlebnikov 			get_page(page);
177762695a84SNick Piggin 			ClearPageLRU(page);
1778fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
1779fa9add64SHugh Dickins 			ret = 0;
178062695a84SNick Piggin 		}
1781f4b7e272SAndrey Ryabinin 		spin_unlock_irq(&pgdat->lru_lock);
178262695a84SNick Piggin 	}
178362695a84SNick Piggin 	return ret;
178462695a84SNick Piggin }
178562695a84SNick Piggin 
17865ad333ebSAndy Whitcroft /*
1787d37dd5dcSFengguang Wu  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1788178821b8SXianting Tian  * then get rescheduled. When there are massive number of tasks doing page
1789d37dd5dcSFengguang Wu  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1790d37dd5dcSFengguang Wu  * the LRU list will go small and be scanned faster than necessary, leading to
1791d37dd5dcSFengguang Wu  * unnecessary swapping, thrashing and OOM.
179235cd7815SRik van Riel  */
1793599d0c95SMel Gorman static int too_many_isolated(struct pglist_data *pgdat, int file,
179435cd7815SRik van Riel 		struct scan_control *sc)
179535cd7815SRik van Riel {
179635cd7815SRik van Riel 	unsigned long inactive, isolated;
179735cd7815SRik van Riel 
179835cd7815SRik van Riel 	if (current_is_kswapd())
179935cd7815SRik van Riel 		return 0;
180035cd7815SRik van Riel 
1801b5ead35eSJohannes Weiner 	if (!writeback_throttling_sane(sc))
180235cd7815SRik van Riel 		return 0;
180335cd7815SRik van Riel 
180435cd7815SRik van Riel 	if (file) {
1805599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1806599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
180735cd7815SRik van Riel 	} else {
1808599d0c95SMel Gorman 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1809599d0c95SMel Gorman 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
181035cd7815SRik van Riel 	}
181135cd7815SRik van Riel 
18123cf23841SFengguang Wu 	/*
18133cf23841SFengguang Wu 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
18143cf23841SFengguang Wu 	 * won't get blocked by normal direct-reclaimers, forming a circular
18153cf23841SFengguang Wu 	 * deadlock.
18163cf23841SFengguang Wu 	 */
1817d0164adcSMel Gorman 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
18183cf23841SFengguang Wu 		inactive >>= 3;
18193cf23841SFengguang Wu 
182035cd7815SRik van Riel 	return isolated > inactive;
182135cd7815SRik van Riel }
182235cd7815SRik van Riel 
1823a222f341SKirill Tkhai /*
1824a222f341SKirill Tkhai  * This moves pages from @list to corresponding LRU list.
1825a222f341SKirill Tkhai  *
1826a222f341SKirill Tkhai  * We move them the other way if the page is referenced by one or more
1827a222f341SKirill Tkhai  * processes, from rmap.
1828a222f341SKirill Tkhai  *
1829a222f341SKirill Tkhai  * If the pages are mostly unmapped, the processing is fast and it is
1830a222f341SKirill Tkhai  * appropriate to hold zone_lru_lock across the whole operation.  But if
1831a222f341SKirill Tkhai  * the pages are mapped, the processing is slow (page_referenced()) so we
1832a222f341SKirill Tkhai  * should drop zone_lru_lock around each page.  It's impossible to balance
1833a222f341SKirill Tkhai  * this, so instead we remove the pages from the LRU while processing them.
1834a222f341SKirill Tkhai  * It is safe to rely on PG_active against the non-LRU pages in here because
1835a222f341SKirill Tkhai  * nobody will play with that bit on a non-LRU page.
1836a222f341SKirill Tkhai  *
1837a222f341SKirill Tkhai  * The downside is that we have to touch page->_refcount against each page.
1838a222f341SKirill Tkhai  * But we had to alter page->flags anyway.
1839a222f341SKirill Tkhai  *
1840a222f341SKirill Tkhai  * Returns the number of pages moved to the given lruvec.
1841a222f341SKirill Tkhai  */
1842a222f341SKirill Tkhai 
1843a222f341SKirill Tkhai static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1844a222f341SKirill Tkhai 						     struct list_head *list)
184566635629SMel Gorman {
1846599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1847a222f341SKirill Tkhai 	int nr_pages, nr_moved = 0;
18483f79768fSHugh Dickins 	LIST_HEAD(pages_to_free);
1849a222f341SKirill Tkhai 	struct page *page;
1850a222f341SKirill Tkhai 	enum lru_list lru;
185166635629SMel Gorman 
1852a222f341SKirill Tkhai 	while (!list_empty(list)) {
1853a222f341SKirill Tkhai 		page = lru_to_page(list);
1854309381feSSasha Levin 		VM_BUG_ON_PAGE(PageLRU(page), page);
185539b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
1856a222f341SKirill Tkhai 			list_del(&page->lru);
1857599d0c95SMel Gorman 			spin_unlock_irq(&pgdat->lru_lock);
185866635629SMel Gorman 			putback_lru_page(page);
1859599d0c95SMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
186066635629SMel Gorman 			continue;
186166635629SMel Gorman 		}
1862599d0c95SMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
1863fa9add64SHugh Dickins 
18647a608572SLinus Torvalds 		SetPageLRU(page);
186566635629SMel Gorman 		lru = page_lru(page);
1866a222f341SKirill Tkhai 
1867a222f341SKirill Tkhai 		nr_pages = hpage_nr_pages(page);
1868a222f341SKirill Tkhai 		update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1869a222f341SKirill Tkhai 		list_move(&page->lru, &lruvec->lists[lru]);
1870fa9add64SHugh Dickins 
18712bcf8879SHugh Dickins 		if (put_page_testzero(page)) {
18722bcf8879SHugh Dickins 			__ClearPageLRU(page);
18732bcf8879SHugh Dickins 			__ClearPageActive(page);
1874fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, lru);
18752bcf8879SHugh Dickins 
18762bcf8879SHugh Dickins 			if (unlikely(PageCompound(page))) {
1877599d0c95SMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
18782bcf8879SHugh Dickins 				(*get_compound_page_dtor(page))(page);
1879599d0c95SMel Gorman 				spin_lock_irq(&pgdat->lru_lock);
18802bcf8879SHugh Dickins 			} else
18812bcf8879SHugh Dickins 				list_add(&page->lru, &pages_to_free);
1882a222f341SKirill Tkhai 		} else {
1883a222f341SKirill Tkhai 			nr_moved += nr_pages;
188466635629SMel Gorman 		}
188566635629SMel Gorman 	}
188666635629SMel Gorman 
18873f79768fSHugh Dickins 	/*
18883f79768fSHugh Dickins 	 * To save our caller's stack, now use input list for pages to free.
18893f79768fSHugh Dickins 	 */
1890a222f341SKirill Tkhai 	list_splice(&pages_to_free, list);
1891a222f341SKirill Tkhai 
1892a222f341SKirill Tkhai 	return nr_moved;
189366635629SMel Gorman }
189466635629SMel Gorman 
189566635629SMel Gorman /*
1896399ba0b9SNeilBrown  * If a kernel thread (such as nfsd for loop-back mounts) services
1897399ba0b9SNeilBrown  * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1898399ba0b9SNeilBrown  * In that case we should only throttle if the backing device it is
1899399ba0b9SNeilBrown  * writing to is congested.  In other cases it is safe to throttle.
1900399ba0b9SNeilBrown  */
1901399ba0b9SNeilBrown static int current_may_throttle(void)
1902399ba0b9SNeilBrown {
1903399ba0b9SNeilBrown 	return !(current->flags & PF_LESS_THROTTLE) ||
1904399ba0b9SNeilBrown 		current->backing_dev_info == NULL ||
1905399ba0b9SNeilBrown 		bdi_write_congested(current->backing_dev_info);
1906399ba0b9SNeilBrown }
1907399ba0b9SNeilBrown 
1908399ba0b9SNeilBrown /*
1909b2e18757SMel Gorman  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
19101742f19fSAndrew Morton  * of reclaimed pages
19111da177e4SLinus Torvalds  */
191266635629SMel Gorman static noinline_for_stack unsigned long
19131a93be0eSKonstantin Khlebnikov shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
19149e3b2f8cSKonstantin Khlebnikov 		     struct scan_control *sc, enum lru_list lru)
19151da177e4SLinus Torvalds {
19161da177e4SLinus Torvalds 	LIST_HEAD(page_list);
1917e247dbceSKOSAKI Motohiro 	unsigned long nr_scanned;
191805ff5137SAndrew Morton 	unsigned long nr_reclaimed = 0;
1919e247dbceSKOSAKI Motohiro 	unsigned long nr_taken;
1920060f005fSKirill Tkhai 	struct reclaim_stat stat;
19213cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
1922f46b7912SKirill Tkhai 	enum vm_event_item item;
1923599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
19241a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1925db73ee0dSMichal Hocko 	bool stalled = false;
192678dc583dSKOSAKI Motohiro 
1927599d0c95SMel Gorman 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
1928db73ee0dSMichal Hocko 		if (stalled)
1929db73ee0dSMichal Hocko 			return 0;
1930db73ee0dSMichal Hocko 
1931db73ee0dSMichal Hocko 		/* wait a bit for the reclaimer. */
1932db73ee0dSMichal Hocko 		msleep(100);
1933db73ee0dSMichal Hocko 		stalled = true;
193435cd7815SRik van Riel 
193535cd7815SRik van Riel 		/* We are about to die and free our memory. Return now. */
193635cd7815SRik van Riel 		if (fatal_signal_pending(current))
193735cd7815SRik van Riel 			return SWAP_CLUSTER_MAX;
193835cd7815SRik van Riel 	}
193935cd7815SRik van Riel 
19401da177e4SLinus Torvalds 	lru_add_drain();
1941f80c0673SMinchan Kim 
1942599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19431da177e4SLinus Torvalds 
19445dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1945a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
194695d918fcSKonstantin Khlebnikov 
1947599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
19489d5e6a9fSHugh Dickins 	reclaim_stat->recent_scanned[file] += nr_taken;
194995d918fcSKonstantin Khlebnikov 
1950f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1951b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1952f46b7912SKirill Tkhai 		__count_vm_events(item, nr_scanned);
1953f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1954599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
1955d563c050SHillf Danton 
1956d563c050SHillf Danton 	if (nr_taken == 0)
195766635629SMel Gorman 		return 0;
1958b35ea17bSKOSAKI Motohiro 
1959a128ca71SShaohua Li 	nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, 0,
19603c710c1aSMichal Hocko 				&stat, false);
1961c661b078SAndy Whitcroft 
1962599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
19633f79768fSHugh Dickins 
1964f46b7912SKirill Tkhai 	item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1965b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
1966f46b7912SKirill Tkhai 		__count_vm_events(item, nr_reclaimed);
1967f46b7912SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1968b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1969b17f18afSKirill Tkhai 	reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1970a74609faSNick Piggin 
1971a222f341SKirill Tkhai 	move_pages_to_lru(lruvec, &page_list);
19723f79768fSHugh Dickins 
1973599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
19743f79768fSHugh Dickins 
1975599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
19763f79768fSHugh Dickins 
1977747db954SJohannes Weiner 	mem_cgroup_uncharge_list(&page_list);
19782d4894b5SMel Gorman 	free_unref_page_list(&page_list);
1979e11da5b4SMel Gorman 
198092df3a72SMel Gorman 	/*
19811c610d5fSAndrey Ryabinin 	 * If dirty pages are scanned that are not queued for IO, it
19821c610d5fSAndrey Ryabinin 	 * implies that flushers are not doing their job. This can
19831c610d5fSAndrey Ryabinin 	 * happen when memory pressure pushes dirty pages to the end of
19841c610d5fSAndrey Ryabinin 	 * the LRU before the dirty limits are breached and the dirty
19851c610d5fSAndrey Ryabinin 	 * data has expired. It can also happen when the proportion of
19861c610d5fSAndrey Ryabinin 	 * dirty pages grows not through writes but through memory
19871c610d5fSAndrey Ryabinin 	 * pressure reclaiming all the clean cache. And in some cases,
19881c610d5fSAndrey Ryabinin 	 * the flushers simply cannot keep up with the allocation
19891c610d5fSAndrey Ryabinin 	 * rate. Nudge the flusher threads in case they are asleep.
19901c610d5fSAndrey Ryabinin 	 */
19911c610d5fSAndrey Ryabinin 	if (stat.nr_unqueued_dirty == nr_taken)
19921c610d5fSAndrey Ryabinin 		wakeup_flusher_threads(WB_REASON_VMSCAN);
19931c610d5fSAndrey Ryabinin 
1994d108c772SAndrey Ryabinin 	sc->nr.dirty += stat.nr_dirty;
1995d108c772SAndrey Ryabinin 	sc->nr.congested += stat.nr_congested;
1996d108c772SAndrey Ryabinin 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
1997d108c772SAndrey Ryabinin 	sc->nr.writeback += stat.nr_writeback;
1998d108c772SAndrey Ryabinin 	sc->nr.immediate += stat.nr_immediate;
1999d108c772SAndrey Ryabinin 	sc->nr.taken += nr_taken;
2000d108c772SAndrey Ryabinin 	if (file)
2001d108c772SAndrey Ryabinin 		sc->nr.file_taken += nr_taken;
20028e950282SMel Gorman 
2003599d0c95SMel Gorman 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2004d51d1e64SSteven Rostedt 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
200505ff5137SAndrew Morton 	return nr_reclaimed;
20061da177e4SLinus Torvalds }
20071da177e4SLinus Torvalds 
2008f626012dSHugh Dickins static void shrink_active_list(unsigned long nr_to_scan,
20091a93be0eSKonstantin Khlebnikov 			       struct lruvec *lruvec,
2010f16015fbSJohannes Weiner 			       struct scan_control *sc,
20119e3b2f8cSKonstantin Khlebnikov 			       enum lru_list lru)
20121cfb419bSKAMEZAWA Hiroyuki {
201344c241f1SKOSAKI Motohiro 	unsigned long nr_taken;
2014f626012dSHugh Dickins 	unsigned long nr_scanned;
20156fe6b7e3SWu Fengguang 	unsigned long vm_flags;
20161cfb419bSKAMEZAWA Hiroyuki 	LIST_HEAD(l_hold);	/* The pages which were snipped off */
20178cab4754SWu Fengguang 	LIST_HEAD(l_active);
2018b69408e8SChristoph Lameter 	LIST_HEAD(l_inactive);
20191cfb419bSKAMEZAWA Hiroyuki 	struct page *page;
20201a93be0eSKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
20219d998b4fSMichal Hocko 	unsigned nr_deactivate, nr_activate;
20229d998b4fSMichal Hocko 	unsigned nr_rotated = 0;
20233cb99451SKonstantin Khlebnikov 	int file = is_file_lru(lru);
2024599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
20251cfb419bSKAMEZAWA Hiroyuki 
20261da177e4SLinus Torvalds 	lru_add_drain();
2027f80c0673SMinchan Kim 
2028599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
2029925b7673SJohannes Weiner 
20305dc35979SKonstantin Khlebnikov 	nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2031a9e7c39fSKirill Tkhai 				     &nr_scanned, sc, lru);
203289b5fae5SJohannes Weiner 
2033599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2034b7c46d15SJohannes Weiner 	reclaim_stat->recent_scanned[file] += nr_taken;
20351cfb419bSKAMEZAWA Hiroyuki 
2036599d0c95SMel Gorman 	__count_vm_events(PGREFILL, nr_scanned);
20372fa2690cSYafang Shao 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
20389d5e6a9fSHugh Dickins 
2039599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
20401da177e4SLinus Torvalds 
20411da177e4SLinus Torvalds 	while (!list_empty(&l_hold)) {
20421da177e4SLinus Torvalds 		cond_resched();
20431da177e4SLinus Torvalds 		page = lru_to_page(&l_hold);
20441da177e4SLinus Torvalds 		list_del(&page->lru);
20457e9cd484SRik van Riel 
204639b5f29aSHugh Dickins 		if (unlikely(!page_evictable(page))) {
2047894bc310SLee Schermerhorn 			putback_lru_page(page);
2048894bc310SLee Schermerhorn 			continue;
2049894bc310SLee Schermerhorn 		}
2050894bc310SLee Schermerhorn 
2051cc715d99SMel Gorman 		if (unlikely(buffer_heads_over_limit)) {
2052cc715d99SMel Gorman 			if (page_has_private(page) && trylock_page(page)) {
2053cc715d99SMel Gorman 				if (page_has_private(page))
2054cc715d99SMel Gorman 					try_to_release_page(page, 0);
2055cc715d99SMel Gorman 				unlock_page(page);
2056cc715d99SMel Gorman 			}
2057cc715d99SMel Gorman 		}
2058cc715d99SMel Gorman 
2059c3ac9a8aSJohannes Weiner 		if (page_referenced(page, 0, sc->target_mem_cgroup,
2060c3ac9a8aSJohannes Weiner 				    &vm_flags)) {
20619992af10SRik van Riel 			nr_rotated += hpage_nr_pages(page);
20628cab4754SWu Fengguang 			/*
20638cab4754SWu Fengguang 			 * Identify referenced, file-backed active pages and
20648cab4754SWu Fengguang 			 * give them one more trip around the active list. So
20658cab4754SWu Fengguang 			 * that executable code get better chances to stay in
20668cab4754SWu Fengguang 			 * memory under moderate memory pressure.  Anon pages
20678cab4754SWu Fengguang 			 * are not likely to be evicted by use-once streaming
20688cab4754SWu Fengguang 			 * IO, plus JVM can create lots of anon VM_EXEC pages,
20698cab4754SWu Fengguang 			 * so we ignore them here.
20708cab4754SWu Fengguang 			 */
207141e20983SWu Fengguang 			if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
20728cab4754SWu Fengguang 				list_add(&page->lru, &l_active);
20738cab4754SWu Fengguang 				continue;
20748cab4754SWu Fengguang 			}
20758cab4754SWu Fengguang 		}
20767e9cd484SRik van Riel 
20775205e56eSKOSAKI Motohiro 		ClearPageActive(page);	/* we are de-activating */
20781899ad18SJohannes Weiner 		SetPageWorkingset(page);
20791da177e4SLinus Torvalds 		list_add(&page->lru, &l_inactive);
20801da177e4SLinus Torvalds 	}
20811da177e4SLinus Torvalds 
2082b555749aSAndrew Morton 	/*
20838cab4754SWu Fengguang 	 * Move pages back to the lru list.
2084b555749aSAndrew Morton 	 */
2085599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
20864f98a2feSRik van Riel 	/*
20878cab4754SWu Fengguang 	 * Count referenced pages from currently used mappings as rotated,
20888cab4754SWu Fengguang 	 * even though only some of them are actually re-activated.  This
20898cab4754SWu Fengguang 	 * helps balance scan pressure between file and anonymous pages in
20907c0db9e9SJerome Marchand 	 * get_scan_count.
2091556adecbSRik van Riel 	 */
2092b7c46d15SJohannes Weiner 	reclaim_stat->recent_rotated[file] += nr_rotated;
2093556adecbSRik van Riel 
2094a222f341SKirill Tkhai 	nr_activate = move_pages_to_lru(lruvec, &l_active);
2095a222f341SKirill Tkhai 	nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2096f372d89eSKirill Tkhai 	/* Keep all free pages in l_active list */
2097f372d89eSKirill Tkhai 	list_splice(&l_inactive, &l_active);
20989851ac13SKirill Tkhai 
20999851ac13SKirill Tkhai 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
21009851ac13SKirill Tkhai 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
21019851ac13SKirill Tkhai 
2102599d0c95SMel Gorman 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2103599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
21042bcf8879SHugh Dickins 
2105f372d89eSKirill Tkhai 	mem_cgroup_uncharge_list(&l_active);
2106f372d89eSKirill Tkhai 	free_unref_page_list(&l_active);
21079d998b4fSMichal Hocko 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
21089d998b4fSMichal Hocko 			nr_deactivate, nr_rotated, sc->priority, file);
21091da177e4SLinus Torvalds }
21101da177e4SLinus Torvalds 
21111a4e58ccSMinchan Kim unsigned long reclaim_pages(struct list_head *page_list)
21121a4e58ccSMinchan Kim {
21131a4e58ccSMinchan Kim 	int nid = -1;
21141a4e58ccSMinchan Kim 	unsigned long nr_reclaimed = 0;
21151a4e58ccSMinchan Kim 	LIST_HEAD(node_page_list);
21161a4e58ccSMinchan Kim 	struct reclaim_stat dummy_stat;
21171a4e58ccSMinchan Kim 	struct page *page;
21181a4e58ccSMinchan Kim 	struct scan_control sc = {
21191a4e58ccSMinchan Kim 		.gfp_mask = GFP_KERNEL,
21201a4e58ccSMinchan Kim 		.priority = DEF_PRIORITY,
21211a4e58ccSMinchan Kim 		.may_writepage = 1,
21221a4e58ccSMinchan Kim 		.may_unmap = 1,
21231a4e58ccSMinchan Kim 		.may_swap = 1,
21241a4e58ccSMinchan Kim 	};
21251a4e58ccSMinchan Kim 
21261a4e58ccSMinchan Kim 	while (!list_empty(page_list)) {
21271a4e58ccSMinchan Kim 		page = lru_to_page(page_list);
21281a4e58ccSMinchan Kim 		if (nid == -1) {
21291a4e58ccSMinchan Kim 			nid = page_to_nid(page);
21301a4e58ccSMinchan Kim 			INIT_LIST_HEAD(&node_page_list);
21311a4e58ccSMinchan Kim 		}
21321a4e58ccSMinchan Kim 
21331a4e58ccSMinchan Kim 		if (nid == page_to_nid(page)) {
21341a4e58ccSMinchan Kim 			ClearPageActive(page);
21351a4e58ccSMinchan Kim 			list_move(&page->lru, &node_page_list);
21361a4e58ccSMinchan Kim 			continue;
21371a4e58ccSMinchan Kim 		}
21381a4e58ccSMinchan Kim 
21391a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21401a4e58ccSMinchan Kim 						NODE_DATA(nid),
21411a4e58ccSMinchan Kim 						&sc, 0,
21421a4e58ccSMinchan Kim 						&dummy_stat, false);
21431a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21441a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21451a4e58ccSMinchan Kim 			list_del(&page->lru);
21461a4e58ccSMinchan Kim 			putback_lru_page(page);
21471a4e58ccSMinchan Kim 		}
21481a4e58ccSMinchan Kim 
21491a4e58ccSMinchan Kim 		nid = -1;
21501a4e58ccSMinchan Kim 	}
21511a4e58ccSMinchan Kim 
21521a4e58ccSMinchan Kim 	if (!list_empty(&node_page_list)) {
21531a4e58ccSMinchan Kim 		nr_reclaimed += shrink_page_list(&node_page_list,
21541a4e58ccSMinchan Kim 						NODE_DATA(nid),
21551a4e58ccSMinchan Kim 						&sc, 0,
21561a4e58ccSMinchan Kim 						&dummy_stat, false);
21571a4e58ccSMinchan Kim 		while (!list_empty(&node_page_list)) {
21581a4e58ccSMinchan Kim 			page = lru_to_page(&node_page_list);
21591a4e58ccSMinchan Kim 			list_del(&page->lru);
21601a4e58ccSMinchan Kim 			putback_lru_page(page);
21611a4e58ccSMinchan Kim 		}
21621a4e58ccSMinchan Kim 	}
21631a4e58ccSMinchan Kim 
21641a4e58ccSMinchan Kim 	return nr_reclaimed;
21651a4e58ccSMinchan Kim }
21661a4e58ccSMinchan Kim 
2167b91ac374SJohannes Weiner static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2168b91ac374SJohannes Weiner 				 struct lruvec *lruvec, struct scan_control *sc)
2169b91ac374SJohannes Weiner {
2170b91ac374SJohannes Weiner 	if (is_active_lru(lru)) {
2171b91ac374SJohannes Weiner 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2172b91ac374SJohannes Weiner 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2173b91ac374SJohannes Weiner 		else
2174b91ac374SJohannes Weiner 			sc->skipped_deactivate = 1;
2175b91ac374SJohannes Weiner 		return 0;
2176b91ac374SJohannes Weiner 	}
2177b91ac374SJohannes Weiner 
2178b91ac374SJohannes Weiner 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2179b91ac374SJohannes Weiner }
2180b91ac374SJohannes Weiner 
218159dc76b0SRik van Riel /*
218259dc76b0SRik van Riel  * The inactive anon list should be small enough that the VM never has
218359dc76b0SRik van Riel  * to do too much work.
218414797e23SKOSAKI Motohiro  *
218559dc76b0SRik van Riel  * The inactive file list should be small enough to leave most memory
218659dc76b0SRik van Riel  * to the established workingset on the scan-resistant active list,
218759dc76b0SRik van Riel  * but large enough to avoid thrashing the aggregate readahead window.
218859dc76b0SRik van Riel  *
218959dc76b0SRik van Riel  * Both inactive lists should also be large enough that each inactive
219059dc76b0SRik van Riel  * page has a chance to be referenced again before it is reclaimed.
219159dc76b0SRik van Riel  *
21922a2e4885SJohannes Weiner  * If that fails and refaulting is observed, the inactive list grows.
21932a2e4885SJohannes Weiner  *
219459dc76b0SRik van Riel  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
21953a50d14dSAndrey Ryabinin  * on this LRU, maintained by the pageout code. An inactive_ratio
219659dc76b0SRik van Riel  * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
219759dc76b0SRik van Riel  *
219859dc76b0SRik van Riel  * total     target    max
219959dc76b0SRik van Riel  * memory    ratio     inactive
220059dc76b0SRik van Riel  * -------------------------------------
220159dc76b0SRik van Riel  *   10MB       1         5MB
220259dc76b0SRik van Riel  *  100MB       1        50MB
220359dc76b0SRik van Riel  *    1GB       3       250MB
220459dc76b0SRik van Riel  *   10GB      10       0.9GB
220559dc76b0SRik van Riel  *  100GB      31         3GB
220659dc76b0SRik van Riel  *    1TB     101        10GB
220759dc76b0SRik van Riel  *   10TB     320        32GB
220814797e23SKOSAKI Motohiro  */
2209b91ac374SJohannes Weiner static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
221014797e23SKOSAKI Motohiro {
2211b91ac374SJohannes Weiner 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
22122a2e4885SJohannes Weiner 	unsigned long inactive, active;
22132a2e4885SJohannes Weiner 	unsigned long inactive_ratio;
221459dc76b0SRik van Riel 	unsigned long gb;
221559dc76b0SRik van Riel 
2216b91ac374SJohannes Weiner 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2217b91ac374SJohannes Weiner 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2218f8d1a311SMel Gorman 
221959dc76b0SRik van Riel 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
222059dc76b0SRik van Riel 	if (gb)
222159dc76b0SRik van Riel 		inactive_ratio = int_sqrt(10 * gb);
2222b39415b2SRik van Riel 	else
222359dc76b0SRik van Riel 		inactive_ratio = 1;
2224fd538803SMichal Hocko 
222559dc76b0SRik van Riel 	return inactive * inactive_ratio < active;
2226b39415b2SRik van Riel }
2227b39415b2SRik van Riel 
22289a265114SJohannes Weiner enum scan_balance {
22299a265114SJohannes Weiner 	SCAN_EQUAL,
22309a265114SJohannes Weiner 	SCAN_FRACT,
22319a265114SJohannes Weiner 	SCAN_ANON,
22329a265114SJohannes Weiner 	SCAN_FILE,
22339a265114SJohannes Weiner };
22349a265114SJohannes Weiner 
22351da177e4SLinus Torvalds /*
22364f98a2feSRik van Riel  * Determine how aggressively the anon and file LRU lists should be
22374f98a2feSRik van Riel  * scanned.  The relative value of each set of LRU lists is determined
22384f98a2feSRik van Riel  * by looking at the fraction of the pages scanned we did rotate back
22394f98a2feSRik van Riel  * onto the active list instead of evict.
22404f98a2feSRik van Riel  *
2241be7bd59dSWanpeng Li  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2242be7bd59dSWanpeng Li  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
22434f98a2feSRik van Riel  */
2244afaf07a6SJohannes Weiner static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2245afaf07a6SJohannes Weiner 			   unsigned long *nr)
22464f98a2feSRik van Riel {
2247afaf07a6SJohannes Weiner 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
224833377678SVladimir Davydov 	int swappiness = mem_cgroup_swappiness(memcg);
224990126375SKonstantin Khlebnikov 	struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
22509a265114SJohannes Weiner 	u64 fraction[2];
22519a265114SJohannes Weiner 	u64 denominator = 0;	/* gcc */
2252599d0c95SMel Gorman 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
22539a265114SJohannes Weiner 	unsigned long anon_prio, file_prio;
22549a265114SJohannes Weiner 	enum scan_balance scan_balance;
22550bf1457fSJohannes Weiner 	unsigned long anon, file;
22569a265114SJohannes Weiner 	unsigned long ap, fp;
22579a265114SJohannes Weiner 	enum lru_list lru;
225876a33fc3SShaohua Li 
225976a33fc3SShaohua Li 	/* If we have no swap space, do not bother scanning anon pages. */
2260d8b38438SVladimir Davydov 	if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
22619a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
226276a33fc3SShaohua Li 		goto out;
226376a33fc3SShaohua Li 	}
22644f98a2feSRik van Riel 
226510316b31SJohannes Weiner 	/*
226610316b31SJohannes Weiner 	 * Global reclaim will swap to prevent OOM even with no
226710316b31SJohannes Weiner 	 * swappiness, but memcg users want to use this knob to
226810316b31SJohannes Weiner 	 * disable swapping for individual groups completely when
226910316b31SJohannes Weiner 	 * using the memory controller's swap limit feature would be
227010316b31SJohannes Weiner 	 * too expensive.
227110316b31SJohannes Weiner 	 */
2272b5ead35eSJohannes Weiner 	if (cgroup_reclaim(sc) && !swappiness) {
22739a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
227410316b31SJohannes Weiner 		goto out;
227510316b31SJohannes Weiner 	}
227610316b31SJohannes Weiner 
227710316b31SJohannes Weiner 	/*
227810316b31SJohannes Weiner 	 * Do not apply any pressure balancing cleverness when the
227910316b31SJohannes Weiner 	 * system is close to OOM, scan both anon and file equally
228010316b31SJohannes Weiner 	 * (unless the swappiness setting disagrees with swapping).
228110316b31SJohannes Weiner 	 */
228202695175SJohannes Weiner 	if (!sc->priority && swappiness) {
22839a265114SJohannes Weiner 		scan_balance = SCAN_EQUAL;
228410316b31SJohannes Weiner 		goto out;
228510316b31SJohannes Weiner 	}
228610316b31SJohannes Weiner 
228711d16c25SJohannes Weiner 	/*
228853138ceaSJohannes Weiner 	 * If the system is almost out of file pages, force-scan anon.
228962376251SJohannes Weiner 	 */
2290b91ac374SJohannes Weiner 	if (sc->file_is_tiny) {
229162376251SJohannes Weiner 		scan_balance = SCAN_ANON;
229262376251SJohannes Weiner 		goto out;
229362376251SJohannes Weiner 	}
229462376251SJohannes Weiner 
229562376251SJohannes Weiner 	/*
2296b91ac374SJohannes Weiner 	 * If there is enough inactive page cache, we do not reclaim
2297b91ac374SJohannes Weiner 	 * anything from the anonymous working right now.
2298e9868505SRik van Riel 	 */
2299b91ac374SJohannes Weiner 	if (sc->cache_trim_mode) {
23009a265114SJohannes Weiner 		scan_balance = SCAN_FILE;
2301e9868505SRik van Riel 		goto out;
23024f98a2feSRik van Riel 	}
23034f98a2feSRik van Riel 
23049a265114SJohannes Weiner 	scan_balance = SCAN_FRACT;
23059a265114SJohannes Weiner 
23064f98a2feSRik van Riel 	/*
230758c37f6eSKOSAKI Motohiro 	 * With swappiness at 100, anonymous and file have the same priority.
230858c37f6eSKOSAKI Motohiro 	 * This scanning priority is essentially the inverse of IO cost.
230958c37f6eSKOSAKI Motohiro 	 */
231002695175SJohannes Weiner 	anon_prio = swappiness;
231175b00af7SHugh Dickins 	file_prio = 200 - anon_prio;
231258c37f6eSKOSAKI Motohiro 
231358c37f6eSKOSAKI Motohiro 	/*
23144f98a2feSRik van Riel 	 * OK, so we have swap space and a fair amount of page cache
23154f98a2feSRik van Riel 	 * pages.  We use the recently rotated / recently scanned
23164f98a2feSRik van Riel 	 * ratios to determine how valuable each cache is.
23174f98a2feSRik van Riel 	 *
23184f98a2feSRik van Riel 	 * Because workloads change over time (and to avoid overflow)
23194f98a2feSRik van Riel 	 * we keep these statistics as a floating average, which ends
23204f98a2feSRik van Riel 	 * up weighing recent references more than old ones.
23214f98a2feSRik van Riel 	 *
23224f98a2feSRik van Riel 	 * anon in [0], file in [1]
23234f98a2feSRik van Riel 	 */
23242ab051e1SJerome Marchand 
2325fd538803SMichal Hocko 	anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2326fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2327fd538803SMichal Hocko 	file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2328fd538803SMichal Hocko 		lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
23292ab051e1SJerome Marchand 
2330599d0c95SMel Gorman 	spin_lock_irq(&pgdat->lru_lock);
233158c37f6eSKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
23326e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[0] /= 2;
23336e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[0] /= 2;
23344f98a2feSRik van Riel 	}
23354f98a2feSRik van Riel 
23366e901571SKOSAKI Motohiro 	if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
23376e901571SKOSAKI Motohiro 		reclaim_stat->recent_scanned[1] /= 2;
23386e901571SKOSAKI Motohiro 		reclaim_stat->recent_rotated[1] /= 2;
23394f98a2feSRik van Riel 	}
23404f98a2feSRik van Riel 
23414f98a2feSRik van Riel 	/*
234200d8089cSRik van Riel 	 * The amount of pressure on anon vs file pages is inversely
234300d8089cSRik van Riel 	 * proportional to the fraction of recently scanned pages on
234400d8089cSRik van Riel 	 * each list that were recently referenced and in active use.
23454f98a2feSRik van Riel 	 */
2346fe35004fSSatoru Moriya 	ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
23476e901571SKOSAKI Motohiro 	ap /= reclaim_stat->recent_rotated[0] + 1;
23484f98a2feSRik van Riel 
2349fe35004fSSatoru Moriya 	fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
23506e901571SKOSAKI Motohiro 	fp /= reclaim_stat->recent_rotated[1] + 1;
2351599d0c95SMel Gorman 	spin_unlock_irq(&pgdat->lru_lock);
23524f98a2feSRik van Riel 
235376a33fc3SShaohua Li 	fraction[0] = ap;
235476a33fc3SShaohua Li 	fraction[1] = fp;
235576a33fc3SShaohua Li 	denominator = ap + fp + 1;
235676a33fc3SShaohua Li out:
23574111304dSHugh Dickins 	for_each_evictable_lru(lru) {
23584111304dSHugh Dickins 		int file = is_file_lru(lru);
23599783aa99SChris Down 		unsigned long lruvec_size;
236076a33fc3SShaohua Li 		unsigned long scan;
23611bc63fb1SChris Down 		unsigned long protection;
236276a33fc3SShaohua Li 
23639783aa99SChris Down 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
23641bc63fb1SChris Down 		protection = mem_cgroup_protection(memcg,
23651bc63fb1SChris Down 						   sc->memcg_low_reclaim);
23669783aa99SChris Down 
23671bc63fb1SChris Down 		if (protection) {
23689783aa99SChris Down 			/*
23699783aa99SChris Down 			 * Scale a cgroup's reclaim pressure by proportioning
23709783aa99SChris Down 			 * its current usage to its memory.low or memory.min
23719783aa99SChris Down 			 * setting.
23729783aa99SChris Down 			 *
23739783aa99SChris Down 			 * This is important, as otherwise scanning aggression
23749783aa99SChris Down 			 * becomes extremely binary -- from nothing as we
23759783aa99SChris Down 			 * approach the memory protection threshold, to totally
23769783aa99SChris Down 			 * nominal as we exceed it.  This results in requiring
23779783aa99SChris Down 			 * setting extremely liberal protection thresholds. It
23789783aa99SChris Down 			 * also means we simply get no protection at all if we
23799783aa99SChris Down 			 * set it too low, which is not ideal.
23801bc63fb1SChris Down 			 *
23811bc63fb1SChris Down 			 * If there is any protection in place, we reduce scan
23821bc63fb1SChris Down 			 * pressure by how much of the total memory used is
23831bc63fb1SChris Down 			 * within protection thresholds.
23849783aa99SChris Down 			 *
23859de7ca46SChris Down 			 * There is one special case: in the first reclaim pass,
23869de7ca46SChris Down 			 * we skip over all groups that are within their low
23879de7ca46SChris Down 			 * protection. If that fails to reclaim enough pages to
23889de7ca46SChris Down 			 * satisfy the reclaim goal, we come back and override
23899de7ca46SChris Down 			 * the best-effort low protection. However, we still
23909de7ca46SChris Down 			 * ideally want to honor how well-behaved groups are in
23919de7ca46SChris Down 			 * that case instead of simply punishing them all
23929de7ca46SChris Down 			 * equally. As such, we reclaim them based on how much
23931bc63fb1SChris Down 			 * memory they are using, reducing the scan pressure
23941bc63fb1SChris Down 			 * again by how much of the total memory used is under
23951bc63fb1SChris Down 			 * hard protection.
23969783aa99SChris Down 			 */
23971bc63fb1SChris Down 			unsigned long cgroup_size = mem_cgroup_size(memcg);
23981bc63fb1SChris Down 
23991bc63fb1SChris Down 			/* Avoid TOCTOU with earlier protection check */
24001bc63fb1SChris Down 			cgroup_size = max(cgroup_size, protection);
24011bc63fb1SChris Down 
24021bc63fb1SChris Down 			scan = lruvec_size - lruvec_size * protection /
24031bc63fb1SChris Down 				cgroup_size;
24049783aa99SChris Down 
24059783aa99SChris Down 			/*
24061bc63fb1SChris Down 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
24079de7ca46SChris Down 			 * reclaim moving forwards, avoiding decremeting
24089de7ca46SChris Down 			 * sc->priority further than desirable.
24099783aa99SChris Down 			 */
24101bc63fb1SChris Down 			scan = max(scan, SWAP_CLUSTER_MAX);
24119783aa99SChris Down 		} else {
24129783aa99SChris Down 			scan = lruvec_size;
24139783aa99SChris Down 		}
24149783aa99SChris Down 
24159783aa99SChris Down 		scan >>= sc->priority;
24169783aa99SChris Down 
2417688035f7SJohannes Weiner 		/*
2418688035f7SJohannes Weiner 		 * If the cgroup's already been deleted, make sure to
2419688035f7SJohannes Weiner 		 * scrape out the remaining cache.
2420688035f7SJohannes Weiner 		 */
2421688035f7SJohannes Weiner 		if (!scan && !mem_cgroup_online(memcg))
24229783aa99SChris Down 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
24239a265114SJohannes Weiner 
24249a265114SJohannes Weiner 		switch (scan_balance) {
24259a265114SJohannes Weiner 		case SCAN_EQUAL:
24269a265114SJohannes Weiner 			/* Scan lists relative to size */
24279a265114SJohannes Weiner 			break;
24289a265114SJohannes Weiner 		case SCAN_FRACT:
24299a265114SJohannes Weiner 			/*
24309a265114SJohannes Weiner 			 * Scan types proportional to swappiness and
24319a265114SJohannes Weiner 			 * their relative recent reclaim efficiency.
243268600f62SRoman Gushchin 			 * Make sure we don't miss the last page
243368600f62SRoman Gushchin 			 * because of a round-off error.
24349a265114SJohannes Weiner 			 */
243568600f62SRoman Gushchin 			scan = DIV64_U64_ROUND_UP(scan * fraction[file],
24366f04f48dSSuleiman Souhlal 						  denominator);
24379a265114SJohannes Weiner 			break;
24389a265114SJohannes Weiner 		case SCAN_FILE:
24399a265114SJohannes Weiner 		case SCAN_ANON:
24409a265114SJohannes Weiner 			/* Scan one type exclusively */
24416b4f7799SJohannes Weiner 			if ((scan_balance == SCAN_FILE) != file) {
24429783aa99SChris Down 				lruvec_size = 0;
24439a265114SJohannes Weiner 				scan = 0;
24446b4f7799SJohannes Weiner 			}
24459a265114SJohannes Weiner 			break;
24469a265114SJohannes Weiner 		default:
24479a265114SJohannes Weiner 			/* Look ma, no brain */
24489a265114SJohannes Weiner 			BUG();
24499a265114SJohannes Weiner 		}
24506b4f7799SJohannes Weiner 
24514111304dSHugh Dickins 		nr[lru] = scan;
245276a33fc3SShaohua Li 	}
24536e08a369SWu Fengguang }
24544f98a2feSRik van Riel 
2455afaf07a6SJohannes Weiner static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
24569b4f98cdSJohannes Weiner {
24579b4f98cdSJohannes Weiner 	unsigned long nr[NR_LRU_LISTS];
2458e82e0561SMel Gorman 	unsigned long targets[NR_LRU_LISTS];
24599b4f98cdSJohannes Weiner 	unsigned long nr_to_scan;
24609b4f98cdSJohannes Weiner 	enum lru_list lru;
24619b4f98cdSJohannes Weiner 	unsigned long nr_reclaimed = 0;
24629b4f98cdSJohannes Weiner 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
24639b4f98cdSJohannes Weiner 	struct blk_plug plug;
24641a501907SMel Gorman 	bool scan_adjusted;
24659b4f98cdSJohannes Weiner 
2466afaf07a6SJohannes Weiner 	get_scan_count(lruvec, sc, nr);
24679b4f98cdSJohannes Weiner 
2468e82e0561SMel Gorman 	/* Record the original scan target for proportional adjustments later */
2469e82e0561SMel Gorman 	memcpy(targets, nr, sizeof(nr));
2470e82e0561SMel Gorman 
24711a501907SMel Gorman 	/*
24721a501907SMel Gorman 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
24731a501907SMel Gorman 	 * event that can occur when there is little memory pressure e.g.
24741a501907SMel Gorman 	 * multiple streaming readers/writers. Hence, we do not abort scanning
24751a501907SMel Gorman 	 * when the requested number of pages are reclaimed when scanning at
24761a501907SMel Gorman 	 * DEF_PRIORITY on the assumption that the fact we are direct
24771a501907SMel Gorman 	 * reclaiming implies that kswapd is not keeping up and it is best to
24781a501907SMel Gorman 	 * do a batch of work at once. For memcg reclaim one check is made to
24791a501907SMel Gorman 	 * abort proportional reclaim if either the file or anon lru has already
24801a501907SMel Gorman 	 * dropped to zero at the first pass.
24811a501907SMel Gorman 	 */
2482b5ead35eSJohannes Weiner 	scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
24831a501907SMel Gorman 			 sc->priority == DEF_PRIORITY);
24841a501907SMel Gorman 
24859b4f98cdSJohannes Weiner 	blk_start_plug(&plug);
24869b4f98cdSJohannes Weiner 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
24879b4f98cdSJohannes Weiner 					nr[LRU_INACTIVE_FILE]) {
2488e82e0561SMel Gorman 		unsigned long nr_anon, nr_file, percentage;
2489e82e0561SMel Gorman 		unsigned long nr_scanned;
2490e82e0561SMel Gorman 
24919b4f98cdSJohannes Weiner 		for_each_evictable_lru(lru) {
24929b4f98cdSJohannes Weiner 			if (nr[lru]) {
24939b4f98cdSJohannes Weiner 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
24949b4f98cdSJohannes Weiner 				nr[lru] -= nr_to_scan;
24959b4f98cdSJohannes Weiner 
24969b4f98cdSJohannes Weiner 				nr_reclaimed += shrink_list(lru, nr_to_scan,
24973b991208SJohannes Weiner 							    lruvec, sc);
24989b4f98cdSJohannes Weiner 			}
24999b4f98cdSJohannes Weiner 		}
2500e82e0561SMel Gorman 
2501bd041733SMichal Hocko 		cond_resched();
2502bd041733SMichal Hocko 
2503e82e0561SMel Gorman 		if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2504e82e0561SMel Gorman 			continue;
2505e82e0561SMel Gorman 
25069b4f98cdSJohannes Weiner 		/*
2507e82e0561SMel Gorman 		 * For kswapd and memcg, reclaim at least the number of pages
25081a501907SMel Gorman 		 * requested. Ensure that the anon and file LRUs are scanned
2509e82e0561SMel Gorman 		 * proportionally what was requested by get_scan_count(). We
2510e82e0561SMel Gorman 		 * stop reclaiming one LRU and reduce the amount scanning
2511e82e0561SMel Gorman 		 * proportional to the original scan target.
2512e82e0561SMel Gorman 		 */
2513e82e0561SMel Gorman 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2514e82e0561SMel Gorman 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2515e82e0561SMel Gorman 
25161a501907SMel Gorman 		/*
25171a501907SMel Gorman 		 * It's just vindictive to attack the larger once the smaller
25181a501907SMel Gorman 		 * has gone to zero.  And given the way we stop scanning the
25191a501907SMel Gorman 		 * smaller below, this makes sure that we only make one nudge
25201a501907SMel Gorman 		 * towards proportionality once we've got nr_to_reclaim.
25211a501907SMel Gorman 		 */
25221a501907SMel Gorman 		if (!nr_file || !nr_anon)
25231a501907SMel Gorman 			break;
25241a501907SMel Gorman 
2525e82e0561SMel Gorman 		if (nr_file > nr_anon) {
2526e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2527e82e0561SMel Gorman 						targets[LRU_ACTIVE_ANON] + 1;
2528e82e0561SMel Gorman 			lru = LRU_BASE;
2529e82e0561SMel Gorman 			percentage = nr_anon * 100 / scan_target;
2530e82e0561SMel Gorman 		} else {
2531e82e0561SMel Gorman 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2532e82e0561SMel Gorman 						targets[LRU_ACTIVE_FILE] + 1;
2533e82e0561SMel Gorman 			lru = LRU_FILE;
2534e82e0561SMel Gorman 			percentage = nr_file * 100 / scan_target;
2535e82e0561SMel Gorman 		}
2536e82e0561SMel Gorman 
2537e82e0561SMel Gorman 		/* Stop scanning the smaller of the LRU */
2538e82e0561SMel Gorman 		nr[lru] = 0;
2539e82e0561SMel Gorman 		nr[lru + LRU_ACTIVE] = 0;
2540e82e0561SMel Gorman 
2541e82e0561SMel Gorman 		/*
2542e82e0561SMel Gorman 		 * Recalculate the other LRU scan count based on its original
2543e82e0561SMel Gorman 		 * scan target and the percentage scanning already complete
2544e82e0561SMel Gorman 		 */
2545e82e0561SMel Gorman 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2546e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2547e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2548e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2549e82e0561SMel Gorman 
2550e82e0561SMel Gorman 		lru += LRU_ACTIVE;
2551e82e0561SMel Gorman 		nr_scanned = targets[lru] - nr[lru];
2552e82e0561SMel Gorman 		nr[lru] = targets[lru] * (100 - percentage) / 100;
2553e82e0561SMel Gorman 		nr[lru] -= min(nr[lru], nr_scanned);
2554e82e0561SMel Gorman 
2555e82e0561SMel Gorman 		scan_adjusted = true;
25569b4f98cdSJohannes Weiner 	}
25579b4f98cdSJohannes Weiner 	blk_finish_plug(&plug);
25589b4f98cdSJohannes Weiner 	sc->nr_reclaimed += nr_reclaimed;
25599b4f98cdSJohannes Weiner 
25609b4f98cdSJohannes Weiner 	/*
25619b4f98cdSJohannes Weiner 	 * Even if we did not try to evict anon pages at all, we want to
25629b4f98cdSJohannes Weiner 	 * rebalance the anon lru active/inactive ratio.
25639b4f98cdSJohannes Weiner 	 */
2564b91ac374SJohannes Weiner 	if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
25659b4f98cdSJohannes Weiner 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
25669b4f98cdSJohannes Weiner 				   sc, LRU_ACTIVE_ANON);
25679b4f98cdSJohannes Weiner }
25689b4f98cdSJohannes Weiner 
256923b9da55SMel Gorman /* Use reclaim/compaction for costly allocs or under memory pressure */
25709e3b2f8cSKonstantin Khlebnikov static bool in_reclaim_compaction(struct scan_control *sc)
257123b9da55SMel Gorman {
2572d84da3f9SKirill A. Shutemov 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
257323b9da55SMel Gorman 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
25749e3b2f8cSKonstantin Khlebnikov 			 sc->priority < DEF_PRIORITY - 2))
257523b9da55SMel Gorman 		return true;
257623b9da55SMel Gorman 
257723b9da55SMel Gorman 	return false;
257823b9da55SMel Gorman }
257923b9da55SMel Gorman 
25804f98a2feSRik van Riel /*
258123b9da55SMel Gorman  * Reclaim/compaction is used for high-order allocation requests. It reclaims
258223b9da55SMel Gorman  * order-0 pages before compacting the zone. should_continue_reclaim() returns
258323b9da55SMel Gorman  * true if more pages should be reclaimed such that when the page allocator
258423b9da55SMel Gorman  * calls try_to_compact_zone() that it will have enough free pages to succeed.
258523b9da55SMel Gorman  * It will give up earlier than that if there is difficulty reclaiming pages.
25863e7d3449SMel Gorman  */
2587a9dd0a83SMel Gorman static inline bool should_continue_reclaim(struct pglist_data *pgdat,
25883e7d3449SMel Gorman 					unsigned long nr_reclaimed,
25893e7d3449SMel Gorman 					struct scan_control *sc)
25903e7d3449SMel Gorman {
25913e7d3449SMel Gorman 	unsigned long pages_for_compaction;
25923e7d3449SMel Gorman 	unsigned long inactive_lru_pages;
2593a9dd0a83SMel Gorman 	int z;
25943e7d3449SMel Gorman 
25953e7d3449SMel Gorman 	/* If not in reclaim/compaction mode, stop */
25969e3b2f8cSKonstantin Khlebnikov 	if (!in_reclaim_compaction(sc))
25973e7d3449SMel Gorman 		return false;
25983e7d3449SMel Gorman 
25993e7d3449SMel Gorman 	/*
26005ee04716SVlastimil Babka 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
26015ee04716SVlastimil Babka 	 * number of pages that were scanned. This will return to the caller
26025ee04716SVlastimil Babka 	 * with the risk reclaim/compaction and the resulting allocation attempt
26035ee04716SVlastimil Babka 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
26045ee04716SVlastimil Babka 	 * allocations through requiring that the full LRU list has been scanned
26055ee04716SVlastimil Babka 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
26065ee04716SVlastimil Babka 	 * scan, but that approximation was wrong, and there were corner cases
26075ee04716SVlastimil Babka 	 * where always a non-zero amount of pages were scanned.
26082876592fSMel Gorman 	 */
26092876592fSMel Gorman 	if (!nr_reclaimed)
26102876592fSMel Gorman 		return false;
26113e7d3449SMel Gorman 
26123e7d3449SMel Gorman 	/* If compaction would go ahead or the allocation would succeed, stop */
2613a9dd0a83SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
2614a9dd0a83SMel Gorman 		struct zone *zone = &pgdat->node_zones[z];
26156aa303deSMel Gorman 		if (!managed_zone(zone))
2616a9dd0a83SMel Gorman 			continue;
2617a9dd0a83SMel Gorman 
2618a9dd0a83SMel Gorman 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2619cf378319SVlastimil Babka 		case COMPACT_SUCCESS:
26203e7d3449SMel Gorman 		case COMPACT_CONTINUE:
26213e7d3449SMel Gorman 			return false;
26223e7d3449SMel Gorman 		default:
2623a9dd0a83SMel Gorman 			/* check next zone */
2624a9dd0a83SMel Gorman 			;
26253e7d3449SMel Gorman 		}
26263e7d3449SMel Gorman 	}
26271c6c1597SHillf Danton 
26281c6c1597SHillf Danton 	/*
26291c6c1597SHillf Danton 	 * If we have not reclaimed enough pages for compaction and the
26301c6c1597SHillf Danton 	 * inactive lists are large enough, continue reclaiming
26311c6c1597SHillf Danton 	 */
26321c6c1597SHillf Danton 	pages_for_compaction = compact_gap(sc->order);
26331c6c1597SHillf Danton 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
26341c6c1597SHillf Danton 	if (get_nr_swap_pages() > 0)
26351c6c1597SHillf Danton 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
26361c6c1597SHillf Danton 
26375ee04716SVlastimil Babka 	return inactive_lru_pages > pages_for_compaction;
2638a9dd0a83SMel Gorman }
26393e7d3449SMel Gorman 
26400f6a5cffSJohannes Weiner static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
2641f16015fbSJohannes Weiner {
26420f6a5cffSJohannes Weiner 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
2643694fbc0fSAndrew Morton 	struct mem_cgroup *memcg;
2644d108c772SAndrey Ryabinin 
26450f6a5cffSJohannes Weiner 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
2646694fbc0fSAndrew Morton 	do {
2647afaf07a6SJohannes Weiner 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
26488e8ae645SJohannes Weiner 		unsigned long reclaimed;
2649cb731d6cSVladimir Davydov 		unsigned long scanned;
26509b4f98cdSJohannes Weiner 
26510f6a5cffSJohannes Weiner 		switch (mem_cgroup_protected(target_memcg, memcg)) {
2652bf8d5d52SRoman Gushchin 		case MEMCG_PROT_MIN:
2653bf8d5d52SRoman Gushchin 			/*
2654bf8d5d52SRoman Gushchin 			 * Hard protection.
2655bf8d5d52SRoman Gushchin 			 * If there is no reclaimable memory, OOM.
2656bf8d5d52SRoman Gushchin 			 */
2657bf8d5d52SRoman Gushchin 			continue;
2658bf8d5d52SRoman Gushchin 		case MEMCG_PROT_LOW:
2659bf8d5d52SRoman Gushchin 			/*
2660bf8d5d52SRoman Gushchin 			 * Soft protection.
2661bf8d5d52SRoman Gushchin 			 * Respect the protection only as long as
2662bf8d5d52SRoman Gushchin 			 * there is an unprotected supply
2663bf8d5d52SRoman Gushchin 			 * of reclaimable memory from other cgroups.
2664bf8d5d52SRoman Gushchin 			 */
2665d6622f63SYisheng Xie 			if (!sc->memcg_low_reclaim) {
2666d6622f63SYisheng Xie 				sc->memcg_low_skipped = 1;
2667241994edSJohannes Weiner 				continue;
2668d6622f63SYisheng Xie 			}
2669e27be240SJohannes Weiner 			memcg_memory_event(memcg, MEMCG_LOW);
2670bf8d5d52SRoman Gushchin 			break;
2671bf8d5d52SRoman Gushchin 		case MEMCG_PROT_NONE:
26729783aa99SChris Down 			/*
26739783aa99SChris Down 			 * All protection thresholds breached. We may
26749783aa99SChris Down 			 * still choose to vary the scan pressure
26759783aa99SChris Down 			 * applied based on by how much the cgroup in
26769783aa99SChris Down 			 * question has exceeded its protection
26779783aa99SChris Down 			 * thresholds (see get_scan_count).
26789783aa99SChris Down 			 */
2679bf8d5d52SRoman Gushchin 			break;
2680241994edSJohannes Weiner 		}
2681241994edSJohannes Weiner 
26828e8ae645SJohannes Weiner 		reclaimed = sc->nr_reclaimed;
2683cb731d6cSVladimir Davydov 		scanned = sc->nr_scanned;
2684afaf07a6SJohannes Weiner 
2685afaf07a6SJohannes Weiner 		shrink_lruvec(lruvec, sc);
2686f9be23d6SKonstantin Khlebnikov 
268728360f39SMel Gorman 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
268828360f39SMel Gorman 			    sc->priority);
2689cb731d6cSVladimir Davydov 
26908e8ae645SJohannes Weiner 		/* Record the group's reclaim efficiency */
26918e8ae645SJohannes Weiner 		vmpressure(sc->gfp_mask, memcg, false,
26928e8ae645SJohannes Weiner 			   sc->nr_scanned - scanned,
26938e8ae645SJohannes Weiner 			   sc->nr_reclaimed - reclaimed);
26948e8ae645SJohannes Weiner 
26950f6a5cffSJohannes Weiner 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
26960f6a5cffSJohannes Weiner }
26970f6a5cffSJohannes Weiner 
2698*6c9e0907SLiu Song static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
26990f6a5cffSJohannes Weiner {
27000f6a5cffSJohannes Weiner 	struct reclaim_state *reclaim_state = current->reclaim_state;
27010f6a5cffSJohannes Weiner 	unsigned long nr_reclaimed, nr_scanned;
27021b05117dSJohannes Weiner 	struct lruvec *target_lruvec;
27030f6a5cffSJohannes Weiner 	bool reclaimable = false;
2704b91ac374SJohannes Weiner 	unsigned long file;
27050f6a5cffSJohannes Weiner 
27061b05117dSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
27071b05117dSJohannes Weiner 
27080f6a5cffSJohannes Weiner again:
27090f6a5cffSJohannes Weiner 	memset(&sc->nr, 0, sizeof(sc->nr));
27100f6a5cffSJohannes Weiner 
27110f6a5cffSJohannes Weiner 	nr_reclaimed = sc->nr_reclaimed;
27120f6a5cffSJohannes Weiner 	nr_scanned = sc->nr_scanned;
27130f6a5cffSJohannes Weiner 
271453138ceaSJohannes Weiner 	/*
2715b91ac374SJohannes Weiner 	 * Target desirable inactive:active list ratios for the anon
2716b91ac374SJohannes Weiner 	 * and file LRU lists.
2717b91ac374SJohannes Weiner 	 */
2718b91ac374SJohannes Weiner 	if (!sc->force_deactivate) {
2719b91ac374SJohannes Weiner 		unsigned long refaults;
2720b91ac374SJohannes Weiner 
2721b91ac374SJohannes Weiner 		if (inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2722b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_ANON;
2723b91ac374SJohannes Weiner 		else
2724b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2725b91ac374SJohannes Weiner 
2726b91ac374SJohannes Weiner 		/*
2727b91ac374SJohannes Weiner 		 * When refaults are being observed, it means a new
2728b91ac374SJohannes Weiner 		 * workingset is being established. Deactivate to get
2729b91ac374SJohannes Weiner 		 * rid of any stale active pages quickly.
2730b91ac374SJohannes Weiner 		 */
2731b91ac374SJohannes Weiner 		refaults = lruvec_page_state(target_lruvec,
2732b91ac374SJohannes Weiner 					     WORKINGSET_ACTIVATE);
2733b91ac374SJohannes Weiner 		if (refaults != target_lruvec->refaults ||
2734b91ac374SJohannes Weiner 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2735b91ac374SJohannes Weiner 			sc->may_deactivate |= DEACTIVATE_FILE;
2736b91ac374SJohannes Weiner 		else
2737b91ac374SJohannes Weiner 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2738b91ac374SJohannes Weiner 	} else
2739b91ac374SJohannes Weiner 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2740b91ac374SJohannes Weiner 
2741b91ac374SJohannes Weiner 	/*
2742b91ac374SJohannes Weiner 	 * If we have plenty of inactive file pages that aren't
2743b91ac374SJohannes Weiner 	 * thrashing, try to reclaim those first before touching
2744b91ac374SJohannes Weiner 	 * anonymous pages.
2745b91ac374SJohannes Weiner 	 */
2746b91ac374SJohannes Weiner 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2747b91ac374SJohannes Weiner 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2748b91ac374SJohannes Weiner 		sc->cache_trim_mode = 1;
2749b91ac374SJohannes Weiner 	else
2750b91ac374SJohannes Weiner 		sc->cache_trim_mode = 0;
2751b91ac374SJohannes Weiner 
2752b91ac374SJohannes Weiner 	/*
275353138ceaSJohannes Weiner 	 * Prevent the reclaimer from falling into the cache trap: as
275453138ceaSJohannes Weiner 	 * cache pages start out inactive, every cache fault will tip
275553138ceaSJohannes Weiner 	 * the scan balance towards the file LRU.  And as the file LRU
275653138ceaSJohannes Weiner 	 * shrinks, so does the window for rotation from references.
275753138ceaSJohannes Weiner 	 * This means we have a runaway feedback loop where a tiny
275853138ceaSJohannes Weiner 	 * thrashing file LRU becomes infinitely more attractive than
275953138ceaSJohannes Weiner 	 * anon pages.  Try to detect this based on file LRU size.
276053138ceaSJohannes Weiner 	 */
276153138ceaSJohannes Weiner 	if (!cgroup_reclaim(sc)) {
276253138ceaSJohannes Weiner 		unsigned long total_high_wmark = 0;
2763b91ac374SJohannes Weiner 		unsigned long free, anon;
2764b91ac374SJohannes Weiner 		int z;
276553138ceaSJohannes Weiner 
276653138ceaSJohannes Weiner 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
276753138ceaSJohannes Weiner 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
276853138ceaSJohannes Weiner 			   node_page_state(pgdat, NR_INACTIVE_FILE);
276953138ceaSJohannes Weiner 
277053138ceaSJohannes Weiner 		for (z = 0; z < MAX_NR_ZONES; z++) {
277153138ceaSJohannes Weiner 			struct zone *zone = &pgdat->node_zones[z];
277253138ceaSJohannes Weiner 			if (!managed_zone(zone))
277353138ceaSJohannes Weiner 				continue;
277453138ceaSJohannes Weiner 
277553138ceaSJohannes Weiner 			total_high_wmark += high_wmark_pages(zone);
277653138ceaSJohannes Weiner 		}
277753138ceaSJohannes Weiner 
2778b91ac374SJohannes Weiner 		/*
2779b91ac374SJohannes Weiner 		 * Consider anon: if that's low too, this isn't a
2780b91ac374SJohannes Weiner 		 * runaway file reclaim problem, but rather just
2781b91ac374SJohannes Weiner 		 * extreme pressure. Reclaim as per usual then.
2782b91ac374SJohannes Weiner 		 */
2783b91ac374SJohannes Weiner 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2784b91ac374SJohannes Weiner 
2785b91ac374SJohannes Weiner 		sc->file_is_tiny =
2786b91ac374SJohannes Weiner 			file + free <= total_high_wmark &&
2787b91ac374SJohannes Weiner 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2788b91ac374SJohannes Weiner 			anon >> sc->priority;
278953138ceaSJohannes Weiner 	}
279053138ceaSJohannes Weiner 
27910f6a5cffSJohannes Weiner 	shrink_node_memcgs(pgdat, sc);
279270ddf637SAnton Vorontsov 
27936b4f7799SJohannes Weiner 	if (reclaim_state) {
2794cb731d6cSVladimir Davydov 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
27956b4f7799SJohannes Weiner 		reclaim_state->reclaimed_slab = 0;
27966b4f7799SJohannes Weiner 	}
27976b4f7799SJohannes Weiner 
27988e8ae645SJohannes Weiner 	/* Record the subtree's reclaim efficiency */
27991b05117dSJohannes Weiner 	vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
280070ddf637SAnton Vorontsov 		   sc->nr_scanned - nr_scanned,
280170ddf637SAnton Vorontsov 		   sc->nr_reclaimed - nr_reclaimed);
280270ddf637SAnton Vorontsov 
28032344d7e4SJohannes Weiner 	if (sc->nr_reclaimed - nr_reclaimed)
28042344d7e4SJohannes Weiner 		reclaimable = true;
28052344d7e4SJohannes Weiner 
2806e3c1ac58SAndrey Ryabinin 	if (current_is_kswapd()) {
2807d108c772SAndrey Ryabinin 		/*
2808e3c1ac58SAndrey Ryabinin 		 * If reclaim is isolating dirty pages under writeback,
2809e3c1ac58SAndrey Ryabinin 		 * it implies that the long-lived page allocation rate
2810e3c1ac58SAndrey Ryabinin 		 * is exceeding the page laundering rate. Either the
2811e3c1ac58SAndrey Ryabinin 		 * global limits are not being effective at throttling
2812e3c1ac58SAndrey Ryabinin 		 * processes due to the page distribution throughout
2813e3c1ac58SAndrey Ryabinin 		 * zones or there is heavy usage of a slow backing
2814e3c1ac58SAndrey Ryabinin 		 * device. The only option is to throttle from reclaim
2815e3c1ac58SAndrey Ryabinin 		 * context which is not ideal as there is no guarantee
2816d108c772SAndrey Ryabinin 		 * the dirtying process is throttled in the same way
2817d108c772SAndrey Ryabinin 		 * balance_dirty_pages() manages.
2818d108c772SAndrey Ryabinin 		 *
2819e3c1ac58SAndrey Ryabinin 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2820e3c1ac58SAndrey Ryabinin 		 * count the number of pages under pages flagged for
2821e3c1ac58SAndrey Ryabinin 		 * immediate reclaim and stall if any are encountered
2822e3c1ac58SAndrey Ryabinin 		 * in the nr_immediate check below.
2823d108c772SAndrey Ryabinin 		 */
2824d108c772SAndrey Ryabinin 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2825d108c772SAndrey Ryabinin 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2826d108c772SAndrey Ryabinin 
2827d108c772SAndrey Ryabinin 		/* Allow kswapd to start writing pages during reclaim.*/
2828d108c772SAndrey Ryabinin 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2829d108c772SAndrey Ryabinin 			set_bit(PGDAT_DIRTY, &pgdat->flags);
2830d108c772SAndrey Ryabinin 
2831d108c772SAndrey Ryabinin 		/*
2832d108c772SAndrey Ryabinin 		 * If kswapd scans pages marked marked for immediate
2833d108c772SAndrey Ryabinin 		 * reclaim and under writeback (nr_immediate), it
2834d108c772SAndrey Ryabinin 		 * implies that pages are cycling through the LRU
2835d108c772SAndrey Ryabinin 		 * faster than they are written so also forcibly stall.
2836d108c772SAndrey Ryabinin 		 */
2837d108c772SAndrey Ryabinin 		if (sc->nr.immediate)
2838d108c772SAndrey Ryabinin 			congestion_wait(BLK_RW_ASYNC, HZ/10);
2839d108c772SAndrey Ryabinin 	}
2840d108c772SAndrey Ryabinin 
2841d108c772SAndrey Ryabinin 	/*
28421b05117dSJohannes Weiner 	 * Tag a node/memcg as congested if all the dirty pages
28431b05117dSJohannes Weiner 	 * scanned were backed by a congested BDI and
28441b05117dSJohannes Weiner 	 * wait_iff_congested will stall.
28451b05117dSJohannes Weiner 	 *
2846e3c1ac58SAndrey Ryabinin 	 * Legacy memcg will stall in page writeback so avoid forcibly
2847e3c1ac58SAndrey Ryabinin 	 * stalling in wait_iff_congested().
2848e3c1ac58SAndrey Ryabinin 	 */
28491b05117dSJohannes Weiner 	if ((current_is_kswapd() ||
28501b05117dSJohannes Weiner 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
2851e3c1ac58SAndrey Ryabinin 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
28521b05117dSJohannes Weiner 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
2853e3c1ac58SAndrey Ryabinin 
2854e3c1ac58SAndrey Ryabinin 	/*
2855d108c772SAndrey Ryabinin 	 * Stall direct reclaim for IO completions if underlying BDIs
2856d108c772SAndrey Ryabinin 	 * and node is congested. Allow kswapd to continue until it
2857d108c772SAndrey Ryabinin 	 * starts encountering unqueued dirty pages or cycling through
2858d108c772SAndrey Ryabinin 	 * the LRU too quickly.
2859d108c772SAndrey Ryabinin 	 */
28601b05117dSJohannes Weiner 	if (!current_is_kswapd() && current_may_throttle() &&
28611b05117dSJohannes Weiner 	    !sc->hibernation_mode &&
28621b05117dSJohannes Weiner 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
2863e3c1ac58SAndrey Ryabinin 		wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2864d108c772SAndrey Ryabinin 
2865d2af3397SJohannes Weiner 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2866d2af3397SJohannes Weiner 				    sc))
2867d2af3397SJohannes Weiner 		goto again;
28682344d7e4SJohannes Weiner 
2869c73322d0SJohannes Weiner 	/*
2870c73322d0SJohannes Weiner 	 * Kswapd gives up on balancing particular nodes after too
2871c73322d0SJohannes Weiner 	 * many failures to reclaim anything from them and goes to
2872c73322d0SJohannes Weiner 	 * sleep. On reclaim progress, reset the failure counter. A
2873c73322d0SJohannes Weiner 	 * successful direct reclaim run will revive a dormant kswapd.
2874c73322d0SJohannes Weiner 	 */
2875c73322d0SJohannes Weiner 	if (reclaimable)
2876c73322d0SJohannes Weiner 		pgdat->kswapd_failures = 0;
2877f16015fbSJohannes Weiner }
2878f16015fbSJohannes Weiner 
287953853e2dSVlastimil Babka /*
2880fdd4c614SVlastimil Babka  * Returns true if compaction should go ahead for a costly-order request, or
2881fdd4c614SVlastimil Babka  * the allocation would already succeed without compaction. Return false if we
2882fdd4c614SVlastimil Babka  * should reclaim first.
288353853e2dSVlastimil Babka  */
28844f588331SMel Gorman static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2885fe4b1b24SMel Gorman {
288631483b6aSMel Gorman 	unsigned long watermark;
2887fdd4c614SVlastimil Babka 	enum compact_result suitable;
2888fe4b1b24SMel Gorman 
2889fdd4c614SVlastimil Babka 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2890fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SUCCESS)
2891fdd4c614SVlastimil Babka 		/* Allocation should succeed already. Don't reclaim. */
2892fdd4c614SVlastimil Babka 		return true;
2893fdd4c614SVlastimil Babka 	if (suitable == COMPACT_SKIPPED)
2894fdd4c614SVlastimil Babka 		/* Compaction cannot yet proceed. Do reclaim. */
2895fe4b1b24SMel Gorman 		return false;
2896fe4b1b24SMel Gorman 
2897fdd4c614SVlastimil Babka 	/*
2898fdd4c614SVlastimil Babka 	 * Compaction is already possible, but it takes time to run and there
2899fdd4c614SVlastimil Babka 	 * are potentially other callers using the pages just freed. So proceed
2900fdd4c614SVlastimil Babka 	 * with reclaim to make a buffer of free pages available to give
2901fdd4c614SVlastimil Babka 	 * compaction a reasonable chance of completing and allocating the page.
2902fdd4c614SVlastimil Babka 	 * Note that we won't actually reclaim the whole buffer in one attempt
2903fdd4c614SVlastimil Babka 	 * as the target watermark in should_continue_reclaim() is lower. But if
2904fdd4c614SVlastimil Babka 	 * we are already above the high+gap watermark, don't reclaim at all.
2905fdd4c614SVlastimil Babka 	 */
2906fdd4c614SVlastimil Babka 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2907fdd4c614SVlastimil Babka 
2908fdd4c614SVlastimil Babka 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2909fe4b1b24SMel Gorman }
2910fe4b1b24SMel Gorman 
29111da177e4SLinus Torvalds /*
29121da177e4SLinus Torvalds  * This is the direct reclaim path, for page-allocating processes.  We only
29131da177e4SLinus Torvalds  * try to reclaim pages from zones which will satisfy the caller's allocation
29141da177e4SLinus Torvalds  * request.
29151da177e4SLinus Torvalds  *
29161da177e4SLinus Torvalds  * If a zone is deemed to be full of pinned pages then just give it a light
29171da177e4SLinus Torvalds  * scan then give up on it.
29181da177e4SLinus Torvalds  */
29190a0337e0SMichal Hocko static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
29201da177e4SLinus Torvalds {
2921dd1a239fSMel Gorman 	struct zoneref *z;
292254a6eb5cSMel Gorman 	struct zone *zone;
29230608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
29240608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
2925619d0d76SWeijie Yang 	gfp_t orig_mask;
292679dafcdcSMel Gorman 	pg_data_t *last_pgdat = NULL;
29271cfb419bSKAMEZAWA Hiroyuki 
2928cc715d99SMel Gorman 	/*
2929cc715d99SMel Gorman 	 * If the number of buffer_heads in the machine exceeds the maximum
2930cc715d99SMel Gorman 	 * allowed level, force direct reclaim to scan the highmem zone as
2931cc715d99SMel Gorman 	 * highmem pages could be pinning lowmem pages storing buffer_heads
2932cc715d99SMel Gorman 	 */
2933619d0d76SWeijie Yang 	orig_mask = sc->gfp_mask;
2934b2e18757SMel Gorman 	if (buffer_heads_over_limit) {
2935cc715d99SMel Gorman 		sc->gfp_mask |= __GFP_HIGHMEM;
29364f588331SMel Gorman 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2937b2e18757SMel Gorman 	}
2938cc715d99SMel Gorman 
2939d4debc66SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
2940b2e18757SMel Gorman 					sc->reclaim_idx, sc->nodemask) {
2941b2e18757SMel Gorman 		/*
29421cfb419bSKAMEZAWA Hiroyuki 		 * Take care memory controller reclaiming has small influence
29431cfb419bSKAMEZAWA Hiroyuki 		 * to global LRU.
29441cfb419bSKAMEZAWA Hiroyuki 		 */
2945b5ead35eSJohannes Weiner 		if (!cgroup_reclaim(sc)) {
2946344736f2SVladimir Davydov 			if (!cpuset_zone_allowed(zone,
2947344736f2SVladimir Davydov 						 GFP_KERNEL | __GFP_HARDWALL))
29481da177e4SLinus Torvalds 				continue;
294965ec02cbSVladimir Davydov 
2950e0887c19SRik van Riel 			/*
2951e0c23279SMel Gorman 			 * If we already have plenty of memory free for
2952e0c23279SMel Gorman 			 * compaction in this zone, don't free any more.
2953e0c23279SMel Gorman 			 * Even though compaction is invoked for any
2954e0c23279SMel Gorman 			 * non-zero order, only frequent costly order
2955e0c23279SMel Gorman 			 * reclamation is disruptive enough to become a
2956c7cfa37bSCopot Alexandru 			 * noticeable problem, like transparent huge
2957c7cfa37bSCopot Alexandru 			 * page allocations.
2958e0887c19SRik van Riel 			 */
29590b06496aSJohannes Weiner 			if (IS_ENABLED(CONFIG_COMPACTION) &&
29600b06496aSJohannes Weiner 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
29614f588331SMel Gorman 			    compaction_ready(zone, sc)) {
29620b06496aSJohannes Weiner 				sc->compaction_ready = true;
2963e0887c19SRik van Riel 				continue;
2964e0887c19SRik van Riel 			}
29650b06496aSJohannes Weiner 
29660608f43dSAndrew Morton 			/*
296779dafcdcSMel Gorman 			 * Shrink each node in the zonelist once. If the
296879dafcdcSMel Gorman 			 * zonelist is ordered by zone (not the default) then a
296979dafcdcSMel Gorman 			 * node may be shrunk multiple times but in that case
297079dafcdcSMel Gorman 			 * the user prefers lower zones being preserved.
297179dafcdcSMel Gorman 			 */
297279dafcdcSMel Gorman 			if (zone->zone_pgdat == last_pgdat)
297379dafcdcSMel Gorman 				continue;
297479dafcdcSMel Gorman 
297579dafcdcSMel Gorman 			/*
29760608f43dSAndrew Morton 			 * This steals pages from memory cgroups over softlimit
29770608f43dSAndrew Morton 			 * and returns the number of reclaimed pages and
29780608f43dSAndrew Morton 			 * scanned pages. This works for global memory pressure
29790608f43dSAndrew Morton 			 * and balancing, not for a memcg's limit.
29800608f43dSAndrew Morton 			 */
29810608f43dSAndrew Morton 			nr_soft_scanned = 0;
2982ef8f2327SMel Gorman 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
29830608f43dSAndrew Morton 						sc->order, sc->gfp_mask,
29840608f43dSAndrew Morton 						&nr_soft_scanned);
29850608f43dSAndrew Morton 			sc->nr_reclaimed += nr_soft_reclaimed;
29860608f43dSAndrew Morton 			sc->nr_scanned += nr_soft_scanned;
2987ac34a1a3SKAMEZAWA Hiroyuki 			/* need some check for avoid more shrink_zone() */
2988ac34a1a3SKAMEZAWA Hiroyuki 		}
2989d149e3b2SYing Han 
299079dafcdcSMel Gorman 		/* See comment about same check for global reclaim above */
299179dafcdcSMel Gorman 		if (zone->zone_pgdat == last_pgdat)
299279dafcdcSMel Gorman 			continue;
299379dafcdcSMel Gorman 		last_pgdat = zone->zone_pgdat;
2994970a39a3SMel Gorman 		shrink_node(zone->zone_pgdat, sc);
29951da177e4SLinus Torvalds 	}
2996e0c23279SMel Gorman 
299765ec02cbSVladimir Davydov 	/*
2998619d0d76SWeijie Yang 	 * Restore to original mask to avoid the impact on the caller if we
2999619d0d76SWeijie Yang 	 * promoted it to __GFP_HIGHMEM.
3000619d0d76SWeijie Yang 	 */
3001619d0d76SWeijie Yang 	sc->gfp_mask = orig_mask;
30021da177e4SLinus Torvalds }
30031da177e4SLinus Torvalds 
3004b910718aSJohannes Weiner static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
30052a2e4885SJohannes Weiner {
3006b910718aSJohannes Weiner 	struct lruvec *target_lruvec;
30072a2e4885SJohannes Weiner 	unsigned long refaults;
30082a2e4885SJohannes Weiner 
3009b910718aSJohannes Weiner 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3010b910718aSJohannes Weiner 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE);
3011b910718aSJohannes Weiner 	target_lruvec->refaults = refaults;
30122a2e4885SJohannes Weiner }
30132a2e4885SJohannes Weiner 
30141da177e4SLinus Torvalds /*
30151da177e4SLinus Torvalds  * This is the main entry point to direct page reclaim.
30161da177e4SLinus Torvalds  *
30171da177e4SLinus Torvalds  * If a full scan of the inactive list fails to free enough memory then we
30181da177e4SLinus Torvalds  * are "out of memory" and something needs to be killed.
30191da177e4SLinus Torvalds  *
30201da177e4SLinus Torvalds  * If the caller is !__GFP_FS then the probability of a failure is reasonably
30211da177e4SLinus Torvalds  * high - the zone may be full of dirty or under-writeback pages, which this
30225b0830cbSJens Axboe  * caller can't do much about.  We kick the writeback threads and take explicit
30235b0830cbSJens Axboe  * naps in the hope that some of these pages can be written.  But if the
30245b0830cbSJens Axboe  * allocating task holds filesystem locks which prevent writeout this might not
30255b0830cbSJens Axboe  * work, and the allocation attempt will fail.
3026a41f24eaSNishanth Aravamudan  *
3027a41f24eaSNishanth Aravamudan  * returns:	0, if no pages reclaimed
3028a41f24eaSNishanth Aravamudan  * 		else, the number of pages reclaimed
30291da177e4SLinus Torvalds  */
3030dac1d27bSMel Gorman static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
30313115cd91SVladimir Davydov 					  struct scan_control *sc)
30321da177e4SLinus Torvalds {
3033241994edSJohannes Weiner 	int initial_priority = sc->priority;
30342a2e4885SJohannes Weiner 	pg_data_t *last_pgdat;
30352a2e4885SJohannes Weiner 	struct zoneref *z;
30362a2e4885SJohannes Weiner 	struct zone *zone;
3037241994edSJohannes Weiner retry:
3038873b4771SKeika Kobayashi 	delayacct_freepages_start();
3039873b4771SKeika Kobayashi 
3040b5ead35eSJohannes Weiner 	if (!cgroup_reclaim(sc))
30417cc30fcfSMel Gorman 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
30421da177e4SLinus Torvalds 
30439e3b2f8cSKonstantin Khlebnikov 	do {
304470ddf637SAnton Vorontsov 		vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
304570ddf637SAnton Vorontsov 				sc->priority);
304666e1707bSBalbir Singh 		sc->nr_scanned = 0;
30470a0337e0SMichal Hocko 		shrink_zones(zonelist, sc);
3048e0c23279SMel Gorman 
3049bb21c7ceSKOSAKI Motohiro 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
30500b06496aSJohannes Weiner 			break;
30510b06496aSJohannes Weiner 
30520b06496aSJohannes Weiner 		if (sc->compaction_ready)
30530b06496aSJohannes Weiner 			break;
30541da177e4SLinus Torvalds 
30551da177e4SLinus Torvalds 		/*
30560e50ce3bSMinchan Kim 		 * If we're getting trouble reclaiming, start doing
30570e50ce3bSMinchan Kim 		 * writepage even in laptop mode.
30580e50ce3bSMinchan Kim 		 */
30590e50ce3bSMinchan Kim 		if (sc->priority < DEF_PRIORITY - 2)
30600e50ce3bSMinchan Kim 			sc->may_writepage = 1;
30610b06496aSJohannes Weiner 	} while (--sc->priority >= 0);
3062bb21c7ceSKOSAKI Motohiro 
30632a2e4885SJohannes Weiner 	last_pgdat = NULL;
30642a2e4885SJohannes Weiner 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
30652a2e4885SJohannes Weiner 					sc->nodemask) {
30662a2e4885SJohannes Weiner 		if (zone->zone_pgdat == last_pgdat)
30672a2e4885SJohannes Weiner 			continue;
30682a2e4885SJohannes Weiner 		last_pgdat = zone->zone_pgdat;
30691b05117dSJohannes Weiner 
30702a2e4885SJohannes Weiner 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
30711b05117dSJohannes Weiner 
30721b05117dSJohannes Weiner 		if (cgroup_reclaim(sc)) {
30731b05117dSJohannes Weiner 			struct lruvec *lruvec;
30741b05117dSJohannes Weiner 
30751b05117dSJohannes Weiner 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
30761b05117dSJohannes Weiner 						   zone->zone_pgdat);
30771b05117dSJohannes Weiner 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
30781b05117dSJohannes Weiner 		}
30792a2e4885SJohannes Weiner 	}
30802a2e4885SJohannes Weiner 
3081873b4771SKeika Kobayashi 	delayacct_freepages_end();
3082873b4771SKeika Kobayashi 
3083bb21c7ceSKOSAKI Motohiro 	if (sc->nr_reclaimed)
3084bb21c7ceSKOSAKI Motohiro 		return sc->nr_reclaimed;
3085bb21c7ceSKOSAKI Motohiro 
30860cee34fdSMel Gorman 	/* Aborted reclaim to try compaction? don't OOM, then */
30870b06496aSJohannes Weiner 	if (sc->compaction_ready)
30887335084dSMel Gorman 		return 1;
30897335084dSMel Gorman 
3090b91ac374SJohannes Weiner 	/*
3091b91ac374SJohannes Weiner 	 * We make inactive:active ratio decisions based on the node's
3092b91ac374SJohannes Weiner 	 * composition of memory, but a restrictive reclaim_idx or a
3093b91ac374SJohannes Weiner 	 * memory.low cgroup setting can exempt large amounts of
3094b91ac374SJohannes Weiner 	 * memory from reclaim. Neither of which are very common, so
3095b91ac374SJohannes Weiner 	 * instead of doing costly eligibility calculations of the
3096b91ac374SJohannes Weiner 	 * entire cgroup subtree up front, we assume the estimates are
3097b91ac374SJohannes Weiner 	 * good, and retry with forcible deactivation if that fails.
3098b91ac374SJohannes Weiner 	 */
3099b91ac374SJohannes Weiner 	if (sc->skipped_deactivate) {
3100b91ac374SJohannes Weiner 		sc->priority = initial_priority;
3101b91ac374SJohannes Weiner 		sc->force_deactivate = 1;
3102b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3103b91ac374SJohannes Weiner 		goto retry;
3104b91ac374SJohannes Weiner 	}
3105b91ac374SJohannes Weiner 
3106241994edSJohannes Weiner 	/* Untapped cgroup reserves?  Don't OOM, retry. */
3107d6622f63SYisheng Xie 	if (sc->memcg_low_skipped) {
3108241994edSJohannes Weiner 		sc->priority = initial_priority;
3109b91ac374SJohannes Weiner 		sc->force_deactivate = 0;
3110b91ac374SJohannes Weiner 		sc->skipped_deactivate = 0;
3111d6622f63SYisheng Xie 		sc->memcg_low_reclaim = 1;
3112d6622f63SYisheng Xie 		sc->memcg_low_skipped = 0;
3113241994edSJohannes Weiner 		goto retry;
3114241994edSJohannes Weiner 	}
3115241994edSJohannes Weiner 
3116bb21c7ceSKOSAKI Motohiro 	return 0;
31171da177e4SLinus Torvalds }
31181da177e4SLinus Torvalds 
3119c73322d0SJohannes Weiner static bool allow_direct_reclaim(pg_data_t *pgdat)
31205515061dSMel Gorman {
31215515061dSMel Gorman 	struct zone *zone;
31225515061dSMel Gorman 	unsigned long pfmemalloc_reserve = 0;
31235515061dSMel Gorman 	unsigned long free_pages = 0;
31245515061dSMel Gorman 	int i;
31255515061dSMel Gorman 	bool wmark_ok;
31265515061dSMel Gorman 
3127c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3128c73322d0SJohannes Weiner 		return true;
3129c73322d0SJohannes Weiner 
31305515061dSMel Gorman 	for (i = 0; i <= ZONE_NORMAL; i++) {
31315515061dSMel Gorman 		zone = &pgdat->node_zones[i];
3132d450abd8SJohannes Weiner 		if (!managed_zone(zone))
3133d450abd8SJohannes Weiner 			continue;
3134d450abd8SJohannes Weiner 
3135d450abd8SJohannes Weiner 		if (!zone_reclaimable_pages(zone))
3136675becceSMel Gorman 			continue;
3137675becceSMel Gorman 
31385515061dSMel Gorman 		pfmemalloc_reserve += min_wmark_pages(zone);
31395515061dSMel Gorman 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
31405515061dSMel Gorman 	}
31415515061dSMel Gorman 
3142675becceSMel Gorman 	/* If there are no reserves (unexpected config) then do not throttle */
3143675becceSMel Gorman 	if (!pfmemalloc_reserve)
3144675becceSMel Gorman 		return true;
3145675becceSMel Gorman 
31465515061dSMel Gorman 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
31475515061dSMel Gorman 
31485515061dSMel Gorman 	/* kswapd must be awake if processes are being throttled */
31495515061dSMel Gorman 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
315038087d9bSMel Gorman 		pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
31515515061dSMel Gorman 						(enum zone_type)ZONE_NORMAL);
31525515061dSMel Gorman 		wake_up_interruptible(&pgdat->kswapd_wait);
31535515061dSMel Gorman 	}
31545515061dSMel Gorman 
31555515061dSMel Gorman 	return wmark_ok;
31565515061dSMel Gorman }
31575515061dSMel Gorman 
31585515061dSMel Gorman /*
31595515061dSMel Gorman  * Throttle direct reclaimers if backing storage is backed by the network
31605515061dSMel Gorman  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
31615515061dSMel Gorman  * depleted. kswapd will continue to make progress and wake the processes
316250694c28SMel Gorman  * when the low watermark is reached.
316350694c28SMel Gorman  *
316450694c28SMel Gorman  * Returns true if a fatal signal was delivered during throttling. If this
316550694c28SMel Gorman  * happens, the page allocator should not consider triggering the OOM killer.
31665515061dSMel Gorman  */
316750694c28SMel Gorman static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
31685515061dSMel Gorman 					nodemask_t *nodemask)
31695515061dSMel Gorman {
3170675becceSMel Gorman 	struct zoneref *z;
31715515061dSMel Gorman 	struct zone *zone;
3172675becceSMel Gorman 	pg_data_t *pgdat = NULL;
31735515061dSMel Gorman 
31745515061dSMel Gorman 	/*
31755515061dSMel Gorman 	 * Kernel threads should not be throttled as they may be indirectly
31765515061dSMel Gorman 	 * responsible for cleaning pages necessary for reclaim to make forward
31775515061dSMel Gorman 	 * progress. kjournald for example may enter direct reclaim while
31785515061dSMel Gorman 	 * committing a transaction where throttling it could forcing other
31795515061dSMel Gorman 	 * processes to block on log_wait_commit().
31805515061dSMel Gorman 	 */
31815515061dSMel Gorman 	if (current->flags & PF_KTHREAD)
318250694c28SMel Gorman 		goto out;
318350694c28SMel Gorman 
318450694c28SMel Gorman 	/*
318550694c28SMel Gorman 	 * If a fatal signal is pending, this process should not throttle.
318650694c28SMel Gorman 	 * It should return quickly so it can exit and free its memory
318750694c28SMel Gorman 	 */
318850694c28SMel Gorman 	if (fatal_signal_pending(current))
318950694c28SMel Gorman 		goto out;
31905515061dSMel Gorman 
3191675becceSMel Gorman 	/*
3192675becceSMel Gorman 	 * Check if the pfmemalloc reserves are ok by finding the first node
3193675becceSMel Gorman 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3194675becceSMel Gorman 	 * GFP_KERNEL will be required for allocating network buffers when
3195675becceSMel Gorman 	 * swapping over the network so ZONE_HIGHMEM is unusable.
3196675becceSMel Gorman 	 *
3197675becceSMel Gorman 	 * Throttling is based on the first usable node and throttled processes
3198675becceSMel Gorman 	 * wait on a queue until kswapd makes progress and wakes them. There
3199675becceSMel Gorman 	 * is an affinity then between processes waking up and where reclaim
3200675becceSMel Gorman 	 * progress has been made assuming the process wakes on the same node.
3201675becceSMel Gorman 	 * More importantly, processes running on remote nodes will not compete
3202675becceSMel Gorman 	 * for remote pfmemalloc reserves and processes on different nodes
3203675becceSMel Gorman 	 * should make reasonable progress.
3204675becceSMel Gorman 	 */
3205675becceSMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
320617636faaSMichael S. Tsirkin 					gfp_zone(gfp_mask), nodemask) {
3207675becceSMel Gorman 		if (zone_idx(zone) > ZONE_NORMAL)
3208675becceSMel Gorman 			continue;
3209675becceSMel Gorman 
3210675becceSMel Gorman 		/* Throttle based on the first usable node */
32115515061dSMel Gorman 		pgdat = zone->zone_pgdat;
3212c73322d0SJohannes Weiner 		if (allow_direct_reclaim(pgdat))
321350694c28SMel Gorman 			goto out;
3214675becceSMel Gorman 		break;
3215675becceSMel Gorman 	}
3216675becceSMel Gorman 
3217675becceSMel Gorman 	/* If no zone was usable by the allocation flags then do not throttle */
3218675becceSMel Gorman 	if (!pgdat)
3219675becceSMel Gorman 		goto out;
32205515061dSMel Gorman 
322168243e76SMel Gorman 	/* Account for the throttling */
322268243e76SMel Gorman 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
322368243e76SMel Gorman 
32245515061dSMel Gorman 	/*
32255515061dSMel Gorman 	 * If the caller cannot enter the filesystem, it's possible that it
32265515061dSMel Gorman 	 * is due to the caller holding an FS lock or performing a journal
32275515061dSMel Gorman 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
32285515061dSMel Gorman 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
32295515061dSMel Gorman 	 * blocked waiting on the same lock. Instead, throttle for up to a
32305515061dSMel Gorman 	 * second before continuing.
32315515061dSMel Gorman 	 */
32325515061dSMel Gorman 	if (!(gfp_mask & __GFP_FS)) {
32335515061dSMel Gorman 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3234c73322d0SJohannes Weiner 			allow_direct_reclaim(pgdat), HZ);
323550694c28SMel Gorman 
323650694c28SMel Gorman 		goto check_pending;
32375515061dSMel Gorman 	}
32385515061dSMel Gorman 
32395515061dSMel Gorman 	/* Throttle until kswapd wakes the process */
32405515061dSMel Gorman 	wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3241c73322d0SJohannes Weiner 		allow_direct_reclaim(pgdat));
324250694c28SMel Gorman 
324350694c28SMel Gorman check_pending:
324450694c28SMel Gorman 	if (fatal_signal_pending(current))
324550694c28SMel Gorman 		return true;
324650694c28SMel Gorman 
324750694c28SMel Gorman out:
324850694c28SMel Gorman 	return false;
32495515061dSMel Gorman }
32505515061dSMel Gorman 
3251dac1d27bSMel Gorman unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3252327c0e96SKAMEZAWA Hiroyuki 				gfp_t gfp_mask, nodemask_t *nodemask)
325366e1707bSBalbir Singh {
325433906bc5SMel Gorman 	unsigned long nr_reclaimed;
325566e1707bSBalbir Singh 	struct scan_control sc = {
325622fba335SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3257f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
3258b2e18757SMel Gorman 		.reclaim_idx = gfp_zone(gfp_mask),
3259ee814fe2SJohannes Weiner 		.order = order,
3260ee814fe2SJohannes Weiner 		.nodemask = nodemask,
3261ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
3262ee814fe2SJohannes Weiner 		.may_writepage = !laptop_mode,
3263a6dc60f8SJohannes Weiner 		.may_unmap = 1,
32642e2e4259SKOSAKI Motohiro 		.may_swap = 1,
326566e1707bSBalbir Singh 	};
326666e1707bSBalbir Singh 
32675515061dSMel Gorman 	/*
3268bb451fdfSGreg Thelen 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3269bb451fdfSGreg Thelen 	 * Confirm they are large enough for max values.
3270bb451fdfSGreg Thelen 	 */
3271bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3272bb451fdfSGreg Thelen 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3273bb451fdfSGreg Thelen 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3274bb451fdfSGreg Thelen 
3275bb451fdfSGreg Thelen 	/*
327650694c28SMel Gorman 	 * Do not enter reclaim if fatal signal was delivered while throttled.
327750694c28SMel Gorman 	 * 1 is returned so that the page allocator does not OOM kill at this
327850694c28SMel Gorman 	 * point.
32795515061dSMel Gorman 	 */
3280f2f43e56SNick Desaulniers 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
32815515061dSMel Gorman 		return 1;
32825515061dSMel Gorman 
32831732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
32843481c37fSYafang Shao 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
328533906bc5SMel Gorman 
32863115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
328733906bc5SMel Gorman 
328833906bc5SMel Gorman 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
32891732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
329033906bc5SMel Gorman 
329133906bc5SMel Gorman 	return nr_reclaimed;
329266e1707bSBalbir Singh }
329366e1707bSBalbir Singh 
3294c255a458SAndrew Morton #ifdef CONFIG_MEMCG
329566e1707bSBalbir Singh 
3296d2e5fb92SMichal Hocko /* Only used by soft limit reclaim. Do not reuse for anything else. */
3297a9dd0a83SMel Gorman unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
32984e416953SBalbir Singh 						gfp_t gfp_mask, bool noswap,
3299ef8f2327SMel Gorman 						pg_data_t *pgdat,
33000ae5e89cSYing Han 						unsigned long *nr_scanned)
33014e416953SBalbir Singh {
3302afaf07a6SJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
33034e416953SBalbir Singh 	struct scan_control sc = {
3304b8f5c566SKOSAKI Motohiro 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
3305ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
33064e416953SBalbir Singh 		.may_writepage = !laptop_mode,
33074e416953SBalbir Singh 		.may_unmap = 1,
3308b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
33094e416953SBalbir Singh 		.may_swap = !noswap,
33104e416953SBalbir Singh 	};
33110ae5e89cSYing Han 
3312d2e5fb92SMichal Hocko 	WARN_ON_ONCE(!current->reclaim_state);
3313d2e5fb92SMichal Hocko 
33144e416953SBalbir Singh 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
33154e416953SBalbir Singh 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3316bdce6d9eSKOSAKI Motohiro 
33179e3b2f8cSKonstantin Khlebnikov 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
33183481c37fSYafang Shao 						      sc.gfp_mask);
3319bdce6d9eSKOSAKI Motohiro 
33204e416953SBalbir Singh 	/*
33214e416953SBalbir Singh 	 * NOTE: Although we can get the priority field, using it
33224e416953SBalbir Singh 	 * here is not a good idea, since it limits the pages we can scan.
3323a9dd0a83SMel Gorman 	 * if we don't reclaim here, the shrink_node from balance_pgdat
33244e416953SBalbir Singh 	 * will pick up pages from other mem cgroup's as well. We hack
33254e416953SBalbir Singh 	 * the priority and make it zero.
33264e416953SBalbir Singh 	 */
3327afaf07a6SJohannes Weiner 	shrink_lruvec(lruvec, &sc);
3328bdce6d9eSKOSAKI Motohiro 
3329bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3330bdce6d9eSKOSAKI Motohiro 
33310ae5e89cSYing Han 	*nr_scanned = sc.nr_scanned;
33320308f7cfSYafang Shao 
33334e416953SBalbir Singh 	return sc.nr_reclaimed;
33344e416953SBalbir Singh }
33354e416953SBalbir Singh 
333672835c86SJohannes Weiner unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3337b70a2a21SJohannes Weiner 					   unsigned long nr_pages,
33388c7c6e34SKAMEZAWA Hiroyuki 					   gfp_t gfp_mask,
3339b70a2a21SJohannes Weiner 					   bool may_swap)
334066e1707bSBalbir Singh {
3341bdce6d9eSKOSAKI Motohiro 	unsigned long nr_reclaimed;
3342eb414681SJohannes Weiner 	unsigned long pflags;
3343499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
334466e1707bSBalbir Singh 	struct scan_control sc = {
3345b70a2a21SJohannes Weiner 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
33467dea19f9SMichal Hocko 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3347ee814fe2SJohannes Weiner 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3348b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
3349ee814fe2SJohannes Weiner 		.target_mem_cgroup = memcg,
3350ee814fe2SJohannes Weiner 		.priority = DEF_PRIORITY,
335166e1707bSBalbir Singh 		.may_writepage = !laptop_mode,
3352a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3353b70a2a21SJohannes Weiner 		.may_swap = may_swap,
3354a09ed5e0SYing Han 	};
3355fa40d1eeSShakeel Butt 	/*
3356fa40d1eeSShakeel Butt 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3357fa40d1eeSShakeel Butt 	 * equal pressure on all the nodes. This is based on the assumption that
3358fa40d1eeSShakeel Butt 	 * the reclaim does not bail out early.
3359fa40d1eeSShakeel Butt 	 */
3360fa40d1eeSShakeel Butt 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
336166e1707bSBalbir Singh 
33621732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3363bdce6d9eSKOSAKI Motohiro 
33643481c37fSYafang Shao 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3365bdce6d9eSKOSAKI Motohiro 
3366eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
3367499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
3368eb414681SJohannes Weiner 
33693115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3370eb414681SJohannes Weiner 
3371499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
3372eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
3373bdce6d9eSKOSAKI Motohiro 
3374bdce6d9eSKOSAKI Motohiro 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
33751732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3376bdce6d9eSKOSAKI Motohiro 
3377bdce6d9eSKOSAKI Motohiro 	return nr_reclaimed;
337866e1707bSBalbir Singh }
337966e1707bSBalbir Singh #endif
338066e1707bSBalbir Singh 
33811d82de61SMel Gorman static void age_active_anon(struct pglist_data *pgdat,
3382ef8f2327SMel Gorman 				struct scan_control *sc)
3383f16015fbSJohannes Weiner {
3384b95a2f2dSJohannes Weiner 	struct mem_cgroup *memcg;
3385b91ac374SJohannes Weiner 	struct lruvec *lruvec;
3386b95a2f2dSJohannes Weiner 
3387b95a2f2dSJohannes Weiner 	if (!total_swap_pages)
3388b95a2f2dSJohannes Weiner 		return;
3389b95a2f2dSJohannes Weiner 
3390b91ac374SJohannes Weiner 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
3391b91ac374SJohannes Weiner 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3392b91ac374SJohannes Weiner 		return;
3393b91ac374SJohannes Weiner 
3394b95a2f2dSJohannes Weiner 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
3395b95a2f2dSJohannes Weiner 	do {
3396b91ac374SJohannes Weiner 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
33971a93be0eSKonstantin Khlebnikov 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
33989e3b2f8cSKonstantin Khlebnikov 				   sc, LRU_ACTIVE_ANON);
3399b95a2f2dSJohannes Weiner 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
3400b95a2f2dSJohannes Weiner 	} while (memcg);
3401f16015fbSJohannes Weiner }
3402f16015fbSJohannes Weiner 
34031c30844dSMel Gorman static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
34041c30844dSMel Gorman {
34051c30844dSMel Gorman 	int i;
34061c30844dSMel Gorman 	struct zone *zone;
34071c30844dSMel Gorman 
34081c30844dSMel Gorman 	/*
34091c30844dSMel Gorman 	 * Check for watermark boosts top-down as the higher zones
34101c30844dSMel Gorman 	 * are more likely to be boosted. Both watermarks and boosts
34111c30844dSMel Gorman 	 * should not be checked at the time time as reclaim would
34121c30844dSMel Gorman 	 * start prematurely when there is no boosting and a lower
34131c30844dSMel Gorman 	 * zone is balanced.
34141c30844dSMel Gorman 	 */
34151c30844dSMel Gorman 	for (i = classzone_idx; i >= 0; i--) {
34161c30844dSMel Gorman 		zone = pgdat->node_zones + i;
34171c30844dSMel Gorman 		if (!managed_zone(zone))
34181c30844dSMel Gorman 			continue;
34191c30844dSMel Gorman 
34201c30844dSMel Gorman 		if (zone->watermark_boost)
34211c30844dSMel Gorman 			return true;
34221c30844dSMel Gorman 	}
34231c30844dSMel Gorman 
34241c30844dSMel Gorman 	return false;
34251c30844dSMel Gorman }
34261c30844dSMel Gorman 
3427e716f2ebSMel Gorman /*
3428e716f2ebSMel Gorman  * Returns true if there is an eligible zone balanced for the request order
3429e716f2ebSMel Gorman  * and classzone_idx
3430e716f2ebSMel Gorman  */
3431e716f2ebSMel Gorman static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
343260cefed4SJohannes Weiner {
3433e716f2ebSMel Gorman 	int i;
3434e716f2ebSMel Gorman 	unsigned long mark = -1;
3435e716f2ebSMel Gorman 	struct zone *zone;
343660cefed4SJohannes Weiner 
34371c30844dSMel Gorman 	/*
34381c30844dSMel Gorman 	 * Check watermarks bottom-up as lower zones are more likely to
34391c30844dSMel Gorman 	 * meet watermarks.
34401c30844dSMel Gorman 	 */
3441e716f2ebSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
3442e716f2ebSMel Gorman 		zone = pgdat->node_zones + i;
34436256c6b4SMel Gorman 
3444e716f2ebSMel Gorman 		if (!managed_zone(zone))
3445e716f2ebSMel Gorman 			continue;
3446e716f2ebSMel Gorman 
3447e716f2ebSMel Gorman 		mark = high_wmark_pages(zone);
3448e716f2ebSMel Gorman 		if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
34496256c6b4SMel Gorman 			return true;
345060cefed4SJohannes Weiner 	}
345160cefed4SJohannes Weiner 
3452e716f2ebSMel Gorman 	/*
3453e716f2ebSMel Gorman 	 * If a node has no populated zone within classzone_idx, it does not
3454e716f2ebSMel Gorman 	 * need balancing by definition. This can happen if a zone-restricted
3455e716f2ebSMel Gorman 	 * allocation tries to wake a remote kswapd.
3456e716f2ebSMel Gorman 	 */
3457e716f2ebSMel Gorman 	if (mark == -1)
3458e716f2ebSMel Gorman 		return true;
3459e716f2ebSMel Gorman 
3460e716f2ebSMel Gorman 	return false;
3461e716f2ebSMel Gorman }
3462e716f2ebSMel Gorman 
3463631b6e08SMel Gorman /* Clear pgdat state for congested, dirty or under writeback. */
3464631b6e08SMel Gorman static void clear_pgdat_congested(pg_data_t *pgdat)
3465631b6e08SMel Gorman {
34661b05117dSJohannes Weiner 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
34671b05117dSJohannes Weiner 
34681b05117dSJohannes Weiner 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3469631b6e08SMel Gorman 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
3470631b6e08SMel Gorman 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3471631b6e08SMel Gorman }
3472631b6e08SMel Gorman 
34731741c877SMel Gorman /*
34745515061dSMel Gorman  * Prepare kswapd for sleeping. This verifies that there are no processes
34755515061dSMel Gorman  * waiting in throttle_direct_reclaim() and that watermarks have been met.
34765515061dSMel Gorman  *
34775515061dSMel Gorman  * Returns true if kswapd is ready to sleep
34785515061dSMel Gorman  */
3479d9f21d42SMel Gorman static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3480f50de2d3SMel Gorman {
34815515061dSMel Gorman 	/*
34829e5e3661SVlastimil Babka 	 * The throttled processes are normally woken up in balance_pgdat() as
3483c73322d0SJohannes Weiner 	 * soon as allow_direct_reclaim() is true. But there is a potential
34849e5e3661SVlastimil Babka 	 * race between when kswapd checks the watermarks and a process gets
34859e5e3661SVlastimil Babka 	 * throttled. There is also a potential race if processes get
34869e5e3661SVlastimil Babka 	 * throttled, kswapd wakes, a large process exits thereby balancing the
34879e5e3661SVlastimil Babka 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
34889e5e3661SVlastimil Babka 	 * the wake up checks. If kswapd is going to sleep, no process should
34899e5e3661SVlastimil Babka 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
34909e5e3661SVlastimil Babka 	 * the wake up is premature, processes will wake kswapd and get
34919e5e3661SVlastimil Babka 	 * throttled again. The difference from wake ups in balance_pgdat() is
34929e5e3661SVlastimil Babka 	 * that here we are under prepare_to_wait().
34935515061dSMel Gorman 	 */
34949e5e3661SVlastimil Babka 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
34959e5e3661SVlastimil Babka 		wake_up_all(&pgdat->pfmemalloc_wait);
3496f50de2d3SMel Gorman 
3497c73322d0SJohannes Weiner 	/* Hopeless node, leave it to direct reclaim */
3498c73322d0SJohannes Weiner 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3499c73322d0SJohannes Weiner 		return true;
3500c73322d0SJohannes Weiner 
3501e716f2ebSMel Gorman 	if (pgdat_balanced(pgdat, order, classzone_idx)) {
3502631b6e08SMel Gorman 		clear_pgdat_congested(pgdat);
3503333b0a45SShantanu Goel 		return true;
35041d82de61SMel Gorman 	}
35051d82de61SMel Gorman 
3506333b0a45SShantanu Goel 	return false;
3507f50de2d3SMel Gorman }
3508f50de2d3SMel Gorman 
35091da177e4SLinus Torvalds /*
35101d82de61SMel Gorman  * kswapd shrinks a node of pages that are at or below the highest usable
35111d82de61SMel Gorman  * zone that is currently unbalanced.
3512b8e83b94SMel Gorman  *
3513b8e83b94SMel Gorman  * Returns true if kswapd scanned at least the requested number of pages to
3514283aba9fSMel Gorman  * reclaim or if the lack of progress was due to pages under writeback.
3515283aba9fSMel Gorman  * This is used to determine if the scanning priority needs to be raised.
351675485363SMel Gorman  */
35171d82de61SMel Gorman static bool kswapd_shrink_node(pg_data_t *pgdat,
3518accf6242SVlastimil Babka 			       struct scan_control *sc)
351975485363SMel Gorman {
35201d82de61SMel Gorman 	struct zone *zone;
35211d82de61SMel Gorman 	int z;
352275485363SMel Gorman 
35231d82de61SMel Gorman 	/* Reclaim a number of pages proportional to the number of zones */
35241d82de61SMel Gorman 	sc->nr_to_reclaim = 0;
3525970a39a3SMel Gorman 	for (z = 0; z <= sc->reclaim_idx; z++) {
35261d82de61SMel Gorman 		zone = pgdat->node_zones + z;
35276aa303deSMel Gorman 		if (!managed_zone(zone))
35281d82de61SMel Gorman 			continue;
35297c954f6dSMel Gorman 
35301d82de61SMel Gorman 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
35317c954f6dSMel Gorman 	}
35327c954f6dSMel Gorman 
35331d82de61SMel Gorman 	/*
35341d82de61SMel Gorman 	 * Historically care was taken to put equal pressure on all zones but
35351d82de61SMel Gorman 	 * now pressure is applied based on node LRU order.
35361d82de61SMel Gorman 	 */
3537970a39a3SMel Gorman 	shrink_node(pgdat, sc);
35381d82de61SMel Gorman 
35391d82de61SMel Gorman 	/*
35401d82de61SMel Gorman 	 * Fragmentation may mean that the system cannot be rebalanced for
35411d82de61SMel Gorman 	 * high-order allocations. If twice the allocation size has been
35421d82de61SMel Gorman 	 * reclaimed then recheck watermarks only at order-0 to prevent
35431d82de61SMel Gorman 	 * excessive reclaim. Assume that a process requested a high-order
35441d82de61SMel Gorman 	 * can direct reclaim/compact.
35451d82de61SMel Gorman 	 */
35469861a62cSVlastimil Babka 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
35471d82de61SMel Gorman 		sc->order = 0;
35481d82de61SMel Gorman 
3549b8e83b94SMel Gorman 	return sc->nr_scanned >= sc->nr_to_reclaim;
355075485363SMel Gorman }
355175485363SMel Gorman 
355275485363SMel Gorman /*
35531d82de61SMel Gorman  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
35541d82de61SMel Gorman  * that are eligible for use by the caller until at least one zone is
35551d82de61SMel Gorman  * balanced.
35561da177e4SLinus Torvalds  *
35571d82de61SMel Gorman  * Returns the order kswapd finished reclaiming at.
35581da177e4SLinus Torvalds  *
35591da177e4SLinus Torvalds  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
356041858966SMel Gorman  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
35618bb4e7a2SWei Yang  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
35621d82de61SMel Gorman  * or lower is eligible for reclaim until at least one usable zone is
35631d82de61SMel Gorman  * balanced.
35641da177e4SLinus Torvalds  */
3565accf6242SVlastimil Babka static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
35661da177e4SLinus Torvalds {
35671da177e4SLinus Torvalds 	int i;
35680608f43dSAndrew Morton 	unsigned long nr_soft_reclaimed;
35690608f43dSAndrew Morton 	unsigned long nr_soft_scanned;
3570eb414681SJohannes Weiner 	unsigned long pflags;
35711c30844dSMel Gorman 	unsigned long nr_boost_reclaim;
35721c30844dSMel Gorman 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
35731c30844dSMel Gorman 	bool boosted;
35741d82de61SMel Gorman 	struct zone *zone;
3575179e9639SAndrew Morton 	struct scan_control sc = {
3576179e9639SAndrew Morton 		.gfp_mask = GFP_KERNEL,
3577ee814fe2SJohannes Weiner 		.order = order,
3578a6dc60f8SJohannes Weiner 		.may_unmap = 1,
3579179e9639SAndrew Morton 	};
358093781325SOmar Sandoval 
35811732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
3582eb414681SJohannes Weiner 	psi_memstall_enter(&pflags);
358393781325SOmar Sandoval 	__fs_reclaim_acquire();
358493781325SOmar Sandoval 
3585f8891e5eSChristoph Lameter 	count_vm_event(PAGEOUTRUN);
35861da177e4SLinus Torvalds 
35871c30844dSMel Gorman 	/*
35881c30844dSMel Gorman 	 * Account for the reclaim boost. Note that the zone boost is left in
35891c30844dSMel Gorman 	 * place so that parallel allocations that are near the watermark will
35901c30844dSMel Gorman 	 * stall or direct reclaim until kswapd is finished.
35911c30844dSMel Gorman 	 */
35921c30844dSMel Gorman 	nr_boost_reclaim = 0;
35931c30844dSMel Gorman 	for (i = 0; i <= classzone_idx; i++) {
35941c30844dSMel Gorman 		zone = pgdat->node_zones + i;
35951c30844dSMel Gorman 		if (!managed_zone(zone))
35961c30844dSMel Gorman 			continue;
35971c30844dSMel Gorman 
35981c30844dSMel Gorman 		nr_boost_reclaim += zone->watermark_boost;
35991c30844dSMel Gorman 		zone_boosts[i] = zone->watermark_boost;
36001c30844dSMel Gorman 	}
36011c30844dSMel Gorman 	boosted = nr_boost_reclaim;
36021c30844dSMel Gorman 
36031c30844dSMel Gorman restart:
36041c30844dSMel Gorman 	sc.priority = DEF_PRIORITY;
36059e3b2f8cSKonstantin Khlebnikov 	do {
3606c73322d0SJohannes Weiner 		unsigned long nr_reclaimed = sc.nr_reclaimed;
3607b8e83b94SMel Gorman 		bool raise_priority = true;
36081c30844dSMel Gorman 		bool balanced;
360993781325SOmar Sandoval 		bool ret;
3610b8e83b94SMel Gorman 
361184c7a777SMel Gorman 		sc.reclaim_idx = classzone_idx;
36121da177e4SLinus Torvalds 
361386c79f6bSMel Gorman 		/*
361484c7a777SMel Gorman 		 * If the number of buffer_heads exceeds the maximum allowed
361584c7a777SMel Gorman 		 * then consider reclaiming from all zones. This has a dual
361684c7a777SMel Gorman 		 * purpose -- on 64-bit systems it is expected that
361784c7a777SMel Gorman 		 * buffer_heads are stripped during active rotation. On 32-bit
361884c7a777SMel Gorman 		 * systems, highmem pages can pin lowmem memory and shrinking
361984c7a777SMel Gorman 		 * buffers can relieve lowmem pressure. Reclaim may still not
362084c7a777SMel Gorman 		 * go ahead if all eligible zones for the original allocation
362184c7a777SMel Gorman 		 * request are balanced to avoid excessive reclaim from kswapd.
362286c79f6bSMel Gorman 		 */
362386c79f6bSMel Gorman 		if (buffer_heads_over_limit) {
362486c79f6bSMel Gorman 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
362586c79f6bSMel Gorman 				zone = pgdat->node_zones + i;
36266aa303deSMel Gorman 				if (!managed_zone(zone))
362786c79f6bSMel Gorman 					continue;
362886c79f6bSMel Gorman 
3629970a39a3SMel Gorman 				sc.reclaim_idx = i;
363086c79f6bSMel Gorman 				break;
363186c79f6bSMel Gorman 			}
363286c79f6bSMel Gorman 		}
363386c79f6bSMel Gorman 
363486c79f6bSMel Gorman 		/*
36351c30844dSMel Gorman 		 * If the pgdat is imbalanced then ignore boosting and preserve
36361c30844dSMel Gorman 		 * the watermarks for a later time and restart. Note that the
36371c30844dSMel Gorman 		 * zone watermarks will be still reset at the end of balancing
36381c30844dSMel Gorman 		 * on the grounds that the normal reclaim should be enough to
36391c30844dSMel Gorman 		 * re-evaluate if boosting is required when kswapd next wakes.
364086c79f6bSMel Gorman 		 */
36411c30844dSMel Gorman 		balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
36421c30844dSMel Gorman 		if (!balanced && nr_boost_reclaim) {
36431c30844dSMel Gorman 			nr_boost_reclaim = 0;
36441c30844dSMel Gorman 			goto restart;
36451c30844dSMel Gorman 		}
36461c30844dSMel Gorman 
36471c30844dSMel Gorman 		/*
36481c30844dSMel Gorman 		 * If boosting is not active then only reclaim if there are no
36491c30844dSMel Gorman 		 * eligible zones. Note that sc.reclaim_idx is not used as
36501c30844dSMel Gorman 		 * buffer_heads_over_limit may have adjusted it.
36511c30844dSMel Gorman 		 */
36521c30844dSMel Gorman 		if (!nr_boost_reclaim && balanced)
36531da177e4SLinus Torvalds 			goto out;
3654e1dbeda6SAndrew Morton 
36551c30844dSMel Gorman 		/* Limit the priority of boosting to avoid reclaim writeback */
36561c30844dSMel Gorman 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
36571c30844dSMel Gorman 			raise_priority = false;
36581c30844dSMel Gorman 
36591c30844dSMel Gorman 		/*
36601c30844dSMel Gorman 		 * Do not writeback or swap pages for boosted reclaim. The
36611c30844dSMel Gorman 		 * intent is to relieve pressure not issue sub-optimal IO
36621c30844dSMel Gorman 		 * from reclaim context. If no pages are reclaimed, the
36631c30844dSMel Gorman 		 * reclaim will be aborted.
36641c30844dSMel Gorman 		 */
36651c30844dSMel Gorman 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
36661c30844dSMel Gorman 		sc.may_swap = !nr_boost_reclaim;
36671c30844dSMel Gorman 
36681da177e4SLinus Torvalds 		/*
36691d82de61SMel Gorman 		 * Do some background aging of the anon list, to give
36701d82de61SMel Gorman 		 * pages a chance to be referenced before reclaiming. All
36711d82de61SMel Gorman 		 * pages are rotated regardless of classzone as this is
36721d82de61SMel Gorman 		 * about consistent aging.
36731d82de61SMel Gorman 		 */
3674ef8f2327SMel Gorman 		age_active_anon(pgdat, &sc);
36751d82de61SMel Gorman 
36761d82de61SMel Gorman 		/*
3677b7ea3c41SMel Gorman 		 * If we're getting trouble reclaiming, start doing writepage
3678b7ea3c41SMel Gorman 		 * even in laptop mode.
3679b7ea3c41SMel Gorman 		 */
3680047d72c3SJohannes Weiner 		if (sc.priority < DEF_PRIORITY - 2)
3681b7ea3c41SMel Gorman 			sc.may_writepage = 1;
3682b7ea3c41SMel Gorman 
36831d82de61SMel Gorman 		/* Call soft limit reclaim before calling shrink_node. */
36841da177e4SLinus Torvalds 		sc.nr_scanned = 0;
36850608f43dSAndrew Morton 		nr_soft_scanned = 0;
3686ef8f2327SMel Gorman 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
36871d82de61SMel Gorman 						sc.gfp_mask, &nr_soft_scanned);
36880608f43dSAndrew Morton 		sc.nr_reclaimed += nr_soft_reclaimed;
36890608f43dSAndrew Morton 
369032a4330dSRik van Riel 		/*
36911d82de61SMel Gorman 		 * There should be no need to raise the scanning priority if
36921d82de61SMel Gorman 		 * enough pages are already being scanned that that high
36931d82de61SMel Gorman 		 * watermark would be met at 100% efficiency.
369432a4330dSRik van Riel 		 */
3695970a39a3SMel Gorman 		if (kswapd_shrink_node(pgdat, &sc))
3696b8e83b94SMel Gorman 			raise_priority = false;
3697d7868daeSMel Gorman 
36985515061dSMel Gorman 		/*
36995515061dSMel Gorman 		 * If the low watermark is met there is no need for processes
37005515061dSMel Gorman 		 * to be throttled on pfmemalloc_wait as they should not be
37015515061dSMel Gorman 		 * able to safely make forward progress. Wake them
37025515061dSMel Gorman 		 */
37035515061dSMel Gorman 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3704c73322d0SJohannes Weiner 				allow_direct_reclaim(pgdat))
3705cfc51155SVlastimil Babka 			wake_up_all(&pgdat->pfmemalloc_wait);
37065515061dSMel Gorman 
3707b8e83b94SMel Gorman 		/* Check if kswapd should be suspending */
370893781325SOmar Sandoval 		__fs_reclaim_release();
370993781325SOmar Sandoval 		ret = try_to_freeze();
371093781325SOmar Sandoval 		__fs_reclaim_acquire();
371193781325SOmar Sandoval 		if (ret || kthread_should_stop())
3712b8e83b94SMel Gorman 			break;
3713b8e83b94SMel Gorman 
3714b8e83b94SMel Gorman 		/*
3715b8e83b94SMel Gorman 		 * Raise priority if scanning rate is too low or there was no
3716b8e83b94SMel Gorman 		 * progress in reclaiming pages
3717b8e83b94SMel Gorman 		 */
3718c73322d0SJohannes Weiner 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
37191c30844dSMel Gorman 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
37201c30844dSMel Gorman 
37211c30844dSMel Gorman 		/*
37221c30844dSMel Gorman 		 * If reclaim made no progress for a boost, stop reclaim as
37231c30844dSMel Gorman 		 * IO cannot be queued and it could be an infinite loop in
37241c30844dSMel Gorman 		 * extreme circumstances.
37251c30844dSMel Gorman 		 */
37261c30844dSMel Gorman 		if (nr_boost_reclaim && !nr_reclaimed)
37271c30844dSMel Gorman 			break;
37281c30844dSMel Gorman 
3729c73322d0SJohannes Weiner 		if (raise_priority || !nr_reclaimed)
3730b8e83b94SMel Gorman 			sc.priority--;
37311d82de61SMel Gorman 	} while (sc.priority >= 1);
37321da177e4SLinus Torvalds 
3733c73322d0SJohannes Weiner 	if (!sc.nr_reclaimed)
3734c73322d0SJohannes Weiner 		pgdat->kswapd_failures++;
3735c73322d0SJohannes Weiner 
3736b8e83b94SMel Gorman out:
37371c30844dSMel Gorman 	/* If reclaim was boosted, account for the reclaim done in this pass */
37381c30844dSMel Gorman 	if (boosted) {
37391c30844dSMel Gorman 		unsigned long flags;
37401c30844dSMel Gorman 
37411c30844dSMel Gorman 		for (i = 0; i <= classzone_idx; i++) {
37421c30844dSMel Gorman 			if (!zone_boosts[i])
37431c30844dSMel Gorman 				continue;
37441c30844dSMel Gorman 
37451c30844dSMel Gorman 			/* Increments are under the zone lock */
37461c30844dSMel Gorman 			zone = pgdat->node_zones + i;
37471c30844dSMel Gorman 			spin_lock_irqsave(&zone->lock, flags);
37481c30844dSMel Gorman 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
37491c30844dSMel Gorman 			spin_unlock_irqrestore(&zone->lock, flags);
37501c30844dSMel Gorman 		}
37511c30844dSMel Gorman 
37521c30844dSMel Gorman 		/*
37531c30844dSMel Gorman 		 * As there is now likely space, wakeup kcompact to defragment
37541c30844dSMel Gorman 		 * pageblocks.
37551c30844dSMel Gorman 		 */
37561c30844dSMel Gorman 		wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
37571c30844dSMel Gorman 	}
37581c30844dSMel Gorman 
37592a2e4885SJohannes Weiner 	snapshot_refaults(NULL, pgdat);
376093781325SOmar Sandoval 	__fs_reclaim_release();
3761eb414681SJohannes Weiner 	psi_memstall_leave(&pflags);
37621732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
3763e5ca8071SYafang Shao 
37640abdee2bSMel Gorman 	/*
37651d82de61SMel Gorman 	 * Return the order kswapd stopped reclaiming at as
37661d82de61SMel Gorman 	 * prepare_kswapd_sleep() takes it into account. If another caller
37671d82de61SMel Gorman 	 * entered the allocator slow path while kswapd was awake, order will
37681d82de61SMel Gorman 	 * remain at the higher level.
37690abdee2bSMel Gorman 	 */
37701d82de61SMel Gorman 	return sc.order;
37711da177e4SLinus Torvalds }
37721da177e4SLinus Torvalds 
3773e716f2ebSMel Gorman /*
3774dffcac2cSShakeel Butt  * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3775dffcac2cSShakeel Butt  * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3776dffcac2cSShakeel Butt  * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3777dffcac2cSShakeel Butt  * after previous reclaim attempt (node is still unbalanced). In that case
3778dffcac2cSShakeel Butt  * return the zone index of the previous kswapd reclaim cycle.
3779e716f2ebSMel Gorman  */
3780e716f2ebSMel Gorman static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3781dffcac2cSShakeel Butt 					   enum zone_type prev_classzone_idx)
3782e716f2ebSMel Gorman {
3783e716f2ebSMel Gorman 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3784dffcac2cSShakeel Butt 		return prev_classzone_idx;
3785dffcac2cSShakeel Butt 	return pgdat->kswapd_classzone_idx;
3786e716f2ebSMel Gorman }
3787e716f2ebSMel Gorman 
378838087d9bSMel Gorman static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
378938087d9bSMel Gorman 				unsigned int classzone_idx)
3790f0bc0a60SKOSAKI Motohiro {
3791f0bc0a60SKOSAKI Motohiro 	long remaining = 0;
3792f0bc0a60SKOSAKI Motohiro 	DEFINE_WAIT(wait);
3793f0bc0a60SKOSAKI Motohiro 
3794f0bc0a60SKOSAKI Motohiro 	if (freezing(current) || kthread_should_stop())
3795f0bc0a60SKOSAKI Motohiro 		return;
3796f0bc0a60SKOSAKI Motohiro 
3797f0bc0a60SKOSAKI Motohiro 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3798f0bc0a60SKOSAKI Motohiro 
3799333b0a45SShantanu Goel 	/*
3800333b0a45SShantanu Goel 	 * Try to sleep for a short interval. Note that kcompactd will only be
3801333b0a45SShantanu Goel 	 * woken if it is possible to sleep for a short interval. This is
3802333b0a45SShantanu Goel 	 * deliberate on the assumption that if reclaim cannot keep an
3803333b0a45SShantanu Goel 	 * eligible zone balanced that it's also unlikely that compaction will
3804333b0a45SShantanu Goel 	 * succeed.
3805333b0a45SShantanu Goel 	 */
3806d9f21d42SMel Gorman 	if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3807fd901c95SVlastimil Babka 		/*
3808fd901c95SVlastimil Babka 		 * Compaction records what page blocks it recently failed to
3809fd901c95SVlastimil Babka 		 * isolate pages from and skips them in the future scanning.
3810fd901c95SVlastimil Babka 		 * When kswapd is going to sleep, it is reasonable to assume
3811fd901c95SVlastimil Babka 		 * that pages and compaction may succeed so reset the cache.
3812fd901c95SVlastimil Babka 		 */
3813fd901c95SVlastimil Babka 		reset_isolation_suitable(pgdat);
3814fd901c95SVlastimil Babka 
3815fd901c95SVlastimil Babka 		/*
3816fd901c95SVlastimil Babka 		 * We have freed the memory, now we should compact it to make
3817fd901c95SVlastimil Babka 		 * allocation of the requested order possible.
3818fd901c95SVlastimil Babka 		 */
381938087d9bSMel Gorman 		wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3820fd901c95SVlastimil Babka 
3821f0bc0a60SKOSAKI Motohiro 		remaining = schedule_timeout(HZ/10);
382238087d9bSMel Gorman 
382338087d9bSMel Gorman 		/*
382438087d9bSMel Gorman 		 * If woken prematurely then reset kswapd_classzone_idx and
382538087d9bSMel Gorman 		 * order. The values will either be from a wakeup request or
382638087d9bSMel Gorman 		 * the previous request that slept prematurely.
382738087d9bSMel Gorman 		 */
382838087d9bSMel Gorman 		if (remaining) {
3829e716f2ebSMel Gorman 			pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
383038087d9bSMel Gorman 			pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
383138087d9bSMel Gorman 		}
383238087d9bSMel Gorman 
3833f0bc0a60SKOSAKI Motohiro 		finish_wait(&pgdat->kswapd_wait, &wait);
3834f0bc0a60SKOSAKI Motohiro 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3835f0bc0a60SKOSAKI Motohiro 	}
3836f0bc0a60SKOSAKI Motohiro 
3837f0bc0a60SKOSAKI Motohiro 	/*
3838f0bc0a60SKOSAKI Motohiro 	 * After a short sleep, check if it was a premature sleep. If not, then
3839f0bc0a60SKOSAKI Motohiro 	 * go fully to sleep until explicitly woken up.
3840f0bc0a60SKOSAKI Motohiro 	 */
3841d9f21d42SMel Gorman 	if (!remaining &&
3842d9f21d42SMel Gorman 	    prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3843f0bc0a60SKOSAKI Motohiro 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3844f0bc0a60SKOSAKI Motohiro 
3845f0bc0a60SKOSAKI Motohiro 		/*
3846f0bc0a60SKOSAKI Motohiro 		 * vmstat counters are not perfectly accurate and the estimated
3847f0bc0a60SKOSAKI Motohiro 		 * value for counters such as NR_FREE_PAGES can deviate from the
3848f0bc0a60SKOSAKI Motohiro 		 * true value by nr_online_cpus * threshold. To avoid the zone
3849f0bc0a60SKOSAKI Motohiro 		 * watermarks being breached while under pressure, we reduce the
3850f0bc0a60SKOSAKI Motohiro 		 * per-cpu vmstat threshold while kswapd is awake and restore
3851f0bc0a60SKOSAKI Motohiro 		 * them before going back to sleep.
3852f0bc0a60SKOSAKI Motohiro 		 */
3853f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
38541c7e7f6cSAaditya Kumar 
38551c7e7f6cSAaditya Kumar 		if (!kthread_should_stop())
3856f0bc0a60SKOSAKI Motohiro 			schedule();
38571c7e7f6cSAaditya Kumar 
3858f0bc0a60SKOSAKI Motohiro 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3859f0bc0a60SKOSAKI Motohiro 	} else {
3860f0bc0a60SKOSAKI Motohiro 		if (remaining)
3861f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3862f0bc0a60SKOSAKI Motohiro 		else
3863f0bc0a60SKOSAKI Motohiro 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3864f0bc0a60SKOSAKI Motohiro 	}
3865f0bc0a60SKOSAKI Motohiro 	finish_wait(&pgdat->kswapd_wait, &wait);
3866f0bc0a60SKOSAKI Motohiro }
3867f0bc0a60SKOSAKI Motohiro 
38681da177e4SLinus Torvalds /*
38691da177e4SLinus Torvalds  * The background pageout daemon, started as a kernel thread
38701da177e4SLinus Torvalds  * from the init process.
38711da177e4SLinus Torvalds  *
38721da177e4SLinus Torvalds  * This basically trickles out pages so that we have _some_
38731da177e4SLinus Torvalds  * free memory available even if there is no other activity
38741da177e4SLinus Torvalds  * that frees anything up. This is needed for things like routing
38751da177e4SLinus Torvalds  * etc, where we otherwise might have all activity going on in
38761da177e4SLinus Torvalds  * asynchronous contexts that cannot page things out.
38771da177e4SLinus Torvalds  *
38781da177e4SLinus Torvalds  * If there are applications that are active memory-allocators
38791da177e4SLinus Torvalds  * (most normal use), this basically shouldn't matter.
38801da177e4SLinus Torvalds  */
38811da177e4SLinus Torvalds static int kswapd(void *p)
38821da177e4SLinus Torvalds {
3883e716f2ebSMel Gorman 	unsigned int alloc_order, reclaim_order;
3884e716f2ebSMel Gorman 	unsigned int classzone_idx = MAX_NR_ZONES - 1;
38851da177e4SLinus Torvalds 	pg_data_t *pgdat = (pg_data_t*)p;
38861da177e4SLinus Torvalds 	struct task_struct *tsk = current;
3887a70f7302SRusty Russell 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
38881da177e4SLinus Torvalds 
3889174596a0SRusty Russell 	if (!cpumask_empty(cpumask))
3890c5f59f08SMike Travis 		set_cpus_allowed_ptr(tsk, cpumask);
38911da177e4SLinus Torvalds 
38921da177e4SLinus Torvalds 	/*
38931da177e4SLinus Torvalds 	 * Tell the memory management that we're a "memory allocator",
38941da177e4SLinus Torvalds 	 * and that if we need more memory we should get access to it
38951da177e4SLinus Torvalds 	 * regardless (see "__alloc_pages()"). "kswapd" should
38961da177e4SLinus Torvalds 	 * never get caught in the normal page freeing logic.
38971da177e4SLinus Torvalds 	 *
38981da177e4SLinus Torvalds 	 * (Kswapd normally doesn't need memory anyway, but sometimes
38991da177e4SLinus Torvalds 	 * you need a small amount of memory in order to be able to
39001da177e4SLinus Torvalds 	 * page out something else, and this flag essentially protects
39011da177e4SLinus Torvalds 	 * us from recursively trying to free more memory as we're
39021da177e4SLinus Torvalds 	 * trying to free the first piece of memory in the first place).
39031da177e4SLinus Torvalds 	 */
3904930d9152SChristoph Lameter 	tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
390583144186SRafael J. Wysocki 	set_freezable();
39061da177e4SLinus Torvalds 
3907e716f2ebSMel Gorman 	pgdat->kswapd_order = 0;
3908e716f2ebSMel Gorman 	pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
39091da177e4SLinus Torvalds 	for ( ; ; ) {
39106f6313d4SJeff Liu 		bool ret;
39113e1d1d28SChristoph Lameter 
3912e716f2ebSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3913e716f2ebSMel Gorman 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3914e716f2ebSMel Gorman 
391538087d9bSMel Gorman kswapd_try_sleep:
391638087d9bSMel Gorman 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
391738087d9bSMel Gorman 					classzone_idx);
3918215ddd66SMel Gorman 
391938087d9bSMel Gorman 		/* Read the new order and classzone_idx */
392038087d9bSMel Gorman 		alloc_order = reclaim_order = pgdat->kswapd_order;
3921dffcac2cSShakeel Butt 		classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
392238087d9bSMel Gorman 		pgdat->kswapd_order = 0;
3923e716f2ebSMel Gorman 		pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
39241da177e4SLinus Torvalds 
39258fe23e05SDavid Rientjes 		ret = try_to_freeze();
39268fe23e05SDavid Rientjes 		if (kthread_should_stop())
39278fe23e05SDavid Rientjes 			break;
39288fe23e05SDavid Rientjes 
39298fe23e05SDavid Rientjes 		/*
39308fe23e05SDavid Rientjes 		 * We can speed up thawing tasks if we don't call balance_pgdat
39318fe23e05SDavid Rientjes 		 * after returning from the refrigerator
3932b1296cc4SRafael J. Wysocki 		 */
393338087d9bSMel Gorman 		if (ret)
393438087d9bSMel Gorman 			continue;
39351d82de61SMel Gorman 
393638087d9bSMel Gorman 		/*
393738087d9bSMel Gorman 		 * Reclaim begins at the requested order but if a high-order
393838087d9bSMel Gorman 		 * reclaim fails then kswapd falls back to reclaiming for
393938087d9bSMel Gorman 		 * order-0. If that happens, kswapd will consider sleeping
394038087d9bSMel Gorman 		 * for the order it finished reclaiming at (reclaim_order)
394138087d9bSMel Gorman 		 * but kcompactd is woken to compact for the original
394238087d9bSMel Gorman 		 * request (alloc_order).
394338087d9bSMel Gorman 		 */
3944e5146b12SMel Gorman 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3945e5146b12SMel Gorman 						alloc_order);
394638087d9bSMel Gorman 		reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
394738087d9bSMel Gorman 		if (reclaim_order < alloc_order)
394838087d9bSMel Gorman 			goto kswapd_try_sleep;
394933906bc5SMel Gorman 	}
3950b0a8cc58STakamori Yamaguchi 
395171abdc15SJohannes Weiner 	tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
395271abdc15SJohannes Weiner 
39531da177e4SLinus Torvalds 	return 0;
39541da177e4SLinus Torvalds }
39551da177e4SLinus Torvalds 
39561da177e4SLinus Torvalds /*
39575ecd9d40SDavid Rientjes  * A zone is low on free memory or too fragmented for high-order memory.  If
39585ecd9d40SDavid Rientjes  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
39595ecd9d40SDavid Rientjes  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
39605ecd9d40SDavid Rientjes  * has failed or is not needed, still wake up kcompactd if only compaction is
39615ecd9d40SDavid Rientjes  * needed.
39621da177e4SLinus Torvalds  */
39635ecd9d40SDavid Rientjes void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
39645ecd9d40SDavid Rientjes 		   enum zone_type classzone_idx)
39651da177e4SLinus Torvalds {
39661da177e4SLinus Torvalds 	pg_data_t *pgdat;
39671da177e4SLinus Torvalds 
39686aa303deSMel Gorman 	if (!managed_zone(zone))
39691da177e4SLinus Torvalds 		return;
39701da177e4SLinus Torvalds 
39715ecd9d40SDavid Rientjes 	if (!cpuset_zone_allowed(zone, gfp_flags))
39721da177e4SLinus Torvalds 		return;
397388f5acf8SMel Gorman 	pgdat = zone->zone_pgdat;
3974dffcac2cSShakeel Butt 
3975dffcac2cSShakeel Butt 	if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3976dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = classzone_idx;
3977dffcac2cSShakeel Butt 	else
3978dffcac2cSShakeel Butt 		pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3979e716f2ebSMel Gorman 						  classzone_idx);
398038087d9bSMel Gorman 	pgdat->kswapd_order = max(pgdat->kswapd_order, order);
39818d0986e2SCon Kolivas 	if (!waitqueue_active(&pgdat->kswapd_wait))
39821da177e4SLinus Torvalds 		return;
3983e1a55637SMel Gorman 
39845ecd9d40SDavid Rientjes 	/* Hopeless node, leave it to direct reclaim if possible */
39855ecd9d40SDavid Rientjes 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
39861c30844dSMel Gorman 	    (pgdat_balanced(pgdat, order, classzone_idx) &&
39871c30844dSMel Gorman 	     !pgdat_watermark_boosted(pgdat, classzone_idx))) {
39885ecd9d40SDavid Rientjes 		/*
39895ecd9d40SDavid Rientjes 		 * There may be plenty of free memory available, but it's too
39905ecd9d40SDavid Rientjes 		 * fragmented for high-order allocations.  Wake up kcompactd
39915ecd9d40SDavid Rientjes 		 * and rely on compaction_suitable() to determine if it's
39925ecd9d40SDavid Rientjes 		 * needed.  If it fails, it will defer subsequent attempts to
39935ecd9d40SDavid Rientjes 		 * ratelimit its work.
39945ecd9d40SDavid Rientjes 		 */
39955ecd9d40SDavid Rientjes 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
39965ecd9d40SDavid Rientjes 			wakeup_kcompactd(pgdat, order, classzone_idx);
3997c73322d0SJohannes Weiner 		return;
39985ecd9d40SDavid Rientjes 	}
3999c73322d0SJohannes Weiner 
40005ecd9d40SDavid Rientjes 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
40015ecd9d40SDavid Rientjes 				      gfp_flags);
40028d0986e2SCon Kolivas 	wake_up_interruptible(&pgdat->kswapd_wait);
40031da177e4SLinus Torvalds }
40041da177e4SLinus Torvalds 
4005c6f37f12SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
40061da177e4SLinus Torvalds /*
40077b51755cSKOSAKI Motohiro  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4008d6277db4SRafael J. Wysocki  * freed pages.
4009d6277db4SRafael J. Wysocki  *
4010d6277db4SRafael J. Wysocki  * Rather than trying to age LRUs the aim is to preserve the overall
4011d6277db4SRafael J. Wysocki  * LRU order by reclaiming preferentially
4012d6277db4SRafael J. Wysocki  * inactive > active > active referenced > active mapped
40131da177e4SLinus Torvalds  */
40147b51755cSKOSAKI Motohiro unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
40151da177e4SLinus Torvalds {
4016d6277db4SRafael J. Wysocki 	struct scan_control sc = {
40177b51755cSKOSAKI Motohiro 		.nr_to_reclaim = nr_to_reclaim,
4018ee814fe2SJohannes Weiner 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
4019b2e18757SMel Gorman 		.reclaim_idx = MAX_NR_ZONES - 1,
40209e3b2f8cSKonstantin Khlebnikov 		.priority = DEF_PRIORITY,
4021ee814fe2SJohannes Weiner 		.may_writepage = 1,
4022ee814fe2SJohannes Weiner 		.may_unmap = 1,
4023ee814fe2SJohannes Weiner 		.may_swap = 1,
4024ee814fe2SJohannes Weiner 		.hibernation_mode = 1,
40251da177e4SLinus Torvalds 	};
40267b51755cSKOSAKI Motohiro 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
40277b51755cSKOSAKI Motohiro 	unsigned long nr_reclaimed;
4028499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
40291da177e4SLinus Torvalds 
4030d92a8cfcSPeter Zijlstra 	fs_reclaim_acquire(sc.gfp_mask);
403193781325SOmar Sandoval 	noreclaim_flag = memalloc_noreclaim_save();
40321732d2b0SAndrew Morton 	set_task_reclaim_state(current, &sc.reclaim_state);
4033d6277db4SRafael J. Wysocki 
40343115cd91SVladimir Davydov 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4035d6277db4SRafael J. Wysocki 
40361732d2b0SAndrew Morton 	set_task_reclaim_state(current, NULL);
4037499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
403893781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4039d6277db4SRafael J. Wysocki 
40407b51755cSKOSAKI Motohiro 	return nr_reclaimed;
40411da177e4SLinus Torvalds }
4042c6f37f12SRafael J. Wysocki #endif /* CONFIG_HIBERNATION */
40431da177e4SLinus Torvalds 
40441da177e4SLinus Torvalds /* It's optimal to keep kswapds on the same CPUs as their memory, but
40451da177e4SLinus Torvalds    not required for correctness.  So if the last cpu in a node goes
40461da177e4SLinus Torvalds    away, we get changed to run anywhere: as the first one comes back,
40471da177e4SLinus Torvalds    restore their cpu bindings. */
4048517bbed9SSebastian Andrzej Siewior static int kswapd_cpu_online(unsigned int cpu)
40491da177e4SLinus Torvalds {
405058c0a4a7SYasunori Goto 	int nid;
40511da177e4SLinus Torvalds 
405248fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
4053c5f59f08SMike Travis 		pg_data_t *pgdat = NODE_DATA(nid);
4054a70f7302SRusty Russell 		const struct cpumask *mask;
4055a70f7302SRusty Russell 
4056a70f7302SRusty Russell 		mask = cpumask_of_node(pgdat->node_id);
4057c5f59f08SMike Travis 
40583e597945SRusty Russell 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
40591da177e4SLinus Torvalds 			/* One of our CPUs online: restore mask */
4060c5f59f08SMike Travis 			set_cpus_allowed_ptr(pgdat->kswapd, mask);
40611da177e4SLinus Torvalds 	}
4062517bbed9SSebastian Andrzej Siewior 	return 0;
40631da177e4SLinus Torvalds }
40641da177e4SLinus Torvalds 
40653218ae14SYasunori Goto /*
40663218ae14SYasunori Goto  * This kswapd start function will be called by init and node-hot-add.
40673218ae14SYasunori Goto  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
40683218ae14SYasunori Goto  */
40693218ae14SYasunori Goto int kswapd_run(int nid)
40703218ae14SYasunori Goto {
40713218ae14SYasunori Goto 	pg_data_t *pgdat = NODE_DATA(nid);
40723218ae14SYasunori Goto 	int ret = 0;
40733218ae14SYasunori Goto 
40743218ae14SYasunori Goto 	if (pgdat->kswapd)
40753218ae14SYasunori Goto 		return 0;
40763218ae14SYasunori Goto 
40773218ae14SYasunori Goto 	pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
40783218ae14SYasunori Goto 	if (IS_ERR(pgdat->kswapd)) {
40793218ae14SYasunori Goto 		/* failure at boot is fatal */
4080c6202adfSThomas Gleixner 		BUG_ON(system_state < SYSTEM_RUNNING);
4081d5dc0ad9SGavin Shan 		pr_err("Failed to start kswapd on node %d\n", nid);
4082d5dc0ad9SGavin Shan 		ret = PTR_ERR(pgdat->kswapd);
4083d72515b8SXishi Qiu 		pgdat->kswapd = NULL;
40843218ae14SYasunori Goto 	}
40853218ae14SYasunori Goto 	return ret;
40863218ae14SYasunori Goto }
40873218ae14SYasunori Goto 
40888fe23e05SDavid Rientjes /*
4089d8adde17SJiang Liu  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4090bfc8c901SVladimir Davydov  * hold mem_hotplug_begin/end().
40918fe23e05SDavid Rientjes  */
40928fe23e05SDavid Rientjes void kswapd_stop(int nid)
40938fe23e05SDavid Rientjes {
40948fe23e05SDavid Rientjes 	struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
40958fe23e05SDavid Rientjes 
4096d8adde17SJiang Liu 	if (kswapd) {
40978fe23e05SDavid Rientjes 		kthread_stop(kswapd);
4098d8adde17SJiang Liu 		NODE_DATA(nid)->kswapd = NULL;
4099d8adde17SJiang Liu 	}
41008fe23e05SDavid Rientjes }
41018fe23e05SDavid Rientjes 
41021da177e4SLinus Torvalds static int __init kswapd_init(void)
41031da177e4SLinus Torvalds {
4104517bbed9SSebastian Andrzej Siewior 	int nid, ret;
410569e05944SAndrew Morton 
41061da177e4SLinus Torvalds 	swap_setup();
410748fb2e24SLai Jiangshan 	for_each_node_state(nid, N_MEMORY)
41083218ae14SYasunori Goto  		kswapd_run(nid);
4109517bbed9SSebastian Andrzej Siewior 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4110517bbed9SSebastian Andrzej Siewior 					"mm/vmscan:online", kswapd_cpu_online,
4111517bbed9SSebastian Andrzej Siewior 					NULL);
4112517bbed9SSebastian Andrzej Siewior 	WARN_ON(ret < 0);
41131da177e4SLinus Torvalds 	return 0;
41141da177e4SLinus Torvalds }
41151da177e4SLinus Torvalds 
41161da177e4SLinus Torvalds module_init(kswapd_init)
41179eeff239SChristoph Lameter 
41189eeff239SChristoph Lameter #ifdef CONFIG_NUMA
41199eeff239SChristoph Lameter /*
4120a5f5f91dSMel Gorman  * Node reclaim mode
41219eeff239SChristoph Lameter  *
4122a5f5f91dSMel Gorman  * If non-zero call node_reclaim when the number of free pages falls below
41239eeff239SChristoph Lameter  * the watermarks.
41249eeff239SChristoph Lameter  */
4125a5f5f91dSMel Gorman int node_reclaim_mode __read_mostly;
41269eeff239SChristoph Lameter 
41271b2ffb78SChristoph Lameter #define RECLAIM_OFF 0
41287d03431cSFernando Luis Vazquez Cao #define RECLAIM_ZONE (1<<0)	/* Run shrink_inactive_list on the zone */
41291b2ffb78SChristoph Lameter #define RECLAIM_WRITE (1<<1)	/* Writeout pages during reclaim */
413095bbc0c7SZhihui Zhang #define RECLAIM_UNMAP (1<<2)	/* Unmap pages during reclaim */
41311b2ffb78SChristoph Lameter 
41329eeff239SChristoph Lameter /*
4133a5f5f91dSMel Gorman  * Priority for NODE_RECLAIM. This determines the fraction of pages
4134a92f7126SChristoph Lameter  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4135a92f7126SChristoph Lameter  * a zone.
4136a92f7126SChristoph Lameter  */
4137a5f5f91dSMel Gorman #define NODE_RECLAIM_PRIORITY 4
4138a92f7126SChristoph Lameter 
41399eeff239SChristoph Lameter /*
4140a5f5f91dSMel Gorman  * Percentage of pages in a zone that must be unmapped for node_reclaim to
41419614634fSChristoph Lameter  * occur.
41429614634fSChristoph Lameter  */
41439614634fSChristoph Lameter int sysctl_min_unmapped_ratio = 1;
41449614634fSChristoph Lameter 
41459614634fSChristoph Lameter /*
41460ff38490SChristoph Lameter  * If the number of slab pages in a zone grows beyond this percentage then
41470ff38490SChristoph Lameter  * slab reclaim needs to occur.
41480ff38490SChristoph Lameter  */
41490ff38490SChristoph Lameter int sysctl_min_slab_ratio = 5;
41500ff38490SChristoph Lameter 
415111fb9989SMel Gorman static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
415290afa5deSMel Gorman {
415311fb9989SMel Gorman 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
415411fb9989SMel Gorman 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
415511fb9989SMel Gorman 		node_page_state(pgdat, NR_ACTIVE_FILE);
415690afa5deSMel Gorman 
415790afa5deSMel Gorman 	/*
415890afa5deSMel Gorman 	 * It's possible for there to be more file mapped pages than
415990afa5deSMel Gorman 	 * accounted for by the pages on the file LRU lists because
416090afa5deSMel Gorman 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
416190afa5deSMel Gorman 	 */
416290afa5deSMel Gorman 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
416390afa5deSMel Gorman }
416490afa5deSMel Gorman 
416590afa5deSMel Gorman /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4166a5f5f91dSMel Gorman static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
416790afa5deSMel Gorman {
4168d031a157SAlexandru Moise 	unsigned long nr_pagecache_reclaimable;
4169d031a157SAlexandru Moise 	unsigned long delta = 0;
417090afa5deSMel Gorman 
417190afa5deSMel Gorman 	/*
417295bbc0c7SZhihui Zhang 	 * If RECLAIM_UNMAP is set, then all file pages are considered
417390afa5deSMel Gorman 	 * potentially reclaimable. Otherwise, we have to worry about
417411fb9989SMel Gorman 	 * pages like swapcache and node_unmapped_file_pages() provides
417590afa5deSMel Gorman 	 * a better estimate
417690afa5deSMel Gorman 	 */
4177a5f5f91dSMel Gorman 	if (node_reclaim_mode & RECLAIM_UNMAP)
4178a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
417990afa5deSMel Gorman 	else
4180a5f5f91dSMel Gorman 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
418190afa5deSMel Gorman 
418290afa5deSMel Gorman 	/* If we can't clean pages, remove dirty pages from consideration */
4183a5f5f91dSMel Gorman 	if (!(node_reclaim_mode & RECLAIM_WRITE))
4184a5f5f91dSMel Gorman 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
418590afa5deSMel Gorman 
418690afa5deSMel Gorman 	/* Watch for any possible underflows due to delta */
418790afa5deSMel Gorman 	if (unlikely(delta > nr_pagecache_reclaimable))
418890afa5deSMel Gorman 		delta = nr_pagecache_reclaimable;
418990afa5deSMel Gorman 
419090afa5deSMel Gorman 	return nr_pagecache_reclaimable - delta;
419190afa5deSMel Gorman }
419290afa5deSMel Gorman 
41930ff38490SChristoph Lameter /*
4194a5f5f91dSMel Gorman  * Try to free up some pages from this node through reclaim.
41959eeff239SChristoph Lameter  */
4196a5f5f91dSMel Gorman static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
41979eeff239SChristoph Lameter {
41987fb2d46dSChristoph Lameter 	/* Minimum pages needed in order to stay on node */
419969e05944SAndrew Morton 	const unsigned long nr_pages = 1 << order;
42009eeff239SChristoph Lameter 	struct task_struct *p = current;
4201499118e9SVlastimil Babka 	unsigned int noreclaim_flag;
4202179e9639SAndrew Morton 	struct scan_control sc = {
420362b726c1SAndrew Morton 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4204f2f43e56SNick Desaulniers 		.gfp_mask = current_gfp_context(gfp_mask),
4205bd2f6199SJohannes Weiner 		.order = order,
4206a5f5f91dSMel Gorman 		.priority = NODE_RECLAIM_PRIORITY,
4207a5f5f91dSMel Gorman 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4208a5f5f91dSMel Gorman 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4209ee814fe2SJohannes Weiner 		.may_swap = 1,
4210f2f43e56SNick Desaulniers 		.reclaim_idx = gfp_zone(gfp_mask),
4211179e9639SAndrew Morton 	};
42129eeff239SChristoph Lameter 
4213132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4214132bb8cfSYafang Shao 					   sc.gfp_mask);
4215132bb8cfSYafang Shao 
42169eeff239SChristoph Lameter 	cond_resched();
421793781325SOmar Sandoval 	fs_reclaim_acquire(sc.gfp_mask);
4218d4f7796eSChristoph Lameter 	/*
421995bbc0c7SZhihui Zhang 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4220d4f7796eSChristoph Lameter 	 * and we also need to be able to write out pages for RECLAIM_WRITE
422195bbc0c7SZhihui Zhang 	 * and RECLAIM_UNMAP.
4222d4f7796eSChristoph Lameter 	 */
4223499118e9SVlastimil Babka 	noreclaim_flag = memalloc_noreclaim_save();
4224499118e9SVlastimil Babka 	p->flags |= PF_SWAPWRITE;
42251732d2b0SAndrew Morton 	set_task_reclaim_state(p, &sc.reclaim_state);
4226c84db23cSChristoph Lameter 
4227a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4228a92f7126SChristoph Lameter 		/*
4229894befecSAndrey Ryabinin 		 * Free memory by calling shrink node with increasing
42300ff38490SChristoph Lameter 		 * priorities until we have enough memory freed.
4231a92f7126SChristoph Lameter 		 */
4232a92f7126SChristoph Lameter 		do {
4233970a39a3SMel Gorman 			shrink_node(pgdat, &sc);
42349e3b2f8cSKonstantin Khlebnikov 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
42350ff38490SChristoph Lameter 	}
4236a92f7126SChristoph Lameter 
42371732d2b0SAndrew Morton 	set_task_reclaim_state(p, NULL);
4238499118e9SVlastimil Babka 	current->flags &= ~PF_SWAPWRITE;
4239499118e9SVlastimil Babka 	memalloc_noreclaim_restore(noreclaim_flag);
424093781325SOmar Sandoval 	fs_reclaim_release(sc.gfp_mask);
4241132bb8cfSYafang Shao 
4242132bb8cfSYafang Shao 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4243132bb8cfSYafang Shao 
4244a79311c1SRik van Riel 	return sc.nr_reclaimed >= nr_pages;
42459eeff239SChristoph Lameter }
4246179e9639SAndrew Morton 
4247a5f5f91dSMel Gorman int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4248179e9639SAndrew Morton {
4249d773ed6bSDavid Rientjes 	int ret;
4250179e9639SAndrew Morton 
4251179e9639SAndrew Morton 	/*
4252a5f5f91dSMel Gorman 	 * Node reclaim reclaims unmapped file backed pages and
42530ff38490SChristoph Lameter 	 * slab pages if we are over the defined limits.
425434aa1330SChristoph Lameter 	 *
42559614634fSChristoph Lameter 	 * A small portion of unmapped file backed pages is needed for
42569614634fSChristoph Lameter 	 * file I/O otherwise pages read by file I/O will be immediately
4257a5f5f91dSMel Gorman 	 * thrown out if the node is overallocated. So we do not reclaim
4258a5f5f91dSMel Gorman 	 * if less than a specified percentage of the node is used by
42599614634fSChristoph Lameter 	 * unmapped file backed pages.
4260179e9639SAndrew Morton 	 */
4261a5f5f91dSMel Gorman 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4262385386cfSJohannes Weiner 	    node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4263a5f5f91dSMel Gorman 		return NODE_RECLAIM_FULL;
4264179e9639SAndrew Morton 
4265179e9639SAndrew Morton 	/*
4266d773ed6bSDavid Rientjes 	 * Do not scan if the allocation should not be delayed.
4267179e9639SAndrew Morton 	 */
4268d0164adcSMel Gorman 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4269a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4270179e9639SAndrew Morton 
4271179e9639SAndrew Morton 	/*
4272a5f5f91dSMel Gorman 	 * Only run node reclaim on the local node or on nodes that do not
4273179e9639SAndrew Morton 	 * have associated processors. This will favor the local processor
4274179e9639SAndrew Morton 	 * over remote processors and spread off node memory allocations
4275179e9639SAndrew Morton 	 * as wide as possible.
4276179e9639SAndrew Morton 	 */
4277a5f5f91dSMel Gorman 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4278a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4279d773ed6bSDavid Rientjes 
4280a5f5f91dSMel Gorman 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4281a5f5f91dSMel Gorman 		return NODE_RECLAIM_NOSCAN;
4282fa5e084eSMel Gorman 
4283a5f5f91dSMel Gorman 	ret = __node_reclaim(pgdat, gfp_mask, order);
4284a5f5f91dSMel Gorman 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4285d773ed6bSDavid Rientjes 
428624cf7251SMel Gorman 	if (!ret)
428724cf7251SMel Gorman 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
428824cf7251SMel Gorman 
4289d773ed6bSDavid Rientjes 	return ret;
4290179e9639SAndrew Morton }
42919eeff239SChristoph Lameter #endif
4292894bc310SLee Schermerhorn 
4293894bc310SLee Schermerhorn /*
4294894bc310SLee Schermerhorn  * page_evictable - test whether a page is evictable
4295894bc310SLee Schermerhorn  * @page: the page to test
4296894bc310SLee Schermerhorn  *
4297894bc310SLee Schermerhorn  * Test whether page is evictable--i.e., should be placed on active/inactive
429839b5f29aSHugh Dickins  * lists vs unevictable list.
4299894bc310SLee Schermerhorn  *
4300894bc310SLee Schermerhorn  * Reasons page might not be evictable:
4301ba9ddf49SLee Schermerhorn  * (1) page's mapping marked unevictable
4302b291f000SNick Piggin  * (2) page is part of an mlocked VMA
4303ba9ddf49SLee Schermerhorn  *
4304894bc310SLee Schermerhorn  */
430539b5f29aSHugh Dickins int page_evictable(struct page *page)
4306894bc310SLee Schermerhorn {
4307e92bb4ddSHuang Ying 	int ret;
4308e92bb4ddSHuang Ying 
4309e92bb4ddSHuang Ying 	/* Prevent address_space of inode and swap cache from being freed */
4310e92bb4ddSHuang Ying 	rcu_read_lock();
4311e92bb4ddSHuang Ying 	ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4312e92bb4ddSHuang Ying 	rcu_read_unlock();
4313e92bb4ddSHuang Ying 	return ret;
4314894bc310SLee Schermerhorn }
431589e004eaSLee Schermerhorn 
431689e004eaSLee Schermerhorn /**
431764e3d12fSKuo-Hsin Yang  * check_move_unevictable_pages - check pages for evictability and move to
431864e3d12fSKuo-Hsin Yang  * appropriate zone lru list
431964e3d12fSKuo-Hsin Yang  * @pvec: pagevec with lru pages to check
432089e004eaSLee Schermerhorn  *
432164e3d12fSKuo-Hsin Yang  * Checks pages for evictability, if an evictable page is in the unevictable
432264e3d12fSKuo-Hsin Yang  * lru list, moves it to the appropriate evictable lru list. This function
432364e3d12fSKuo-Hsin Yang  * should be only used for lru pages.
432489e004eaSLee Schermerhorn  */
432564e3d12fSKuo-Hsin Yang void check_move_unevictable_pages(struct pagevec *pvec)
432689e004eaSLee Schermerhorn {
4327925b7673SJohannes Weiner 	struct lruvec *lruvec;
4328785b99feSMel Gorman 	struct pglist_data *pgdat = NULL;
432924513264SHugh Dickins 	int pgscanned = 0;
433024513264SHugh Dickins 	int pgrescued = 0;
433189e004eaSLee Schermerhorn 	int i;
433289e004eaSLee Schermerhorn 
433364e3d12fSKuo-Hsin Yang 	for (i = 0; i < pvec->nr; i++) {
433464e3d12fSKuo-Hsin Yang 		struct page *page = pvec->pages[i];
4335785b99feSMel Gorman 		struct pglist_data *pagepgdat = page_pgdat(page);
433689e004eaSLee Schermerhorn 
433724513264SHugh Dickins 		pgscanned++;
4338785b99feSMel Gorman 		if (pagepgdat != pgdat) {
4339785b99feSMel Gorman 			if (pgdat)
4340785b99feSMel Gorman 				spin_unlock_irq(&pgdat->lru_lock);
4341785b99feSMel Gorman 			pgdat = pagepgdat;
4342785b99feSMel Gorman 			spin_lock_irq(&pgdat->lru_lock);
434389e004eaSLee Schermerhorn 		}
4344785b99feSMel Gorman 		lruvec = mem_cgroup_page_lruvec(page, pgdat);
434589e004eaSLee Schermerhorn 
434624513264SHugh Dickins 		if (!PageLRU(page) || !PageUnevictable(page))
434724513264SHugh Dickins 			continue;
434889e004eaSLee Schermerhorn 
434939b5f29aSHugh Dickins 		if (page_evictable(page)) {
435024513264SHugh Dickins 			enum lru_list lru = page_lru_base_type(page);
435124513264SHugh Dickins 
4352309381feSSasha Levin 			VM_BUG_ON_PAGE(PageActive(page), page);
435324513264SHugh Dickins 			ClearPageUnevictable(page);
4354fa9add64SHugh Dickins 			del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4355fa9add64SHugh Dickins 			add_page_to_lru_list(page, lruvec, lru);
435624513264SHugh Dickins 			pgrescued++;
435789e004eaSLee Schermerhorn 		}
435889e004eaSLee Schermerhorn 	}
435924513264SHugh Dickins 
4360785b99feSMel Gorman 	if (pgdat) {
436124513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
436224513264SHugh Dickins 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4363785b99feSMel Gorman 		spin_unlock_irq(&pgdat->lru_lock);
436424513264SHugh Dickins 	}
436585046579SHugh Dickins }
436664e3d12fSKuo-Hsin Yang EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4367