blob: 670a46dff1af3d0b5f41d06def9e6da0172b2b96 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070053
54#include <asm/tlbflush.h>
55#include <asm/div64.h>
56
57#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070058#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070059
Nick Piggin0f8053a2006-03-22 00:08:33 -080060#include "internal.h"
61
Mel Gorman33906bc2010-08-09 17:19:16 -070062#define CREATE_TRACE_POINTS
63#include <trace/events/vmscan.h>
64
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070065#undef CREATE_TRACE_POINTS
66#include <trace/hooks/vmscan.h>
67
Linus Torvalds1da177e2005-04-16 15:20:36 -070068struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080069 /* How many pages shrink_list() should reclaim */
70 unsigned long nr_to_reclaim;
71
Johannes Weineree814fe2014-08-06 16:06:19 -070072 /*
73 * Nodemask of nodes allowed by the caller. If NULL, all nodes
74 * are scanned.
75 */
76 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070077
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070078 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080079 * The memory cgroup that hit its limit and as a result is the
80 * primary target of this reclaim invocation.
81 */
82 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080083
Johannes Weiner7cf111b2020-06-03 16:03:06 -070084 /*
85 * Scan pressure balancing between anon and file LRUs
86 */
87 unsigned long anon_cost;
88 unsigned long file_cost;
89
Johannes Weinerb91ac372019-11-30 17:56:02 -080090 /* Can active pages be deactivated as part of reclaim? */
91#define DEACTIVATE_ANON 1
92#define DEACTIVATE_FILE 2
93 unsigned int may_deactivate:2;
94 unsigned int force_deactivate:1;
95 unsigned int skipped_deactivate:1;
96
Johannes Weiner1276ad62017-02-24 14:56:11 -080097 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -070098 unsigned int may_writepage:1;
99
100 /* Can mapped pages be reclaimed? */
101 unsigned int may_unmap:1;
102
103 /* Can pages be swapped as part of reclaim? */
104 unsigned int may_swap:1;
105
Yisheng Xied6622f62017-05-03 14:53:57 -0700106 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700107 * Cgroup memory below memory.low is protected as long as we
108 * don't threaten to OOM. If any cgroup is reclaimed at
109 * reduced force or passed over entirely due to its memory.low
110 * setting (memcg_low_skipped), and nothing is reclaimed as a
111 * result, then go back for one more cycle that reclaims the protected
112 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700113 */
114 unsigned int memcg_low_reclaim:1;
115 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800116
Johannes Weineree814fe2014-08-06 16:06:19 -0700117 unsigned int hibernation_mode:1;
118
119 /* One of the zones is ready for compaction */
120 unsigned int compaction_ready:1;
121
Johannes Weinerb91ac372019-11-30 17:56:02 -0800122 /* There is easily reclaimable cold cache in the current node */
123 unsigned int cache_trim_mode:1;
124
Johannes Weiner53138ce2019-11-30 17:55:56 -0800125 /* The file pages on the current node are dangerously low */
126 unsigned int file_is_tiny:1;
127
Dave Hansen26aa2d12021-09-02 14:59:16 -0700128 /* Always discard instead of demoting to lower tier memory */
129 unsigned int no_demotion:1;
130
Greg Thelenbb451fd2018-08-17 15:45:19 -0700131 /* Allocation order */
132 s8 order;
133
134 /* Scan (total_size >> priority) pages at once */
135 s8 priority;
136
137 /* The highest zone to isolate pages for reclaim from */
138 s8 reclaim_idx;
139
140 /* This context's GFP mask */
141 gfp_t gfp_mask;
142
Johannes Weineree814fe2014-08-06 16:06:19 -0700143 /* Incremented by the number of inactive pages that were scanned */
144 unsigned long nr_scanned;
145
146 /* Number of pages freed so far during a call to shrink_zones() */
147 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700148
149 struct {
150 unsigned int dirty;
151 unsigned int unqueued_dirty;
152 unsigned int congested;
153 unsigned int writeback;
154 unsigned int immediate;
155 unsigned int file_taken;
156 unsigned int taken;
157 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700158
159 /* for recording the reclaimed slab by now */
160 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700161};
162
Linus Torvalds1da177e2005-04-16 15:20:36 -0700163#ifdef ARCH_HAS_PREFETCHW
164#define prefetchw_prev_lru_page(_page, _base, _field) \
165 do { \
166 if ((_page)->lru.prev != _base) { \
167 struct page *prev; \
168 \
169 prev = lru_to_page(&(_page->lru)); \
170 prefetchw(&prev->_field); \
171 } \
172 } while (0)
173#else
174#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
175#endif
176
177/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700178 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700179 */
180int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700181
Yang Shi0a432dc2019-09-23 15:38:12 -0700182static void set_task_reclaim_state(struct task_struct *task,
183 struct reclaim_state *rs)
184{
185 /* Check for an overwrite */
186 WARN_ON_ONCE(rs && task->reclaim_state);
187
188 /* Check for the nulling of an already-nulled member */
189 WARN_ON_ONCE(!rs && !task->reclaim_state);
190
191 task->reclaim_state = rs;
192}
193
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194static LIST_HEAD(shrinker_list);
195static DECLARE_RWSEM(shrinker_rwsem);
196
Yang Shi0a432dc2019-09-23 15:38:12 -0700197#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700198static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700199
Yang Shi3c6f17e2021-05-04 18:36:33 -0700200/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700201static inline int shrinker_map_size(int nr_items)
202{
203 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
204}
Yang Shi2bfd3632021-05-04 18:36:11 -0700205
Yang Shi3c6f17e2021-05-04 18:36:33 -0700206static inline int shrinker_defer_size(int nr_items)
207{
208 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
209}
210
Yang Shi468ab842021-05-04 18:36:26 -0700211static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
212 int nid)
213{
214 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
215 lockdep_is_held(&shrinker_rwsem));
216}
217
Yang Shie4262c42021-05-04 18:36:23 -0700218static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700219 int map_size, int defer_size,
220 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700221{
Yang Shie4262c42021-05-04 18:36:23 -0700222 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700223 struct mem_cgroup_per_node *pn;
224 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700225 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700226
Yang Shi2bfd3632021-05-04 18:36:11 -0700227 for_each_node(nid) {
228 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700229 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700230 /* Not yet online memcg */
231 if (!old)
232 return 0;
233
234 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
235 if (!new)
236 return -ENOMEM;
237
Yang Shi3c6f17e2021-05-04 18:36:33 -0700238 new->nr_deferred = (atomic_long_t *)(new + 1);
239 new->map = (void *)new->nr_deferred + defer_size;
240
241 /* map: set all old bits, clear all new bits */
242 memset(new->map, (int)0xff, old_map_size);
243 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
244 /* nr_deferred: copy old values, clear all new values */
245 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
246 memset((void *)new->nr_deferred + old_defer_size, 0,
247 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700248
Yang Shie4262c42021-05-04 18:36:23 -0700249 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700250 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700251 }
252
253 return 0;
254}
255
Yang Shie4262c42021-05-04 18:36:23 -0700256void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700257{
258 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700259 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700260 int nid;
261
Yang Shi2bfd3632021-05-04 18:36:11 -0700262 for_each_node(nid) {
263 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700264 info = rcu_dereference_protected(pn->shrinker_info, true);
265 kvfree(info);
266 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700267 }
268}
269
Yang Shie4262c42021-05-04 18:36:23 -0700270int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700271{
Yang Shie4262c42021-05-04 18:36:23 -0700272 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700273 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700274 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700275
Yang Shid27cf2a2021-05-04 18:36:14 -0700276 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700277 map_size = shrinker_map_size(shrinker_nr_max);
278 defer_size = shrinker_defer_size(shrinker_nr_max);
279 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700280 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700281 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
282 if (!info) {
283 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700284 ret = -ENOMEM;
285 break;
286 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700287 info->nr_deferred = (atomic_long_t *)(info + 1);
288 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700289 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700290 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700291 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700292
293 return ret;
294}
295
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296static inline bool need_expand(int nr_max)
297{
298 return round_up(nr_max, BITS_PER_LONG) >
299 round_up(shrinker_nr_max, BITS_PER_LONG);
300}
301
Yang Shie4262c42021-05-04 18:36:23 -0700302static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700303{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700304 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700305 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306 int map_size, defer_size = 0;
307 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700308 struct mem_cgroup *memcg;
309
Yang Shi3c6f17e2021-05-04 18:36:33 -0700310 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700311 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700312
Yang Shi2bfd3632021-05-04 18:36:11 -0700313 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700314 goto out;
315
316 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700317
Yang Shi3c6f17e2021-05-04 18:36:33 -0700318 map_size = shrinker_map_size(new_nr_max);
319 defer_size = shrinker_defer_size(new_nr_max);
320 old_map_size = shrinker_map_size(shrinker_nr_max);
321 old_defer_size = shrinker_defer_size(shrinker_nr_max);
322
Yang Shi2bfd3632021-05-04 18:36:11 -0700323 memcg = mem_cgroup_iter(NULL, NULL, NULL);
324 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700325 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
326 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700327 if (ret) {
328 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700329 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700330 }
331 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700332out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700333 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700334 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700335
Yang Shi2bfd3632021-05-04 18:36:11 -0700336 return ret;
337}
338
339void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
340{
341 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700342 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700343
344 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700345 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 /* Pairs with smp mb in shrink_slab() */
347 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700348 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 rcu_read_unlock();
350 }
351}
352
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700353static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700354
355static int prealloc_memcg_shrinker(struct shrinker *shrinker)
356{
357 int id, ret = -ENOMEM;
358
Yang Shi476b30a2021-05-04 18:36:39 -0700359 if (mem_cgroup_disabled())
360 return -ENOSYS;
361
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700362 down_write(&shrinker_rwsem);
363 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700364 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700365 if (id < 0)
366 goto unlock;
367
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700368 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700369 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700370 idr_remove(&shrinker_idr, id);
371 goto unlock;
372 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700373 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700374 shrinker->id = id;
375 ret = 0;
376unlock:
377 up_write(&shrinker_rwsem);
378 return ret;
379}
380
381static void unregister_memcg_shrinker(struct shrinker *shrinker)
382{
383 int id = shrinker->id;
384
385 BUG_ON(id < 0);
386
Yang Shi41ca6682021-05-04 18:36:29 -0700387 lockdep_assert_held(&shrinker_rwsem);
388
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700389 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700390}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700391
Yang Shi86750832021-05-04 18:36:36 -0700392static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
393 struct mem_cgroup *memcg)
394{
395 struct shrinker_info *info;
396
397 info = shrinker_info_protected(memcg, nid);
398 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
399}
400
401static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
402 struct mem_cgroup *memcg)
403{
404 struct shrinker_info *info;
405
406 info = shrinker_info_protected(memcg, nid);
407 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
408}
409
Yang Shia1780152021-05-04 18:36:42 -0700410void reparent_shrinker_deferred(struct mem_cgroup *memcg)
411{
412 int i, nid;
413 long nr;
414 struct mem_cgroup *parent;
415 struct shrinker_info *child_info, *parent_info;
416
417 parent = parent_mem_cgroup(memcg);
418 if (!parent)
419 parent = root_mem_cgroup;
420
421 /* Prevent from concurrent shrinker_info expand */
422 down_read(&shrinker_rwsem);
423 for_each_node(nid) {
424 child_info = shrinker_info_protected(memcg, nid);
425 parent_info = shrinker_info_protected(parent, nid);
426 for (i = 0; i < shrinker_nr_max; i++) {
427 nr = atomic_long_read(&child_info->nr_deferred[i]);
428 atomic_long_add(nr, &parent_info->nr_deferred[i]);
429 }
430 }
431 up_read(&shrinker_rwsem);
432}
433
Johannes Weinerb5ead352019-11-30 17:55:40 -0800434static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800435{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800436 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800437}
Tejun Heo97c93412015-05-22 18:23:36 -0400438
439/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800440 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400441 * @sc: scan_control in question
442 *
443 * The normal page dirty throttling mechanism in balance_dirty_pages() is
444 * completely broken with the legacy memcg and direct stalling in
445 * shrink_page_list() is used for throttling instead, which lacks all the
446 * niceties such as fairness, adaptive pausing, bandwidth proportional
447 * allocation and configurability.
448 *
449 * This function tests whether the vmscan currently in progress can assume
450 * that the normal dirty throttling mechanism is operational.
451 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800452static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400453{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800454 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400455 return true;
456#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800457 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400458 return true;
459#endif
460 return false;
461}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800462#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700463static int prealloc_memcg_shrinker(struct shrinker *shrinker)
464{
Yang Shi476b30a2021-05-04 18:36:39 -0700465 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700466}
467
468static void unregister_memcg_shrinker(struct shrinker *shrinker)
469{
470}
471
Yang Shi86750832021-05-04 18:36:36 -0700472static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
473 struct mem_cgroup *memcg)
474{
475 return 0;
476}
477
478static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
479 struct mem_cgroup *memcg)
480{
481 return 0;
482}
483
Johannes Weinerb5ead352019-11-30 17:55:40 -0800484static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800485{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800486 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800487}
Tejun Heo97c93412015-05-22 18:23:36 -0400488
Johannes Weinerb5ead352019-11-30 17:55:40 -0800489static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400490{
491 return true;
492}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800493#endif
494
Yang Shi86750832021-05-04 18:36:36 -0700495static long xchg_nr_deferred(struct shrinker *shrinker,
496 struct shrink_control *sc)
497{
498 int nid = sc->nid;
499
500 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
501 nid = 0;
502
503 if (sc->memcg &&
504 (shrinker->flags & SHRINKER_MEMCG_AWARE))
505 return xchg_nr_deferred_memcg(nid, shrinker,
506 sc->memcg);
507
508 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
509}
510
511
512static long add_nr_deferred(long nr, struct shrinker *shrinker,
513 struct shrink_control *sc)
514{
515 int nid = sc->nid;
516
517 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
518 nid = 0;
519
520 if (sc->memcg &&
521 (shrinker->flags & SHRINKER_MEMCG_AWARE))
522 return add_nr_deferred_memcg(nr, nid, shrinker,
523 sc->memcg);
524
525 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
526}
527
Dave Hansen26aa2d12021-09-02 14:59:16 -0700528static bool can_demote(int nid, struct scan_control *sc)
529{
Huang Ying20b51af12021-09-02 14:59:33 -0700530 if (!numa_demotion_enabled)
531 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700532 if (sc) {
533 if (sc->no_demotion)
534 return false;
535 /* It is pointless to do demotion in memcg reclaim */
536 if (cgroup_reclaim(sc))
537 return false;
538 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700539 if (next_demotion_node(nid) == NUMA_NO_NODE)
540 return false;
541
Huang Ying20b51af12021-09-02 14:59:33 -0700542 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700543}
544
Keith Buscha2a36482021-09-02 14:59:26 -0700545static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
546 int nid,
547 struct scan_control *sc)
548{
549 if (memcg == NULL) {
550 /*
551 * For non-memcg reclaim, is there
552 * space in any swap device?
553 */
554 if (get_nr_swap_pages() > 0)
555 return true;
556 } else {
557 /* Is the memcg below its swap limit? */
558 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
559 return true;
560 }
561
562 /*
563 * The page can not be swapped.
564 *
565 * Can it be reclaimed from this node via demotion?
566 */
567 return can_demote(nid, sc);
568}
569
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700570/*
571 * This misses isolated pages which are not accounted for to save counters.
572 * As the data only determines if reclaim or compaction continues, it is
573 * not expected that isolated pages will be a dominating factor.
574 */
575unsigned long zone_reclaimable_pages(struct zone *zone)
576{
577 unsigned long nr;
578
579 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
580 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700581 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700582 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
583 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
584
585 return nr;
586}
587
Michal Hockofd538802017-02-22 15:45:58 -0800588/**
589 * lruvec_lru_size - Returns the number of pages on the given LRU list.
590 * @lruvec: lru vector
591 * @lru: lru to use
592 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
593 */
Yu Zhao20913392021-02-24 12:08:44 -0800594static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
595 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800596{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800597 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800598 int zid;
599
Johannes Weinerde3b0152019-11-30 17:55:31 -0800600 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800601 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800602
Michal Hockofd538802017-02-22 15:45:58 -0800603 if (!managed_zone(zone))
604 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800605
Michal Hockofd538802017-02-22 15:45:58 -0800606 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800607 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800608 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800610 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800611 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800612}
613
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000615 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700616 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900617int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700618{
Yang Shi476b30a2021-05-04 18:36:39 -0700619 unsigned int size;
620 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000621
Yang Shi476b30a2021-05-04 18:36:39 -0700622 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
623 err = prealloc_memcg_shrinker(shrinker);
624 if (err != -ENOSYS)
625 return err;
626
627 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
628 }
629
630 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000631 if (shrinker->flags & SHRINKER_NUMA_AWARE)
632 size *= nr_node_ids;
633
634 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
635 if (!shrinker->nr_deferred)
636 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700637
Tetsuo Handa8e049442018-04-04 19:53:07 +0900638 return 0;
639}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000640
Tetsuo Handa8e049442018-04-04 19:53:07 +0900641void free_prealloced_shrinker(struct shrinker *shrinker)
642{
Yang Shi41ca6682021-05-04 18:36:29 -0700643 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
644 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700645 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700646 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700647 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700648 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700649
Tetsuo Handa8e049442018-04-04 19:53:07 +0900650 kfree(shrinker->nr_deferred);
651 shrinker->nr_deferred = NULL;
652}
653
654void register_shrinker_prepared(struct shrinker *shrinker)
655{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700656 down_write(&shrinker_rwsem);
657 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700658 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700659 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900660}
661
662int register_shrinker(struct shrinker *shrinker)
663{
664 int err = prealloc_shrinker(shrinker);
665
666 if (err)
667 return err;
668 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000669 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700670}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700671EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700672
673/*
674 * Remove one
675 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700676void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700677{
Yang Shi41ca6682021-05-04 18:36:29 -0700678 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900679 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700680
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681 down_write(&shrinker_rwsem);
682 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700683 shrinker->flags &= ~SHRINKER_REGISTERED;
684 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
685 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700687
Andrew Vaginae393322013-10-16 13:46:46 -0700688 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900689 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700691EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692
693#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000694
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800695static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800696 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700697{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000698 unsigned long freed = 0;
699 unsigned long long delta;
700 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700701 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000702 long nr;
703 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704 long batch_size = shrinker->batch ? shrinker->batch
705 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800706 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000707
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700708 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700709 if (freeable == 0 || freeable == SHRINK_EMPTY)
710 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000711
712 /*
713 * copy the current shrinker scan count into a local variable
714 * and zero it so that other concurrent shrinker invocations
715 * don't also do this scanning work.
716 */
Yang Shi86750832021-05-04 18:36:36 -0700717 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000718
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700719 if (shrinker->seeks) {
720 delta = freeable >> priority;
721 delta *= 4;
722 do_div(delta, shrinker->seeks);
723 } else {
724 /*
725 * These objects don't require any IO to create. Trim
726 * them aggressively under memory pressure to keep
727 * them from causing refetches in the IO caches.
728 */
729 delta = freeable / 2;
730 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700731
Yang Shi18bb4732021-05-04 18:36:45 -0700732 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000733 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700734 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000735
736 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800737 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000738
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800739 /*
740 * Normally, we should not scan less than batch_size objects in one
741 * pass to avoid too frequent shrinker calls, but if the slab has less
742 * than batch_size objects in total and we are really tight on memory,
743 * we will try to reclaim all available objects, otherwise we can end
744 * up failing allocations although there are plenty of reclaimable
745 * objects spread over several slabs with usage less than the
746 * batch_size.
747 *
748 * We detect the "tight on memory" situations by looking at the total
749 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700750 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800751 * scanning at high prio and therefore should try to reclaim as much as
752 * possible.
753 */
754 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700755 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000756 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800757 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000758
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800759 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700760 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000761 ret = shrinker->scan_objects(shrinker, shrinkctl);
762 if (ret == SHRINK_STOP)
763 break;
764 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000765
Chris Wilsond460acb2017-09-06 16:19:26 -0700766 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
767 total_scan -= shrinkctl->nr_scanned;
768 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
770 cond_resched();
771 }
772
Yang Shi18bb4732021-05-04 18:36:45 -0700773 /*
774 * The deferred work is increased by any new work (delta) that wasn't
775 * done, decreased by old deferred work that was done now.
776 *
777 * And it is capped to two times of the freeable items.
778 */
779 next_deferred = max_t(long, (nr + delta - scanned), 0);
780 next_deferred = min(next_deferred, (2 * freeable));
781
Glauber Costa1d3d4432013-08-28 10:18:04 +1000782 /*
783 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700784 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000785 */
Yang Shi86750832021-05-04 18:36:36 -0700786 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000787
Yang Shi8efb4b52021-05-04 18:36:08 -0700788 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700790}
791
Yang Shi0a432dc2019-09-23 15:38:12 -0700792#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700793static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
794 struct mem_cgroup *memcg, int priority)
795{
Yang Shie4262c42021-05-04 18:36:23 -0700796 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700797 unsigned long ret, freed = 0;
798 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700799
Yang Shi0a432dc2019-09-23 15:38:12 -0700800 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700801 return 0;
802
803 if (!down_read_trylock(&shrinker_rwsem))
804 return 0;
805
Yang Shi468ab842021-05-04 18:36:26 -0700806 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700807 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700808 goto unlock;
809
Yang Shie4262c42021-05-04 18:36:23 -0700810 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811 struct shrink_control sc = {
812 .gfp_mask = gfp_mask,
813 .nid = nid,
814 .memcg = memcg,
815 };
816 struct shrinker *shrinker;
817
818 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700819 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700820 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700821 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700822 continue;
823 }
824
Yang Shi0a432dc2019-09-23 15:38:12 -0700825 /* Call non-slab shrinkers even though kmem is disabled */
826 if (!memcg_kmem_enabled() &&
827 !(shrinker->flags & SHRINKER_NONSLAB))
828 continue;
829
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700830 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700831 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700832 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700833 /*
834 * After the shrinker reported that it had no objects to
835 * free, but before we cleared the corresponding bit in
836 * the memcg shrinker map, a new object might have been
837 * added. To make sure, we have the bit set in this
838 * case, we invoke the shrinker one more time and reset
839 * the bit if it reports that it is not empty anymore.
840 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700841 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700842 *
843 * list_lru_add() shrink_slab_memcg()
844 * list_add_tail() clear_bit()
845 * <MB> <MB>
846 * set_bit() do_shrink_slab()
847 */
848 smp_mb__after_atomic();
849 ret = do_shrink_slab(&sc, shrinker, priority);
850 if (ret == SHRINK_EMPTY)
851 ret = 0;
852 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700853 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700854 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700855 freed += ret;
856
857 if (rwsem_is_contended(&shrinker_rwsem)) {
858 freed = freed ? : 1;
859 break;
860 }
861 }
862unlock:
863 up_read(&shrinker_rwsem);
864 return freed;
865}
Yang Shi0a432dc2019-09-23 15:38:12 -0700866#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700867static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
868 struct mem_cgroup *memcg, int priority)
869{
870 return 0;
871}
Yang Shi0a432dc2019-09-23 15:38:12 -0700872#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700873
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800874/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800875 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800876 * @gfp_mask: allocation context
877 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800878 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800879 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700880 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800881 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700882 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800883 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
884 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700886 * @memcg specifies the memory cgroup to target. Unaware shrinkers
887 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800888 *
Josef Bacik9092c712018-01-31 16:16:26 -0800889 * @priority is sc->priority, we take the number of objects and >> by priority
890 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700891 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800892 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800894static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
895 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800896 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700898 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700899 struct shrinker *shrinker;
900
Yang Shifa1e5122019-08-02 21:48:44 -0700901 /*
902 * The root memcg might be allocated even though memcg is disabled
903 * via "cgroup_disable=memory" boot parameter. This could make
904 * mem_cgroup_is_root() return false, then just run memcg slab
905 * shrink, but skip global shrink. This may result in premature
906 * oom.
907 */
908 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700909 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800910
Tetsuo Handae830c632018-04-05 16:23:35 -0700911 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700912 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700913
914 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800915 struct shrink_control sc = {
916 .gfp_mask = gfp_mask,
917 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800918 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800919 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800920
Kirill Tkhai9b996462018-08-17 15:48:21 -0700921 ret = do_shrink_slab(&sc, shrinker, priority);
922 if (ret == SHRINK_EMPTY)
923 ret = 0;
924 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800925 /*
926 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700927 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800928 * by parallel ongoing shrinking.
929 */
930 if (rwsem_is_contended(&shrinker_rwsem)) {
931 freed = freed ? : 1;
932 break;
933 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800935
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700937out:
938 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000939 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940}
941
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800942void drop_slab_node(int nid)
943{
944 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700945 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800946
947 do {
948 struct mem_cgroup *memcg = NULL;
949
Chunxin Zang069c4112020-10-13 16:56:46 -0700950 if (fatal_signal_pending(current))
951 return;
952
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800953 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700954 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800955 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800956 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800957 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700958 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800959}
960
961void drop_slab(void)
962{
963 int nid;
964
965 for_each_online_node(nid)
966 drop_slab_node(nid);
967}
968
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969static inline int is_page_cache_freeable(struct page *page)
970{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700971 /*
972 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400973 * that isolated the page, the page cache and optional buffer
974 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700975 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700976 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400977 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700978}
979
Yang Shicb165562019-11-30 17:55:28 -0800980static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700981{
Christoph Lameter930d9152006-01-08 01:00:47 -0800982 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700983 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400984 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400986 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987 return 1;
988 return 0;
989}
990
991/*
992 * We detected a synchronous write error writing a page out. Probably
993 * -ENOSPC. We need to propagate that into the address_space for a subsequent
994 * fsync(), msync() or close().
995 *
996 * The tricky part is that after writepage we cannot touch the mapping: nothing
997 * prevents it from being freed up. But we have a ref on the page and once
998 * that page is locked, the mapping is pinned.
999 *
1000 * We're allowed to run sleeping lock_page() here because we know the caller has
1001 * __GFP_FS.
1002 */
1003static void handle_write_error(struct address_space *mapping,
1004 struct page *page, int error)
1005{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001006 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001007 if (page_mapping(page) == mapping)
1008 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001009 unlock_page(page);
1010}
1011
Christoph Lameter04e62a22006-06-23 02:03:38 -07001012/* possible outcome of pageout() */
1013typedef enum {
1014 /* failed to write page out, page is locked */
1015 PAGE_KEEP,
1016 /* move page to the active list, page is locked */
1017 PAGE_ACTIVATE,
1018 /* page has been sent to the disk successfully, page is unlocked */
1019 PAGE_SUCCESS,
1020 /* page is clean and locked */
1021 PAGE_CLEAN,
1022} pageout_t;
1023
Linus Torvalds1da177e2005-04-16 15:20:36 -07001024/*
Andrew Morton1742f192006-03-22 00:08:21 -08001025 * pageout is called by shrink_page_list() for each dirty page.
1026 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 */
Yang Shicb165562019-11-30 17:55:28 -08001028static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001029{
1030 /*
1031 * If the page is dirty, only perform writeback if that write
1032 * will be non-blocking. To prevent this allocation from being
1033 * stalled by pagecache activity. But note that there may be
1034 * stalls if we need to run get_block(). We could test
1035 * PagePrivate for that.
1036 *
Al Viro81742022014-04-03 03:17:43 -04001037 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001038 * this page's queue, we can perform writeback even if that
1039 * will block.
1040 *
1041 * If the page is swapcache, write it back even if that would
1042 * block, for some throttling. This happens by accident, because
1043 * swap_backing_dev_info is bust: it doesn't reflect the
1044 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 */
1046 if (!is_page_cache_freeable(page))
1047 return PAGE_KEEP;
1048 if (!mapping) {
1049 /*
1050 * Some data journaling orphaned pages can have
1051 * page->mapping == NULL while being dirty with clean buffers.
1052 */
David Howells266cf652009-04-03 16:42:36 +01001053 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054 if (try_to_free_buffers(page)) {
1055 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001056 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057 return PAGE_CLEAN;
1058 }
1059 }
1060 return PAGE_KEEP;
1061 }
1062 if (mapping->a_ops->writepage == NULL)
1063 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001064 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001065 return PAGE_KEEP;
1066
1067 if (clear_page_dirty_for_io(page)) {
1068 int res;
1069 struct writeback_control wbc = {
1070 .sync_mode = WB_SYNC_NONE,
1071 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001072 .range_start = 0,
1073 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074 .for_reclaim = 1,
1075 };
1076
1077 SetPageReclaim(page);
1078 res = mapping->a_ops->writepage(page, &wbc);
1079 if (res < 0)
1080 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001081 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001082 ClearPageReclaim(page);
1083 return PAGE_ACTIVATE;
1084 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001085
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086 if (!PageWriteback(page)) {
1087 /* synchronous write or broken a_ops? */
1088 ClearPageReclaim(page);
1089 }
yalin wang3aa23852016-01-14 15:18:30 -08001090 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001091 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 return PAGE_SUCCESS;
1093 }
1094
1095 return PAGE_CLEAN;
1096}
1097
Andrew Mortona649fd92006-10-17 00:09:36 -07001098/*
Nick Piggine2867812008-07-25 19:45:30 -07001099 * Same as remove_mapping, but if the page is removed from the mapping, it
1100 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001101 */
Johannes Weinera5289102014-04-03 14:47:51 -07001102static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001103 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001104{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001105 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001106 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001107
Nick Piggin28e4d962006-09-25 23:31:23 -07001108 BUG_ON(!PageLocked(page));
1109 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001110
Johannes Weiner30472502021-09-02 14:53:18 -07001111 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001112 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001113 * The non racy check for a busy page.
1114 *
1115 * Must be careful with the order of the tests. When someone has
1116 * a ref to the page, it may be possible that they dirty it then
1117 * drop the reference. So if PageDirty is tested before page_count
1118 * here, then the following race may occur:
1119 *
1120 * get_user_pages(&page);
1121 * [user mapping goes away]
1122 * write_to(page);
1123 * !PageDirty(page) [good]
1124 * SetPageDirty(page);
1125 * put_page(page);
1126 * !page_count(page) [good, discard it]
1127 *
1128 * [oops, our write_to data is lost]
1129 *
1130 * Reversing the order of the tests ensures such a situation cannot
1131 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001132 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001133 *
1134 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001135 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001136 */
William Kucharski906d2782019-10-18 20:20:33 -07001137 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001138 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001139 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001140 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001141 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001142 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001143 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001144 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001145
1146 if (PageSwapCache(page)) {
1147 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001148
1149 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001150 if (reclaimed && !mapping_exiting(mapping))
1151 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001152 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001153 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001154 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001155 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001156 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001157 void (*freepage)(struct page *);
1158
1159 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001160 /*
1161 * Remember a shadow entry for reclaimed file cache in
1162 * order to detect refaults, thus thrashing, later on.
1163 *
1164 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001165 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001166 * inode reclaim needs to empty out the radix tree or
1167 * the nodes are lost. Don't plant shadows behind its
1168 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001169 *
1170 * We also don't store shadows for DAX mappings because the
1171 * only page cache pages found in these are zero pages
1172 * covering holes, and because we don't want to mix DAX
1173 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001174 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001175 */
Huang Ying9de4f222020-04-06 20:04:41 -07001176 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001177 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001178 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001179 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001180 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001181
1182 if (freepage != NULL)
1183 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001184 }
1185
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001186 return 1;
1187
1188cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001189 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001190 return 0;
1191}
1192
Linus Torvalds1da177e2005-04-16 15:20:36 -07001193/*
Nick Piggine2867812008-07-25 19:45:30 -07001194 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1195 * someone else has a ref on the page, abort and return 0. If it was
1196 * successfully detached, return 1. Assumes the caller has a single ref on
1197 * this page.
1198 */
1199int remove_mapping(struct address_space *mapping, struct page *page)
1200{
Johannes Weinerb9107182019-11-30 17:55:59 -08001201 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001202 /*
1203 * Unfreezing the refcount with 1 rather than 2 effectively
1204 * drops the pagecache ref for us without requiring another
1205 * atomic operation.
1206 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001207 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001208 return 1;
1209 }
1210 return 0;
1211}
1212
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001213/**
1214 * putback_lru_page - put previously isolated page onto appropriate LRU list
1215 * @page: page to be put back to appropriate lru list
1216 *
1217 * Add previously isolated @page to appropriate LRU list.
1218 * Page may still be unevictable for other reasons.
1219 *
1220 * lru_lock must not be held, interrupts must be enabled.
1221 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001222void putback_lru_page(struct page *page)
1223{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001224 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001225 put_page(page); /* drop ref from isolate */
1226}
1227
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001228enum page_references {
1229 PAGEREF_RECLAIM,
1230 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001231 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001232 PAGEREF_ACTIVATE,
1233};
1234
1235static enum page_references page_check_references(struct page *page,
1236 struct scan_control *sc)
1237{
Johannes Weiner645747462010-03-05 13:42:22 -08001238 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001239 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001240
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001241 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1242 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001243 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001244
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001245 /*
1246 * Mlock lost the isolation race with us. Let try_to_unmap()
1247 * move the page to the unevictable list.
1248 */
1249 if (vm_flags & VM_LOCKED)
1250 return PAGEREF_RECLAIM;
1251
Johannes Weiner645747462010-03-05 13:42:22 -08001252 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001253 /*
1254 * All mapped pages start out with page table
1255 * references from the instantiating fault, so we need
1256 * to look twice if a mapped file page is used more
1257 * than once.
1258 *
1259 * Mark it and spare it for another trip around the
1260 * inactive list. Another page table reference will
1261 * lead to its activation.
1262 *
1263 * Note: the mark is set for activated pages as well
1264 * so that recently deactivated but used pages are
1265 * quickly recovered.
1266 */
1267 SetPageReferenced(page);
1268
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001269 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001270 return PAGEREF_ACTIVATE;
1271
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001272 /*
1273 * Activate file-backed executable pages after first usage.
1274 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001275 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001276 return PAGEREF_ACTIVATE;
1277
Johannes Weiner645747462010-03-05 13:42:22 -08001278 return PAGEREF_KEEP;
1279 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001280
1281 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001282 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001283 return PAGEREF_RECLAIM_CLEAN;
1284
1285 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001286}
1287
Mel Gormane2be15f2013-07-03 15:01:57 -07001288/* Check if a page is dirty or under writeback */
1289static void page_check_dirty_writeback(struct page *page,
1290 bool *dirty, bool *writeback)
1291{
Mel Gormanb4597222013-07-03 15:02:05 -07001292 struct address_space *mapping;
1293
Mel Gormane2be15f2013-07-03 15:01:57 -07001294 /*
1295 * Anonymous pages are not handled by flushers and must be written
1296 * from reclaim context. Do not stall reclaim based on them
1297 */
Huang Ying9de4f222020-04-06 20:04:41 -07001298 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001299 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001300 *dirty = false;
1301 *writeback = false;
1302 return;
1303 }
1304
1305 /* By default assume that the page flags are accurate */
1306 *dirty = PageDirty(page);
1307 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001308
1309 /* Verify dirty/writeback state if the filesystem supports it */
1310 if (!page_has_private(page))
1311 return;
1312
1313 mapping = page_mapping(page);
1314 if (mapping && mapping->a_ops->is_dirty_writeback)
1315 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001316}
1317
Dave Hansen26aa2d12021-09-02 14:59:16 -07001318static struct page *alloc_demote_page(struct page *page, unsigned long node)
1319{
1320 struct migration_target_control mtc = {
1321 /*
1322 * Allocate from 'node', or fail quickly and quietly.
1323 * When this happens, 'page' will likely just be discarded
1324 * instead of migrated.
1325 */
1326 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1327 __GFP_THISNODE | __GFP_NOWARN |
1328 __GFP_NOMEMALLOC | GFP_NOWAIT,
1329 .nid = node
1330 };
1331
1332 return alloc_migration_target(page, (unsigned long)&mtc);
1333}
1334
1335/*
1336 * Take pages on @demote_list and attempt to demote them to
1337 * another node. Pages which are not demoted are left on
1338 * @demote_pages.
1339 */
1340static unsigned int demote_page_list(struct list_head *demote_pages,
1341 struct pglist_data *pgdat)
1342{
1343 int target_nid = next_demotion_node(pgdat->node_id);
1344 unsigned int nr_succeeded;
1345 int err;
1346
1347 if (list_empty(demote_pages))
1348 return 0;
1349
1350 if (target_nid == NUMA_NO_NODE)
1351 return 0;
1352
1353 /* Demotion ignores all cpuset and mempolicy settings */
1354 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1355 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1356 &nr_succeeded);
1357
Yang Shi668e4142021-09-02 14:59:19 -07001358 if (current_is_kswapd())
1359 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1360 else
1361 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1362
Dave Hansen26aa2d12021-09-02 14:59:16 -07001363 return nr_succeeded;
1364}
1365
Nick Piggine2867812008-07-25 19:45:30 -07001366/*
Andrew Morton1742f192006-03-22 00:08:21 -08001367 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001368 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001369static unsigned int shrink_page_list(struct list_head *page_list,
1370 struct pglist_data *pgdat,
1371 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001372 struct reclaim_stat *stat,
1373 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001374{
1375 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001376 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001377 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001378 unsigned int nr_reclaimed = 0;
1379 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001380 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001381
Kirill Tkhai060f0052019-03-05 15:48:15 -08001382 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001383 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001384 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385
Dave Hansen26aa2d12021-09-02 14:59:16 -07001386retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387 while (!list_empty(page_list)) {
1388 struct address_space *mapping;
1389 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001390 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001391 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001392 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393
1394 cond_resched();
1395
1396 page = lru_to_page(page_list);
1397 list_del(&page->lru);
1398
Nick Piggin529ae9a2008-08-02 12:01:03 +02001399 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001400 goto keep;
1401
Sasha Levin309381fea2014-01-23 15:52:54 -08001402 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001404 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001405
1406 /* Account the number of base pages even though THP */
1407 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001408
Hugh Dickins39b5f292012-10-08 16:33:18 -07001409 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001410 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001411
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001412 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001413 goto keep_locked;
1414
Andy Whitcroftc661b072007-08-22 14:01:26 -07001415 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1416 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1417
Mel Gorman283aba92013-07-03 15:01:51 -07001418 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001419 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001420 * reclaim_congested which affects wait_iff_congested. kswapd
1421 * will stall and start writing pages if the tail of the LRU
1422 * is all dirty unqueued pages.
1423 */
1424 page_check_dirty_writeback(page, &dirty, &writeback);
1425 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001426 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001427
1428 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001429 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001430
Mel Gormand04e8ac2013-07-03 15:02:03 -07001431 /*
1432 * Treat this page as congested if the underlying BDI is or if
1433 * pages are cycling through the LRU so quickly that the
1434 * pages marked for immediate reclaim are making it to the
1435 * end of the LRU a second time.
1436 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001437 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001438 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001439 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001440 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001441 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001442
1443 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001444 * If a page at the tail of the LRU is under writeback, there
1445 * are three cases to consider.
1446 *
1447 * 1) If reclaim is encountering an excessive number of pages
1448 * under writeback and this page is both under writeback and
1449 * PageReclaim then it indicates that pages are being queued
1450 * for IO but are being recycled through the LRU before the
1451 * IO can complete. Waiting on the page itself risks an
1452 * indefinite stall if it is impossible to writeback the
1453 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001454 * note that the LRU is being scanned too quickly and the
1455 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001456 *
Tejun Heo97c93412015-05-22 18:23:36 -04001457 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001458 * not marked for immediate reclaim, or the caller does not
1459 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1460 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001461 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001462 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001463 * Require may_enter_fs because we would wait on fs, which
1464 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001465 * enter reclaim, and deadlock if it waits on a page for
1466 * which it is needed to do the write (loop masks off
1467 * __GFP_IO|__GFP_FS for this reason); but more thought
1468 * would probably show more reasons.
1469 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001470 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001471 * PageReclaim. memcg does not have any dirty pages
1472 * throttling so we could easily OOM just because too many
1473 * pages are in writeback and there is nothing else to
1474 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001475 *
1476 * In cases 1) and 2) we activate the pages to get them out of
1477 * the way while we continue scanning for clean pages on the
1478 * inactive list and refilling from the active list. The
1479 * observation here is that waiting for disk writes is more
1480 * expensive than potentially causing reloads down the line.
1481 * Since they're marked for immediate reclaim, they won't put
1482 * memory pressure on the cache working set any longer than it
1483 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001484 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001485 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001486 /* Case 1 above */
1487 if (current_is_kswapd() &&
1488 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001489 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001490 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001491 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001492
1493 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001494 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001495 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001496 /*
1497 * This is slightly racy - end_page_writeback()
1498 * might have just cleared PageReclaim, then
1499 * setting PageReclaim here end up interpreted
1500 * as PageReadahead - but that does not matter
1501 * enough to care. What we do want is for this
1502 * page to have PageReclaim set next time memcg
1503 * reclaim reaches the tests above, so it will
1504 * then wait_on_page_writeback() to avoid OOM;
1505 * and it's also appropriate in global reclaim.
1506 */
1507 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001508 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001509 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001510
1511 /* Case 3 above */
1512 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001513 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001514 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001515 /* then go back and try same page again */
1516 list_add_tail(&page->lru, page_list);
1517 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001518 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001519 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520
Minchan Kim8940b342019-09-25 16:49:11 -07001521 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001522 references = page_check_references(page, sc);
1523
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001524 switch (references) {
1525 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001526 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001527 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001528 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001529 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001530 case PAGEREF_RECLAIM:
1531 case PAGEREF_RECLAIM_CLEAN:
1532 ; /* try to reclaim the page below */
1533 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001534
Linus Torvalds1da177e2005-04-16 15:20:36 -07001535 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001536 * Before reclaiming the page, try to relocate
1537 * its contents to another node.
1538 */
1539 if (do_demote_pass &&
1540 (thp_migration_supported() || !PageTransHuge(page))) {
1541 list_add(&page->lru, &demote_pages);
1542 unlock_page(page);
1543 continue;
1544 }
1545
1546 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001547 * Anonymous process memory has backing store?
1548 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001549 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001551 if (PageAnon(page) && PageSwapBacked(page)) {
1552 if (!PageSwapCache(page)) {
1553 if (!(sc->gfp_mask & __GFP_IO))
1554 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001555 if (page_maybe_dma_pinned(page))
1556 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001557 if (PageTransHuge(page)) {
1558 /* cannot split THP, skip it */
1559 if (!can_split_huge_page(page, NULL))
1560 goto activate_locked;
1561 /*
1562 * Split pages without a PMD map right
1563 * away. Chances are some or all of the
1564 * tail pages can be freed without IO.
1565 */
1566 if (!compound_mapcount(page) &&
1567 split_huge_page_to_list(page,
1568 page_list))
1569 goto activate_locked;
1570 }
1571 if (!add_to_swap(page)) {
1572 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001573 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001574 /* Fallback to swap normal pages */
1575 if (split_huge_page_to_list(page,
1576 page_list))
1577 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001578#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1579 count_vm_event(THP_SWPOUT_FALLBACK);
1580#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001581 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001582 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001583 }
Minchan Kim0f074652017-07-06 15:37:24 -07001584
Kirill Tkhai4b793062020-04-01 21:10:18 -07001585 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001586
1587 /* Adding to swap updated mapping */
1588 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001589 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001590 } else if (unlikely(PageTransHuge(page))) {
1591 /* Split file THP */
1592 if (split_huge_page_to_list(page, page_list))
1593 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001594 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001595
1596 /*
Yang Shi98879b32019-07-11 20:59:30 -07001597 * THP may get split above, need minus tail pages and update
1598 * nr_pages to avoid accounting tail pages twice.
1599 *
1600 * The tail pages that are added into swap cache successfully
1601 * reach here.
1602 */
1603 if ((nr_pages > 1) && !PageTransHuge(page)) {
1604 sc->nr_scanned -= (nr_pages - 1);
1605 nr_pages = 1;
1606 }
1607
1608 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001609 * The page is mapped into the page tables of one or more
1610 * processes. Try to unmap it here.
1611 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001612 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001613 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001614 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001615
1616 if (unlikely(PageTransHuge(page)))
1617 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001618
Yang Shi1fb08ac2021-06-30 18:52:01 -07001619 try_to_unmap(page, flags);
1620 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001621 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001622 if (!was_swapbacked && PageSwapBacked(page))
1623 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001624 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 }
1626 }
1627
1628 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001629 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001630 * Only kswapd can writeback filesystem pages
1631 * to avoid risk of stack overflow. But avoid
1632 * injecting inefficient single-page IO into
1633 * flusher writeback as much as possible: only
1634 * write pages when we've encountered many
1635 * dirty pages, and when we've already scanned
1636 * the rest of the LRU for clean pages and see
1637 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001638 */
Huang Ying9de4f222020-04-06 20:04:41 -07001639 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001640 (!current_is_kswapd() || !PageReclaim(page) ||
1641 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001642 /*
1643 * Immediately reclaim when written back.
1644 * Similar in principal to deactivate_page()
1645 * except we already have the page isolated
1646 * and know it's dirty
1647 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001648 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001649 SetPageReclaim(page);
1650
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001651 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001652 }
1653
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001654 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001655 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001656 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001657 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001658 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001659 goto keep_locked;
1660
Mel Gormand950c942015-09-04 15:47:35 -07001661 /*
1662 * Page is dirty. Flush the TLB if a writable entry
1663 * potentially exists to avoid CPU writes after IO
1664 * starts and then write it out here.
1665 */
1666 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001667 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001668 case PAGE_KEEP:
1669 goto keep_locked;
1670 case PAGE_ACTIVATE:
1671 goto activate_locked;
1672 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001673 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001674
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001675 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001676 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001677 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001678 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001679
Linus Torvalds1da177e2005-04-16 15:20:36 -07001680 /*
1681 * A synchronous write - probably a ramdisk. Go
1682 * ahead and try to reclaim the page.
1683 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001684 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 goto keep;
1686 if (PageDirty(page) || PageWriteback(page))
1687 goto keep_locked;
1688 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001689 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001690 case PAGE_CLEAN:
1691 ; /* try to free the page below */
1692 }
1693 }
1694
1695 /*
1696 * If the page has buffers, try to free the buffer mappings
1697 * associated with this page. If we succeed we try to free
1698 * the page as well.
1699 *
1700 * We do this even if the page is PageDirty().
1701 * try_to_release_page() does not perform I/O, but it is
1702 * possible for a page to have PageDirty set, but it is actually
1703 * clean (all its buffers are clean). This happens if the
1704 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001705 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001706 * try_to_release_page() will discover that cleanness and will
1707 * drop the buffers and mark the page clean - it can be freed.
1708 *
1709 * Rarely, pages can have buffers and no ->mapping. These are
1710 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001711 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001712 * and if that worked, and the page is no longer mapped into
1713 * process address space (page_count == 1) it can be freed.
1714 * Otherwise, leave the page on the LRU so it is swappable.
1715 */
David Howells266cf652009-04-03 16:42:36 +01001716 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717 if (!try_to_release_page(page, sc->gfp_mask))
1718 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001719 if (!mapping && page_count(page) == 1) {
1720 unlock_page(page);
1721 if (put_page_testzero(page))
1722 goto free_it;
1723 else {
1724 /*
1725 * rare race with speculative reference.
1726 * the speculative reference will free
1727 * this page shortly, so we may
1728 * increment nr_reclaimed here (and
1729 * leave it off the LRU).
1730 */
1731 nr_reclaimed++;
1732 continue;
1733 }
1734 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001735 }
1736
Shaohua Li802a3a92017-05-03 14:52:32 -07001737 if (PageAnon(page) && !PageSwapBacked(page)) {
1738 /* follow __remove_mapping for reference */
1739 if (!page_ref_freeze(page, 1))
1740 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001741 /*
1742 * The page has only one reference left, which is
1743 * from the isolation. After the caller puts the
1744 * page back on lru and drops the reference, the
1745 * page will be freed anyway. It doesn't matter
1746 * which lru it goes. So we don't bother checking
1747 * PageDirty here.
1748 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001749 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001750 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001751 } else if (!mapping || !__remove_mapping(mapping, page, true,
1752 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001753 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001754
1755 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001756free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001757 /*
1758 * THP may get swapped out in a whole, need account
1759 * all base pages.
1760 */
1761 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001762
1763 /*
1764 * Is there need to periodically free_page_list? It would
1765 * appear not as the counts should be low
1766 */
Yang Shi7ae88532019-09-23 15:38:09 -07001767 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001768 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001769 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001770 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001771 continue;
1772
Yang Shi98879b32019-07-11 20:59:30 -07001773activate_locked_split:
1774 /*
1775 * The tail pages that are failed to add into swap cache
1776 * reach here. Fixup nr_scanned and nr_pages.
1777 */
1778 if (nr_pages > 1) {
1779 sc->nr_scanned -= (nr_pages - 1);
1780 nr_pages = 1;
1781 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001782activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001783 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001784 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1785 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001786 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001787 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001788 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001789 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001790 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001791 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001792 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001793 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001794keep_locked:
1795 unlock_page(page);
1796keep:
1797 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001798 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001799 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001800 /* 'page_list' is always empty here */
1801
1802 /* Migrate pages selected for demotion */
1803 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1804 /* Pages that could not be demoted are still in @demote_pages */
1805 if (!list_empty(&demote_pages)) {
1806 /* Pages which failed to demoted go back on @page_list for retry: */
1807 list_splice_init(&demote_pages, page_list);
1808 do_demote_pass = false;
1809 goto retry;
1810 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001811
Yang Shi98879b32019-07-11 20:59:30 -07001812 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1813
Johannes Weiner747db952014-08-08 14:19:24 -07001814 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001815 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001816 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001817
Linus Torvalds1da177e2005-04-16 15:20:36 -07001818 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001819 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001820
Andrew Morton05ff5132006-03-22 00:08:20 -08001821 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001822}
1823
Maninder Singh730ec8c2020-06-03 16:01:18 -07001824unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001825 struct list_head *page_list)
1826{
1827 struct scan_control sc = {
1828 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001829 .may_unmap = 1,
1830 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001831 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001832 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001833 struct page *page, *next;
1834 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001835 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001836
1837 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001838 if (!PageHuge(page) && page_is_file_lru(page) &&
1839 !PageDirty(page) && !__PageMovable(page) &&
1840 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001841 ClearPageActive(page);
1842 list_move(&page->lru, &clean_pages);
1843 }
1844 }
1845
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001846 /*
1847 * We should be safe here since we are only dealing with file pages and
1848 * we are not kswapd and therefore cannot write dirty file pages. But
1849 * call memalloc_noreclaim_save() anyway, just in case these conditions
1850 * change in the future.
1851 */
1852 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001853 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001854 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001855 memalloc_noreclaim_restore(noreclaim_flag);
1856
Minchan Kim02c6de82012-10-08 16:31:55 -07001857 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001858 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1859 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001860 /*
1861 * Since lazyfree pages are isolated from file LRU from the beginning,
1862 * they will rotate back to anonymous LRU in the end if it failed to
1863 * discard so isolated count will be mismatched.
1864 * Compensate the isolated count for both LRU lists.
1865 */
1866 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1867 stat.nr_lazyfree_fail);
1868 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001869 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001870 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001871}
1872
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001873/*
1874 * Attempt to remove the specified page from its LRU. Only take this page
1875 * if it is of the appropriate PageActive status. Pages which are being
1876 * freed elsewhere are also ignored.
1877 *
1878 * page: page to consider
1879 * mode: one of the LRU isolation modes defined above
1880 *
Alex Shic2135f72021-02-24 12:08:01 -08001881 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001882 */
Alex Shic2135f72021-02-24 12:08:01 -08001883bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001884{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001885 /* Only take pages on the LRU. */
1886 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001887 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001888
Minchan Kime46a2872012-10-08 16:33:48 -07001889 /* Compaction should not handle unevictable pages but CMA can do so */
1890 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001891 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001892
Mel Gormanc8244932012-01-12 17:19:38 -08001893 /*
1894 * To minimise LRU disruption, the caller can indicate that it only
1895 * wants to isolate pages it will be able to operate on without
1896 * blocking - clean pages for the most part.
1897 *
Mel Gormanc8244932012-01-12 17:19:38 -08001898 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1899 * that it is possible to migrate without blocking
1900 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001901 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001902 /* All the caller can do on PageWriteback is block */
1903 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001904 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001905
1906 if (PageDirty(page)) {
1907 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001908 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001909
Mel Gormanc8244932012-01-12 17:19:38 -08001910 /*
1911 * Only pages without mappings or that have a
1912 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001913 * without blocking. However, we can be racing with
1914 * truncation so it's necessary to lock the page
1915 * to stabilise the mapping as truncation holds
1916 * the page lock until after the page is removed
1917 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001918 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001919 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001920 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001921
Mel Gormanc8244932012-01-12 17:19:38 -08001922 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001923 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001924 unlock_page(page);
1925 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001926 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001927 }
1928 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001929
Minchan Kimf80c0672011-10-31 17:06:55 -07001930 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001931 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001932
Alex Shic2135f72021-02-24 12:08:01 -08001933 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001934}
1935
Mel Gorman7ee36a12016-07-28 15:47:17 -07001936/*
1937 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001938 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001939 */
1940static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001941 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001942{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001943 int zid;
1944
Mel Gorman7ee36a12016-07-28 15:47:17 -07001945 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1946 if (!nr_zone_taken[zid])
1947 continue;
1948
Wei Yanga892cb62020-06-03 16:01:12 -07001949 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001950 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001951
Mel Gorman7ee36a12016-07-28 15:47:17 -07001952}
1953
Mel Gormanf611fab2021-06-30 18:53:19 -07001954/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001955 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1956 *
1957 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001958 * shrink the lists perform better by taking out a batch of pages
1959 * and working on them outside the LRU lock.
1960 *
1961 * For pagecache intensive workloads, this function is the hottest
1962 * spot in the kernel (apart from copy_*_user functions).
1963 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001964 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001965 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001966 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001967 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001968 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001969 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001970 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001971 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001972 *
1973 * returns how many pages were moved onto *@dst.
1974 */
Andrew Morton69e05942006-03-22 00:08:19 -08001975static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001976 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001977 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001978 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001979{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001980 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001981 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001982 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001983 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001984 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001985 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001986 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001987 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988
Yang Shi98879b32019-07-11 20:59:30 -07001989 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001990 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001991 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001992 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001993
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994 page = lru_to_page(src);
1995 prefetchw_prev_lru_page(page, src, flags);
1996
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001997 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001998 total_scan += nr_pages;
1999
Mel Gormanb2e18752016-07-28 15:45:37 -07002000 if (page_zonenum(page) > sc->reclaim_idx) {
2001 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002002 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002003 continue;
2004 }
2005
Minchan Kim791b48b2017-05-12 15:47:06 -07002006 /*
2007 * Do not count skipped pages because that makes the function
2008 * return with no isolated pages if the LRU mostly contains
2009 * ineligible pages. This causes the VM to not reclaim any
2010 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002011 *
2012 * Account all tail pages of THP. This would not cause
2013 * premature OOM since __isolate_lru_page() returns -EBUSY
2014 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002015 */
Yang Shi98879b32019-07-11 20:59:30 -07002016 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002017 if (!__isolate_lru_page_prepare(page, mode)) {
2018 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002019 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002020 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002021 }
Alex Shic2135f72021-02-24 12:08:01 -08002022 /*
2023 * Be careful not to clear PageLRU until after we're
2024 * sure the page is not being freed elsewhere -- the
2025 * page release code relies on it.
2026 */
2027 if (unlikely(!get_page_unless_zero(page))) {
2028 list_move(&page->lru, src);
2029 continue;
2030 }
2031
2032 if (!TestClearPageLRU(page)) {
2033 /* Another thread is already isolating this page */
2034 put_page(page);
2035 list_move(&page->lru, src);
2036 continue;
2037 }
2038
2039 nr_taken += nr_pages;
2040 nr_zone_taken[page_zonenum(page)] += nr_pages;
2041 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002042 }
2043
Mel Gormanb2e18752016-07-28 15:45:37 -07002044 /*
2045 * Splice any skipped pages to the start of the LRU list. Note that
2046 * this disrupts the LRU order when reclaiming for lower zones but
2047 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2048 * scanning would soon rescan the same pages to skip and put the
2049 * system at risk of premature OOM.
2050 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002051 if (!list_empty(&pages_skipped)) {
2052 int zid;
2053
Johannes Weiner3db65812017-05-03 14:52:13 -07002054 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002055 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2056 if (!nr_skipped[zid])
2057 continue;
2058
2059 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002060 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002061 }
2062 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002063 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002064 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002065 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002066 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002067 return nr_taken;
2068}
2069
Nick Piggin62695a82008-10-18 20:26:09 -07002070/**
2071 * isolate_lru_page - tries to isolate a page from its LRU list
2072 * @page: page to isolate from its LRU list
2073 *
2074 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2075 * vmstat statistic corresponding to whatever LRU list the page was on.
2076 *
2077 * Returns 0 if the page was removed from an LRU list.
2078 * Returns -EBUSY if the page was not on an LRU list.
2079 *
2080 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002081 * the active list, it will have PageActive set. If it was found on
2082 * the unevictable list, it will have the PageUnevictable bit set. That flag
2083 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002084 *
2085 * The vmstat statistic corresponding to the list on which the page was
2086 * found will be decremented.
2087 *
2088 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002089 *
Nick Piggin62695a82008-10-18 20:26:09 -07002090 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002091 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002092 * without a stable reference).
2093 * (2) the lru_lock must not be held.
2094 * (3) interrupts must be enabled.
2095 */
2096int isolate_lru_page(struct page *page)
2097{
2098 int ret = -EBUSY;
2099
Sasha Levin309381fea2014-01-23 15:52:54 -08002100 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002101 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002102
Alex Shid25b5bd2020-12-15 12:34:16 -08002103 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002104 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002105
Alex Shid25b5bd2020-12-15 12:34:16 -08002106 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002107 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002108 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002109 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002110 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002111 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002112
Nick Piggin62695a82008-10-18 20:26:09 -07002113 return ret;
2114}
2115
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002116/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002117 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002118 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002119 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2120 * the LRU list will go small and be scanned faster than necessary, leading to
2121 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002122 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002123static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002124 struct scan_control *sc)
2125{
2126 unsigned long inactive, isolated;
2127
2128 if (current_is_kswapd())
2129 return 0;
2130
Johannes Weinerb5ead352019-11-30 17:55:40 -08002131 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002132 return 0;
2133
2134 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002135 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2136 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002138 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2139 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002140 }
2141
Fengguang Wu3cf23842012-12-18 14:23:31 -08002142 /*
2143 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2144 * won't get blocked by normal direct-reclaimers, forming a circular
2145 * deadlock.
2146 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002147 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002148 inactive >>= 3;
2149
Rik van Riel35cd7812009-09-21 17:01:38 -07002150 return isolated > inactive;
2151}
2152
Kirill Tkhaia222f342019-05-13 17:17:00 -07002153/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002154 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2155 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002156 *
2157 * Returns the number of pages moved to the given lruvec.
2158 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002159static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2160 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002161{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002162 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002163 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002164 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002165
Kirill Tkhaia222f342019-05-13 17:17:00 -07002166 while (!list_empty(list)) {
2167 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002168 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002169 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002170 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002171 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002172 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002173 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002174 continue;
2175 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002176
Alex Shi3d06afa2020-12-15 12:33:37 -08002177 /*
2178 * The SetPageLRU needs to be kept here for list integrity.
2179 * Otherwise:
2180 * #0 move_pages_to_lru #1 release_pages
2181 * if !put_page_testzero
2182 * if (put_page_testzero())
2183 * !PageLRU //skip lru_lock
2184 * SetPageLRU()
2185 * list_add(&page->lru,)
2186 * list_add(&page->lru,)
2187 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002188 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002189
Alex Shi3d06afa2020-12-15 12:33:37 -08002190 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002191 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002192
2193 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002194 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002195 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002196 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002197 } else
2198 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002199
2200 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002201 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002202
Alex Shiafca9152020-12-15 12:34:02 -08002203 /*
2204 * All pages were isolated from the same lruvec (and isolation
2205 * inhibits memcg migration).
2206 */
Muchun Song7467c392021-06-28 19:37:59 -07002207 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002208 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002209 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002210 nr_moved += nr_pages;
2211 if (PageActive(page))
2212 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002213 }
Mel Gorman66635622010-08-09 17:19:30 -07002214
Hugh Dickins3f797682012-01-12 17:20:07 -08002215 /*
2216 * To save our caller's stack, now use input list for pages to free.
2217 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002218 list_splice(&pages_to_free, list);
2219
2220 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002221}
2222
2223/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002224 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002225 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002226 * In that case we should only throttle if the backing device it is
2227 * writing to is congested. In other cases it is safe to throttle.
2228 */
2229static int current_may_throttle(void)
2230{
NeilBrowna37b0712020-06-01 21:48:18 -07002231 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002232 current->backing_dev_info == NULL ||
2233 bdi_write_congested(current->backing_dev_info);
2234}
2235
2236/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002237 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002238 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002239 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002240static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002241shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002242 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002243{
2244 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002245 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002246 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002247 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002248 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002249 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002250 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002251 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002252 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002253
Mel Gorman599d0c92016-07-28 15:45:31 -07002254 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002255 if (stalled)
2256 return 0;
2257
2258 /* wait a bit for the reclaimer. */
2259 msleep(100);
2260 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002261
2262 /* We are about to die and free our memory. Return now. */
2263 if (fatal_signal_pending(current))
2264 return SWAP_CLUSTER_MAX;
2265 }
2266
Linus Torvalds1da177e2005-04-16 15:20:36 -07002267 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002268
Alex Shi6168d0d2020-12-15 12:34:29 -08002269 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002270
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002271 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002272 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002273
Mel Gorman599d0c92016-07-28 15:45:31 -07002274 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002275 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002276 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002277 __count_vm_events(item, nr_scanned);
2278 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002279 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2280
Alex Shi6168d0d2020-12-15 12:34:29 -08002281 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002282
Hillf Dantond563c052012-03-21 16:34:02 -07002283 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002284 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002285
Shakeel Butt013339d2020-12-14 19:06:39 -08002286 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002287
Alex Shi6168d0d2020-12-15 12:34:29 -08002288 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002289 move_pages_to_lru(lruvec, &page_list);
2290
2291 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002292 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002293 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002294 __count_vm_events(item, nr_reclaimed);
2295 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002296 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002297 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002298
Alex Shi75cc3c92020-12-15 14:20:50 -08002299 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002300 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002301 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002302
Mel Gorman92df3a72011-10-31 17:07:56 -07002303 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002304 * If dirty pages are scanned that are not queued for IO, it
2305 * implies that flushers are not doing their job. This can
2306 * happen when memory pressure pushes dirty pages to the end of
2307 * the LRU before the dirty limits are breached and the dirty
2308 * data has expired. It can also happen when the proportion of
2309 * dirty pages grows not through writes but through memory
2310 * pressure reclaiming all the clean cache. And in some cases,
2311 * the flushers simply cannot keep up with the allocation
2312 * rate. Nudge the flusher threads in case they are asleep.
2313 */
2314 if (stat.nr_unqueued_dirty == nr_taken)
2315 wakeup_flusher_threads(WB_REASON_VMSCAN);
2316
Andrey Ryabinind108c772018-04-10 16:27:59 -07002317 sc->nr.dirty += stat.nr_dirty;
2318 sc->nr.congested += stat.nr_congested;
2319 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2320 sc->nr.writeback += stat.nr_writeback;
2321 sc->nr.immediate += stat.nr_immediate;
2322 sc->nr.taken += nr_taken;
2323 if (file)
2324 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002325
Mel Gorman599d0c92016-07-28 15:45:31 -07002326 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002327 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002328 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002329}
2330
Hugh Dickins15b44732020-12-15 14:21:31 -08002331/*
2332 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2333 *
2334 * We move them the other way if the page is referenced by one or more
2335 * processes.
2336 *
2337 * If the pages are mostly unmapped, the processing is fast and it is
2338 * appropriate to hold lru_lock across the whole operation. But if
2339 * the pages are mapped, the processing is slow (page_referenced()), so
2340 * we should drop lru_lock around each page. It's impossible to balance
2341 * this, so instead we remove the pages from the LRU while processing them.
2342 * It is safe to rely on PG_active against the non-LRU pages in here because
2343 * nobody will play with that bit on a non-LRU page.
2344 *
2345 * The downside is that we have to touch page->_refcount against each page.
2346 * But we had to alter page->flags anyway.
2347 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002348static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002349 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002350 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002351 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002352{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002353 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002354 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002355 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002357 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002358 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002359 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002360 unsigned nr_deactivate, nr_activate;
2361 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002362 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002363 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002364
2365 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002366
Alex Shi6168d0d2020-12-15 12:34:29 -08002367 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002368
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002369 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002370 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002371
Mel Gorman599d0c92016-07-28 15:45:31 -07002372 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002373
Shakeel Butt912c0572020-08-06 23:26:32 -07002374 if (!cgroup_reclaim(sc))
2375 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002376 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002377
Alex Shi6168d0d2020-12-15 12:34:29 -08002378 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 while (!list_empty(&l_hold)) {
2381 cond_resched();
2382 page = lru_to_page(&l_hold);
2383 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002384
Hugh Dickins39b5f292012-10-08 16:33:18 -07002385 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002386 putback_lru_page(page);
2387 continue;
2388 }
2389
Mel Gormancc715d92012-03-21 16:34:00 -07002390 if (unlikely(buffer_heads_over_limit)) {
2391 if (page_has_private(page) && trylock_page(page)) {
2392 if (page_has_private(page))
2393 try_to_release_page(page, 0);
2394 unlock_page(page);
2395 }
2396 }
2397
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002398 if (page_referenced(page, 0, sc->target_mem_cgroup,
2399 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002400 /*
2401 * Identify referenced, file-backed active pages and
2402 * give them one more trip around the active list. So
2403 * that executable code get better chances to stay in
2404 * memory under moderate memory pressure. Anon pages
2405 * are not likely to be evicted by use-once streaming
2406 * IO, plus JVM can create lots of anon VM_EXEC pages,
2407 * so we ignore them here.
2408 */
Huang Ying9de4f222020-04-06 20:04:41 -07002409 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002410 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002411 list_add(&page->lru, &l_active);
2412 continue;
2413 }
2414 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002415
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002416 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002417 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002418 list_add(&page->lru, &l_inactive);
2419 }
2420
Andrew Mortonb5557492009-01-06 14:40:13 -08002421 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002422 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002423 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002424 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002425
Kirill Tkhaia222f342019-05-13 17:17:00 -07002426 nr_activate = move_pages_to_lru(lruvec, &l_active);
2427 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002428 /* Keep all free pages in l_active list */
2429 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002430
2431 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2432 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2433
Mel Gorman599d0c92016-07-28 15:45:31 -07002434 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002435 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002436
Kirill Tkhaif372d892019-05-13 17:16:57 -07002437 mem_cgroup_uncharge_list(&l_active);
2438 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002439 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2440 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002441}
2442
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002443unsigned long reclaim_pages(struct list_head *page_list)
2444{
Yang Shif661d002020-04-01 21:10:05 -07002445 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002446 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002447 LIST_HEAD(node_page_list);
2448 struct reclaim_stat dummy_stat;
2449 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002450 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002451 struct scan_control sc = {
2452 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002453 .may_writepage = 1,
2454 .may_unmap = 1,
2455 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002456 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002457 };
2458
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002459 noreclaim_flag = memalloc_noreclaim_save();
2460
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002461 while (!list_empty(page_list)) {
2462 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002463 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002464 nid = page_to_nid(page);
2465 INIT_LIST_HEAD(&node_page_list);
2466 }
2467
2468 if (nid == page_to_nid(page)) {
2469 ClearPageActive(page);
2470 list_move(&page->lru, &node_page_list);
2471 continue;
2472 }
2473
2474 nr_reclaimed += shrink_page_list(&node_page_list,
2475 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002476 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002477 while (!list_empty(&node_page_list)) {
2478 page = lru_to_page(&node_page_list);
2479 list_del(&page->lru);
2480 putback_lru_page(page);
2481 }
2482
Yang Shif661d002020-04-01 21:10:05 -07002483 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 }
2485
2486 if (!list_empty(&node_page_list)) {
2487 nr_reclaimed += shrink_page_list(&node_page_list,
2488 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002489 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002490 while (!list_empty(&node_page_list)) {
2491 page = lru_to_page(&node_page_list);
2492 list_del(&page->lru);
2493 putback_lru_page(page);
2494 }
2495 }
2496
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002497 memalloc_noreclaim_restore(noreclaim_flag);
2498
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002499 return nr_reclaimed;
2500}
2501
Johannes Weinerb91ac372019-11-30 17:56:02 -08002502static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2503 struct lruvec *lruvec, struct scan_control *sc)
2504{
2505 if (is_active_lru(lru)) {
2506 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2507 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2508 else
2509 sc->skipped_deactivate = 1;
2510 return 0;
2511 }
2512
2513 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2514}
2515
Rik van Riel59dc76b2016-05-20 16:56:31 -07002516/*
2517 * The inactive anon list should be small enough that the VM never has
2518 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002519 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002520 * The inactive file list should be small enough to leave most memory
2521 * to the established workingset on the scan-resistant active list,
2522 * but large enough to avoid thrashing the aggregate readahead window.
2523 *
2524 * Both inactive lists should also be large enough that each inactive
2525 * page has a chance to be referenced again before it is reclaimed.
2526 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002527 * If that fails and refaulting is observed, the inactive list grows.
2528 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002529 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002530 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002531 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2532 *
2533 * total target max
2534 * memory ratio inactive
2535 * -------------------------------------
2536 * 10MB 1 5MB
2537 * 100MB 1 50MB
2538 * 1GB 3 250MB
2539 * 10GB 10 0.9GB
2540 * 100GB 31 3GB
2541 * 1TB 101 10GB
2542 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002543 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002544static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002545{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002546 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002547 unsigned long inactive, active;
2548 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002549 unsigned long gb;
2550
Johannes Weinerb91ac372019-11-30 17:56:02 -08002551 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2552 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002553
Johannes Weinerb91ac372019-11-30 17:56:02 -08002554 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002555 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002556 inactive_ratio = int_sqrt(10 * gb);
2557 else
2558 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002559
Rik van Riel59dc76b2016-05-20 16:56:31 -07002560 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002561}
2562
Johannes Weiner9a265112013-02-22 16:32:17 -08002563enum scan_balance {
2564 SCAN_EQUAL,
2565 SCAN_FRACT,
2566 SCAN_ANON,
2567 SCAN_FILE,
2568};
2569
Yu Zhao3eb07702020-09-27 20:49:08 -06002570static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2571{
2572 unsigned long file;
2573 struct lruvec *target_lruvec;
2574
Yu Zhaoa1537a62022-01-27 20:32:37 -07002575 if (lru_gen_enabled())
2576 return;
2577
Yu Zhao3eb07702020-09-27 20:49:08 -06002578 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2579
2580 /*
2581 * Flush the memory cgroup stats, so that we read accurate per-memcg
2582 * lruvec stats for heuristics.
2583 */
2584 mem_cgroup_flush_stats();
2585
2586 /*
2587 * Determine the scan balance between anon and file LRUs.
2588 */
2589 spin_lock_irq(&target_lruvec->lru_lock);
2590 sc->anon_cost = target_lruvec->anon_cost;
2591 sc->file_cost = target_lruvec->file_cost;
2592 spin_unlock_irq(&target_lruvec->lru_lock);
2593
2594 /*
2595 * Target desirable inactive:active list ratios for the anon
2596 * and file LRU lists.
2597 */
2598 if (!sc->force_deactivate) {
2599 unsigned long refaults;
2600
2601 refaults = lruvec_page_state(target_lruvec,
2602 WORKINGSET_ACTIVATE_ANON);
2603 if (refaults != target_lruvec->refaults[0] ||
2604 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2605 sc->may_deactivate |= DEACTIVATE_ANON;
2606 else
2607 sc->may_deactivate &= ~DEACTIVATE_ANON;
2608
2609 /*
2610 * When refaults are being observed, it means a new
2611 * workingset is being established. Deactivate to get
2612 * rid of any stale active pages quickly.
2613 */
2614 refaults = lruvec_page_state(target_lruvec,
2615 WORKINGSET_ACTIVATE_FILE);
2616 if (refaults != target_lruvec->refaults[1] ||
2617 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2618 sc->may_deactivate |= DEACTIVATE_FILE;
2619 else
2620 sc->may_deactivate &= ~DEACTIVATE_FILE;
2621 } else
2622 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2623
2624 /*
2625 * If we have plenty of inactive file pages that aren't
2626 * thrashing, try to reclaim those first before touching
2627 * anonymous pages.
2628 */
2629 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2630 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2631 sc->cache_trim_mode = 1;
2632 else
2633 sc->cache_trim_mode = 0;
2634
2635 /*
2636 * Prevent the reclaimer from falling into the cache trap: as
2637 * cache pages start out inactive, every cache fault will tip
2638 * the scan balance towards the file LRU. And as the file LRU
2639 * shrinks, so does the window for rotation from references.
2640 * This means we have a runaway feedback loop where a tiny
2641 * thrashing file LRU becomes infinitely more attractive than
2642 * anon pages. Try to detect this based on file LRU size.
2643 */
2644 if (!cgroup_reclaim(sc)) {
2645 unsigned long total_high_wmark = 0;
2646 unsigned long free, anon;
2647 int z;
2648
2649 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2650 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2651 node_page_state(pgdat, NR_INACTIVE_FILE);
2652
2653 for (z = 0; z < MAX_NR_ZONES; z++) {
2654 struct zone *zone = &pgdat->node_zones[z];
2655
2656 if (!managed_zone(zone))
2657 continue;
2658
2659 total_high_wmark += high_wmark_pages(zone);
2660 }
2661
2662 /*
2663 * Consider anon: if that's low too, this isn't a
2664 * runaway file reclaim problem, but rather just
2665 * extreme pressure. Reclaim as per usual then.
2666 */
2667 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2668
2669 sc->file_is_tiny =
2670 file + free <= total_high_wmark &&
2671 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2672 anon >> sc->priority;
2673 }
2674}
2675
Linus Torvalds1da177e2005-04-16 15:20:36 -07002676/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002677 * Determine how aggressively the anon and file LRU lists should be
2678 * scanned. The relative value of each set of LRU lists is determined
2679 * by looking at the fraction of the pages scanned we did rotate back
2680 * onto the active list instead of evict.
2681 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002682 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2683 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002684 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002685static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2686 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002687{
Keith Buscha2a36482021-09-02 14:59:26 -07002688 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002689 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002690 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002691 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002692 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002693 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002694 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002695 unsigned long ap, fp;
2696 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002697 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002698
2699 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002700 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002701 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002702 goto out;
2703 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002704
Johannes Weiner10316b32013-02-22 16:32:14 -08002705 /*
2706 * Global reclaim will swap to prevent OOM even with no
2707 * swappiness, but memcg users want to use this knob to
2708 * disable swapping for individual groups completely when
2709 * using the memory controller's swap limit feature would be
2710 * too expensive.
2711 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002712 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002713 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002714 goto out;
2715 }
2716
2717 /*
2718 * Do not apply any pressure balancing cleverness when the
2719 * system is close to OOM, scan both anon and file equally
2720 * (unless the swappiness setting disagrees with swapping).
2721 */
Johannes Weiner02695172014-08-06 16:06:17 -07002722 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002723 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002724 goto out;
2725 }
2726
Johannes Weiner11d16c22013-02-22 16:32:15 -08002727 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002728 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002729 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002730 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002731 scan_balance = SCAN_ANON;
2732 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002733 }
2734
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002735 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2736
Johannes Weiner62376252014-05-06 12:50:07 -07002737 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002738 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002739 * anything from the anonymous working right now. But when balancing
2740 * anon and page cache files for reclaim, allow swapping of anon pages
2741 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002742 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002743 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002744 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002745 goto out;
2746 }
2747
Johannes Weiner9a265112013-02-22 16:32:17 -08002748 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002749 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002750 * Calculate the pressure balance between anon and file pages.
2751 *
2752 * The amount of pressure we put on each LRU is inversely
2753 * proportional to the cost of reclaiming each list, as
2754 * determined by the share of pages that are refaulting, times
2755 * the relative IO cost of bringing back a swapped out
2756 * anonymous page vs reloading a filesystem page (swappiness).
2757 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002758 * Although we limit that influence to ensure no list gets
2759 * left behind completely: at least a third of the pressure is
2760 * applied, before swappiness.
2761 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002762 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002763 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002764 total_cost = sc->anon_cost + sc->file_cost;
2765 anon_cost = total_cost + sc->anon_cost;
2766 file_cost = total_cost + sc->file_cost;
2767 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002768
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002769 ap = swappiness * (total_cost + 1);
2770 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002771
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002772 fp = (200 - swappiness) * (total_cost + 1);
2773 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002774
Shaohua Li76a33fc2010-05-24 14:32:36 -07002775 fraction[0] = ap;
2776 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002777 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002778out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002779 for_each_evictable_lru(lru) {
2780 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002781 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002782 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002783 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002784
Chris Down9783aa92019-10-06 17:58:32 -07002785 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002786 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2787 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002788
Johannes Weinerf56ce412021-08-19 19:04:21 -07002789 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002790 /*
2791 * Scale a cgroup's reclaim pressure by proportioning
2792 * its current usage to its memory.low or memory.min
2793 * setting.
2794 *
2795 * This is important, as otherwise scanning aggression
2796 * becomes extremely binary -- from nothing as we
2797 * approach the memory protection threshold, to totally
2798 * nominal as we exceed it. This results in requiring
2799 * setting extremely liberal protection thresholds. It
2800 * also means we simply get no protection at all if we
2801 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002802 *
2803 * If there is any protection in place, we reduce scan
2804 * pressure by how much of the total memory used is
2805 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002806 *
Chris Down9de7ca42019-10-06 17:58:35 -07002807 * There is one special case: in the first reclaim pass,
2808 * we skip over all groups that are within their low
2809 * protection. If that fails to reclaim enough pages to
2810 * satisfy the reclaim goal, we come back and override
2811 * the best-effort low protection. However, we still
2812 * ideally want to honor how well-behaved groups are in
2813 * that case instead of simply punishing them all
2814 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002815 * memory they are using, reducing the scan pressure
2816 * again by how much of the total memory used is under
2817 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002818 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002819 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002820 unsigned long protection;
2821
2822 /* memory.low scaling, make sure we retry before OOM */
2823 if (!sc->memcg_low_reclaim && low > min) {
2824 protection = low;
2825 sc->memcg_low_skipped = 1;
2826 } else {
2827 protection = min;
2828 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002829
2830 /* Avoid TOCTOU with earlier protection check */
2831 cgroup_size = max(cgroup_size, protection);
2832
2833 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002834 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002835
2836 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002837 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002838 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002839 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002840 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002841 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002842 } else {
2843 scan = lruvec_size;
2844 }
2845
2846 scan >>= sc->priority;
2847
Johannes Weiner688035f2017-05-03 14:52:07 -07002848 /*
2849 * If the cgroup's already been deleted, make sure to
2850 * scrape out the remaining cache.
2851 */
2852 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002853 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002854
Johannes Weiner688035f2017-05-03 14:52:07 -07002855 switch (scan_balance) {
2856 case SCAN_EQUAL:
2857 /* Scan lists relative to size */
2858 break;
2859 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002860 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002861 * Scan types proportional to swappiness and
2862 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002863 * Make sure we don't miss the last page on
2864 * the offlined memory cgroups because of a
2865 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002866 */
Gavin Shan76073c62020-02-20 20:04:24 -08002867 scan = mem_cgroup_online(memcg) ?
2868 div64_u64(scan * fraction[file], denominator) :
2869 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002870 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002871 break;
2872 case SCAN_FILE:
2873 case SCAN_ANON:
2874 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002875 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002876 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002877 break;
2878 default:
2879 /* Look ma, no brain */
2880 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002881 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002882
Johannes Weiner688035f2017-05-03 14:52:07 -07002883 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002884 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002885}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002886
Dave Hansen2f368a92021-09-02 14:59:23 -07002887/*
2888 * Anonymous LRU management is a waste if there is
2889 * ultimately no way to reclaim the memory.
2890 */
2891static bool can_age_anon_pages(struct pglist_data *pgdat,
2892 struct scan_control *sc)
2893{
2894 /* Aging the anon LRU is valuable if swap is present: */
2895 if (total_swap_pages > 0)
2896 return true;
2897
2898 /* Also valuable if anon pages can be demoted: */
2899 return can_demote(pgdat->node_id, sc);
2900}
2901
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002902#ifdef CONFIG_LRU_GEN
2903
2904/******************************************************************************
2905 * shorthand helpers
2906 ******************************************************************************/
2907
Yu Zhaoa1537a62022-01-27 20:32:37 -07002908#define DEFINE_MAX_SEQ(lruvec) \
2909 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2910
2911#define DEFINE_MIN_SEQ(lruvec) \
2912 unsigned long min_seq[ANON_AND_FILE] = { \
2913 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2914 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2915 }
2916
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002917#define for_each_gen_type_zone(gen, type, zone) \
2918 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2919 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2920 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2921
Yu Zhaoa1537a62022-01-27 20:32:37 -07002922static int page_lru_gen(struct page *page)
2923{
2924 unsigned long flags = READ_ONCE(page->flags);
2925
2926 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2927}
2928
2929static int page_lru_tier(struct page *page)
2930{
2931 int refs;
2932 unsigned long flags = READ_ONCE(page->flags);
2933
2934 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2935 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2936
2937 return lru_tier_from_refs(refs);
2938}
2939
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002940static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2941{
2942 struct pglist_data *pgdat = NODE_DATA(nid);
2943
2944#ifdef CONFIG_MEMCG
2945 if (memcg) {
2946 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2947
2948 /* for hotadd_new_pgdat() */
2949 if (!lruvec->pgdat)
2950 lruvec->pgdat = pgdat;
2951
2952 return lruvec;
2953 }
2954#endif
2955 VM_BUG_ON(!mem_cgroup_disabled());
2956
2957 return pgdat ? &pgdat->__lruvec : NULL;
2958}
2959
Yu Zhaoa1537a62022-01-27 20:32:37 -07002960static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2961{
2962 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2963 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2964
2965 if (!can_demote(pgdat->node_id, sc) &&
2966 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2967 return 0;
2968
2969 return mem_cgroup_swappiness(memcg);
2970}
2971
2972static int get_nr_gens(struct lruvec *lruvec, int type)
2973{
2974 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2975}
2976
2977static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2978{
2979 /* see the comment on lru_gen_struct */
2980 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2981 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2982 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2983}
2984
2985/******************************************************************************
2986 * refault feedback loop
2987 ******************************************************************************/
2988
2989/*
2990 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2991 *
2992 * The P term is refaulted/(evicted+protected) from a tier in the generation
2993 * currently being evicted; the I term is the exponential moving average of the
2994 * P term over the generations previously evicted, using the smoothing factor
2995 * 1/2; the D term isn't supported.
2996 *
2997 * The setpoint (SP) is always the first tier of one type; the process variable
2998 * (PV) is either any tier of the other type or any other tier of the same
2999 * type.
3000 *
3001 * The error is the difference between the SP and the PV; the correction is
3002 * turn off protection when SP>PV or turn on protection when SP<PV.
3003 *
3004 * For future optimizations:
3005 * 1. The D term may discount the other two terms over time so that long-lived
3006 * generations can resist stale information.
3007 */
3008struct ctrl_pos {
3009 unsigned long refaulted;
3010 unsigned long total;
3011 int gain;
3012};
3013
3014static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3015 struct ctrl_pos *pos)
3016{
3017 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3018 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3019
3020 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3021 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3022 pos->total = lrugen->avg_total[type][tier] +
3023 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3024 if (tier)
3025 pos->total += lrugen->protected[hist][type][tier - 1];
3026 pos->gain = gain;
3027}
3028
3029static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3030{
3031 int hist, tier;
3032 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3033 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3034 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3035
3036 lockdep_assert_held(&lruvec->lru_lock);
3037
3038 if (!carryover && !clear)
3039 return;
3040
3041 hist = lru_hist_from_seq(seq);
3042
3043 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3044 if (carryover) {
3045 unsigned long sum;
3046
3047 sum = lrugen->avg_refaulted[type][tier] +
3048 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3049 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3050
3051 sum = lrugen->avg_total[type][tier] +
3052 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3053 if (tier)
3054 sum += lrugen->protected[hist][type][tier - 1];
3055 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3056 }
3057
3058 if (clear) {
3059 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3060 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3061 if (tier)
3062 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3063 }
3064 }
3065}
3066
3067static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3068{
3069 /*
3070 * Return true if the PV has a limited number of refaults or a lower
3071 * refaulted/total than the SP.
3072 */
3073 return pv->refaulted < MIN_LRU_BATCH ||
3074 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3075 (sp->refaulted + 1) * pv->total * pv->gain;
3076}
3077
3078/******************************************************************************
3079 * the aging
3080 ******************************************************************************/
3081
3082static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3083{
3084 unsigned long old_flags, new_flags;
3085 int type = page_is_file_lru(page);
3086 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3087 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3088
3089 do {
3090 new_flags = old_flags = READ_ONCE(page->flags);
3091 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3092
3093 new_gen = (old_gen + 1) % MAX_NR_GENS;
3094
3095 new_flags &= ~LRU_GEN_MASK;
3096 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3097 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3098 /* for end_page_writeback() */
3099 if (reclaiming)
3100 new_flags |= BIT(PG_reclaim);
3101 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3102
3103 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3104
3105 return new_gen;
3106}
3107
3108static void inc_min_seq(struct lruvec *lruvec)
3109{
3110 int type;
3111 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3112
3113 VM_BUG_ON(!seq_is_valid(lruvec));
3114
3115 for (type = 0; type < ANON_AND_FILE; type++) {
3116 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3117 continue;
3118
3119 reset_ctrl_pos(lruvec, type, true);
3120 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3121 }
3122}
3123
3124static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3125{
3126 int gen, type, zone;
3127 bool success = false;
3128 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3129 DEFINE_MIN_SEQ(lruvec);
3130
3131 VM_BUG_ON(!seq_is_valid(lruvec));
3132
3133 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3134 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3135 gen = lru_gen_from_seq(min_seq[type]);
3136
3137 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3138 if (!list_empty(&lrugen->lists[gen][type][zone]))
3139 goto next;
3140 }
3141
3142 min_seq[type]++;
3143 }
3144next:
3145 ;
3146 }
3147
3148 /* see the comment on lru_gen_struct */
3149 if (can_swap) {
3150 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3151 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3152 }
3153
3154 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3155 if (min_seq[type] == lrugen->min_seq[type])
3156 continue;
3157
3158 reset_ctrl_pos(lruvec, type, true);
3159 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3160 success = true;
3161 }
3162
3163 return success;
3164}
3165
3166static void inc_max_seq(struct lruvec *lruvec, unsigned long max_seq)
3167{
3168 int prev, next;
3169 int type, zone;
3170 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3171
3172 spin_lock_irq(&lruvec->lru_lock);
3173
3174 VM_BUG_ON(!seq_is_valid(lruvec));
3175
3176 if (max_seq != lrugen->max_seq)
3177 goto unlock;
3178
3179 inc_min_seq(lruvec);
3180
3181 /*
3182 * Update the active/inactive LRU sizes for compatibility. Both sides of
3183 * the current max_seq need to be covered, since max_seq+1 can overlap
3184 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3185 * overlap, cold/hot inversion happens. This can be solved by moving
3186 * pages from min_seq to min_seq+1 but is omitted for simplicity.
3187 */
3188 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3189 next = lru_gen_from_seq(lrugen->max_seq + 1);
3190
3191 for (type = 0; type < ANON_AND_FILE; type++) {
3192 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3193 enum lru_list lru = type * LRU_INACTIVE_FILE;
3194 long delta = lrugen->nr_pages[prev][type][zone] -
3195 lrugen->nr_pages[next][type][zone];
3196
3197 if (!delta)
3198 continue;
3199
3200 __update_lru_size(lruvec, lru, zone, delta);
3201 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3202 }
3203 }
3204
3205 for (type = 0; type < ANON_AND_FILE; type++)
3206 reset_ctrl_pos(lruvec, type, false);
3207
3208 /* make sure preceding modifications appear */
3209 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3210unlock:
3211 spin_unlock_irq(&lruvec->lru_lock);
3212}
3213
3214static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
3215 unsigned long *min_seq, bool can_swap, bool *need_aging)
3216{
3217 int gen, type, zone;
3218 long old = 0;
3219 long young = 0;
3220 long total = 0;
3221 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3222
3223 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3224 unsigned long seq;
3225
3226 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3227 long size = 0;
3228
3229 gen = lru_gen_from_seq(seq);
3230
3231 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3232 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
3233
3234 total += size;
3235 if (seq == max_seq)
3236 young += size;
3237 if (seq + MIN_NR_GENS == max_seq)
3238 old += size;
3239 }
3240 }
3241
3242 /*
3243 * The aging and the eviction is a typical producer-consumer model. The
3244 * aging tries to be lazy to reduce the unnecessary overhead. On the
3245 * other hand, the eviction stalls when the number of generations
3246 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
3247 * generations, hence the first two if's.
3248 *
3249 * In addition, it's ideal to spread pages out evenly, meaning
3250 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
3251 * reasonable range for this average portion would [1/MIN_NR_GENS,
3252 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
3253 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
3254 * from the producer's POV, the aging only cares about the upper bound
3255 * of hot pages, i.e., 1/MIN_NR_GENS.
3256 */
3257 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
3258 *need_aging = true;
3259 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
3260 *need_aging = false;
3261 else if (young * MIN_NR_GENS > total)
3262 *need_aging = true;
3263 else if (old * (MIN_NR_GENS + 2) < total)
3264 *need_aging = true;
3265 else
3266 *need_aging = false;
3267
3268 return total > 0 ? total : 0;
3269}
3270
3271static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3272{
3273 bool need_aging;
3274 long nr_to_scan;
3275 int swappiness = get_swappiness(lruvec, sc);
3276 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3277 DEFINE_MAX_SEQ(lruvec);
3278 DEFINE_MIN_SEQ(lruvec);
3279
3280 mem_cgroup_calculate_protection(NULL, memcg);
3281
3282 if (mem_cgroup_below_min(memcg))
3283 return;
3284
3285 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
3286 if (!nr_to_scan)
3287 return;
3288
3289 nr_to_scan >>= sc->priority;
3290
3291 if (!mem_cgroup_online(memcg))
3292 nr_to_scan++;
3293
3294 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
3295 inc_max_seq(lruvec, max_seq);
3296}
3297
3298static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3299{
3300 struct mem_cgroup *memcg;
3301
3302 VM_BUG_ON(!current_is_kswapd());
3303
3304 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3305 do {
3306 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3307
3308 age_lruvec(lruvec, sc);
3309
3310 cond_resched();
3311 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3312}
3313
3314/******************************************************************************
3315 * the eviction
3316 ******************************************************************************/
3317
3318static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
3319{
3320 bool success;
3321 int gen = page_lru_gen(page);
3322 int type = page_is_file_lru(page);
3323 int zone = page_zonenum(page);
3324 int tier = page_lru_tier(page);
3325 int delta = thp_nr_pages(page);
3326 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3327
3328 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
3329
3330 if (!page_evictable(page)) {
3331 success = lru_gen_del_page(lruvec, page, true);
3332 VM_BUG_ON_PAGE(!success, page);
3333 SetPageUnevictable(page);
3334 add_page_to_lru_list(page, lruvec);
3335 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
3336 return true;
3337 }
3338
3339 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
3340 success = lru_gen_del_page(lruvec, page, true);
3341 VM_BUG_ON_PAGE(!success, page);
3342 SetPageSwapBacked(page);
3343 add_page_to_lru_list_tail(page, lruvec);
3344 return true;
3345 }
3346
3347 if (tier > tier_idx) {
3348 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3349
3350 gen = page_inc_gen(lruvec, page, false);
3351 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
3352
3353 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
3354 lrugen->protected[hist][type][tier - 1] + delta);
3355 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
3356 return true;
3357 }
3358
3359 if (PageLocked(page) || PageWriteback(page) ||
3360 (type == LRU_GEN_FILE && PageDirty(page))) {
3361 gen = page_inc_gen(lruvec, page, true);
3362 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
3363 return true;
3364 }
3365
3366 return false;
3367}
3368
3369static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
3370{
3371 bool success;
3372
3373 if (!sc->may_unmap && page_mapped(page))
3374 return false;
3375
3376 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
3377 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
3378 return false;
3379
3380 if (!get_page_unless_zero(page))
3381 return false;
3382
3383 if (!TestClearPageLRU(page)) {
3384 put_page(page);
3385 return false;
3386 }
3387
3388 success = lru_gen_del_page(lruvec, page, true);
3389 VM_BUG_ON_PAGE(!success, page);
3390
3391 return true;
3392}
3393
3394static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
3395 int type, int tier, struct list_head *list)
3396{
3397 int gen, zone;
3398 enum vm_event_item item;
3399 int sorted = 0;
3400 int scanned = 0;
3401 int isolated = 0;
3402 int remaining = MAX_LRU_BATCH;
3403 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3404 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3405
3406 VM_BUG_ON(!list_empty(list));
3407
3408 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
3409 return 0;
3410
3411 gen = lru_gen_from_seq(lrugen->min_seq[type]);
3412
3413 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
3414 LIST_HEAD(moved);
3415 int skipped = 0;
3416 struct list_head *head = &lrugen->lists[gen][type][zone];
3417
3418 while (!list_empty(head)) {
3419 struct page *page = lru_to_page(head);
3420 int delta = thp_nr_pages(page);
3421
3422 VM_BUG_ON_PAGE(PageTail(page), page);
3423 VM_BUG_ON_PAGE(PageUnevictable(page), page);
3424 VM_BUG_ON_PAGE(PageActive(page), page);
3425 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
3426 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
3427
3428 prefetchw_prev_lru_page(page, head, flags);
3429
3430 scanned += delta;
3431
3432 if (sort_page(lruvec, page, tier))
3433 sorted += delta;
3434 else if (isolate_page(lruvec, page, sc)) {
3435 list_add(&page->lru, list);
3436 isolated += delta;
3437 } else {
3438 list_move(&page->lru, &moved);
3439 skipped += delta;
3440 }
3441
3442 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
3443 break;
3444 }
3445
3446 if (skipped) {
3447 list_splice(&moved, head);
3448 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
3449 }
3450
3451 if (!remaining || isolated >= MIN_LRU_BATCH)
3452 break;
3453 }
3454
3455 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
3456 if (!cgroup_reclaim(sc)) {
3457 __count_vm_events(item, isolated);
3458 __count_vm_events(PGREFILL, sorted);
3459 }
3460 __count_memcg_events(memcg, item, isolated);
3461 __count_memcg_events(memcg, PGREFILL, sorted);
3462 __count_vm_events(PGSCAN_ANON + type, isolated);
3463
3464 /*
3465 * There might not be eligible pages due to reclaim_idx, may_unmap and
3466 * may_writepage. Check the remaining to prevent livelock if there is no
3467 * progress.
3468 */
3469 return isolated || !remaining ? scanned : 0;
3470}
3471
3472static int get_tier_idx(struct lruvec *lruvec, int type)
3473{
3474 int tier;
3475 struct ctrl_pos sp, pv;
3476
3477 /*
3478 * To leave a margin for fluctuations, use a larger gain factor (1:2).
3479 * This value is chosen because any other tier would have at least twice
3480 * as many refaults as the first tier.
3481 */
3482 read_ctrl_pos(lruvec, type, 0, 1, &sp);
3483 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3484 read_ctrl_pos(lruvec, type, tier, 2, &pv);
3485 if (!positive_ctrl_err(&sp, &pv))
3486 break;
3487 }
3488
3489 return tier - 1;
3490}
3491
3492static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
3493{
3494 int type, tier;
3495 struct ctrl_pos sp, pv;
3496 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
3497
3498 /*
3499 * Compare the first tier of anon with that of file to determine which
3500 * type to scan. Also need to compare other tiers of the selected type
3501 * with the first tier of the other type to determine the last tier (of
3502 * the selected type) to evict.
3503 */
3504 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
3505 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
3506 type = positive_ctrl_err(&sp, &pv);
3507
3508 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
3509 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3510 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
3511 if (!positive_ctrl_err(&sp, &pv))
3512 break;
3513 }
3514
3515 *tier_idx = tier - 1;
3516
3517 return type;
3518}
3519
3520static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
3521 int *type_scanned, struct list_head *list)
3522{
3523 int i;
3524 int type;
3525 int scanned;
3526 int tier = -1;
3527 DEFINE_MIN_SEQ(lruvec);
3528
3529 VM_BUG_ON(!seq_is_valid(lruvec));
3530
3531 /*
3532 * Try to make the obvious choice first. When anon and file are both
3533 * available from the same generation, interpret swappiness 1 as file
3534 * first and 200 as anon first.
3535 */
3536 if (!swappiness)
3537 type = LRU_GEN_FILE;
3538 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
3539 type = LRU_GEN_ANON;
3540 else if (swappiness == 1)
3541 type = LRU_GEN_FILE;
3542 else if (swappiness == 200)
3543 type = LRU_GEN_ANON;
3544 else
3545 type = get_type_to_scan(lruvec, swappiness, &tier);
3546
3547 for (i = !swappiness; i < ANON_AND_FILE; i++) {
3548 if (tier < 0)
3549 tier = get_tier_idx(lruvec, type);
3550
3551 scanned = scan_pages(lruvec, sc, type, tier, list);
3552 if (scanned)
3553 break;
3554
3555 type = !type;
3556 tier = -1;
3557 }
3558
3559 *type_scanned = type;
3560
3561 return scanned;
3562}
3563
3564static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
3565{
3566 int type;
3567 int scanned;
3568 int reclaimed;
3569 LIST_HEAD(list);
3570 struct page *page;
3571 enum vm_event_item item;
3572 struct reclaim_stat stat;
3573 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3574 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3575
3576 spin_lock_irq(&lruvec->lru_lock);
3577
3578 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
3579
3580 if (try_to_inc_min_seq(lruvec, swappiness))
3581 scanned++;
3582
3583 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
3584 scanned = 0;
3585
3586 spin_unlock_irq(&lruvec->lru_lock);
3587
3588 if (list_empty(&list))
3589 return scanned;
3590
3591 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
3592
3593 /*
3594 * To avoid livelock, don't add rejected pages back to the same lists
3595 * they were isolated from. See lru_gen_add_page().
3596 */
3597 list_for_each_entry(page, &list, lru) {
3598 ClearPageReferenced(page);
3599 ClearPageWorkingset(page);
3600
3601 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
3602 ClearPageActive(page);
3603 else if (page_is_file_lru(page) || PageSwapCache(page))
3604 SetPageActive(page);
3605 }
3606
3607 spin_lock_irq(&lruvec->lru_lock);
3608
3609 move_pages_to_lru(lruvec, &list);
3610
3611 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
3612 if (!cgroup_reclaim(sc))
3613 __count_vm_events(item, reclaimed);
3614 __count_memcg_events(memcg, item, reclaimed);
3615 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
3616
3617 spin_unlock_irq(&lruvec->lru_lock);
3618
3619 mem_cgroup_uncharge_list(&list);
3620 free_unref_page_list(&list);
3621
3622 sc->nr_reclaimed += reclaimed;
3623
3624 return scanned;
3625}
3626
3627static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
3628{
3629 bool need_aging;
3630 long nr_to_scan;
3631 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3632 DEFINE_MAX_SEQ(lruvec);
3633 DEFINE_MIN_SEQ(lruvec);
3634
3635 if (mem_cgroup_below_min(memcg) ||
3636 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
3637 return 0;
3638
3639 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
3640 if (!nr_to_scan)
3641 return 0;
3642
3643 /* reset the priority if the target has been met */
3644 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
3645
3646 if (!mem_cgroup_online(memcg))
3647 nr_to_scan++;
3648
3649 if (!nr_to_scan)
3650 return 0;
3651
3652 if (!need_aging)
3653 return nr_to_scan;
3654
3655 /* leave the work to lru_gen_age_node() */
3656 if (current_is_kswapd())
3657 return 0;
3658
3659 /* try other memcgs before going to the aging path */
3660 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
3661 sc->skipped_deactivate = true;
3662 return 0;
3663 }
3664
3665 inc_max_seq(lruvec, max_seq);
3666
3667 return nr_to_scan;
3668}
3669
3670static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3671{
3672 struct blk_plug plug;
3673 long scanned = 0;
3674
3675 lru_add_drain();
3676
3677 blk_start_plug(&plug);
3678
3679 while (true) {
3680 int delta;
3681 int swappiness;
3682 long nr_to_scan;
3683
3684 if (sc->may_swap)
3685 swappiness = get_swappiness(lruvec, sc);
3686 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
3687 swappiness = 1;
3688 else
3689 swappiness = 0;
3690
3691 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
3692 if (!nr_to_scan)
3693 break;
3694
3695 delta = evict_pages(lruvec, sc, swappiness);
3696 if (!delta)
3697 break;
3698
3699 scanned += delta;
3700 if (scanned >= nr_to_scan)
3701 break;
3702
3703 cond_resched();
3704 }
3705
3706 blk_finish_plug(&plug);
3707}
3708
Yu Zhaof88ed5a2021-01-25 21:12:33 -07003709/******************************************************************************
3710 * initialization
3711 ******************************************************************************/
3712
3713void lru_gen_init_lruvec(struct lruvec *lruvec)
3714{
3715 int gen, type, zone;
3716 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3717
3718 lrugen->max_seq = MIN_NR_GENS + 1;
3719
3720 for_each_gen_type_zone(gen, type, zone)
3721 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
3722}
3723
3724#ifdef CONFIG_MEMCG
3725void lru_gen_init_memcg(struct mem_cgroup *memcg)
3726{
3727}
3728
3729void lru_gen_exit_memcg(struct mem_cgroup *memcg)
3730{
3731 int nid;
3732
3733 for_each_node(nid) {
3734 struct lruvec *lruvec = get_lruvec(memcg, nid);
3735
3736 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
3737 sizeof(lruvec->lrugen.nr_pages)));
3738 }
3739}
3740#endif
3741
3742static int __init init_lru_gen(void)
3743{
3744 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
3745 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
3746
3747 return 0;
3748};
3749late_initcall(init_lru_gen);
3750
Yu Zhaoa1537a62022-01-27 20:32:37 -07003751#else
3752
3753static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3754{
3755}
3756
3757static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3758{
3759}
3760
Yu Zhaof88ed5a2021-01-25 21:12:33 -07003761#endif /* CONFIG_LRU_GEN */
3762
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003763static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003764{
3765 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07003766 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003767 unsigned long nr_to_scan;
3768 enum lru_list lru;
3769 unsigned long nr_reclaimed = 0;
3770 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
3771 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07003772 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003773
Yu Zhaoa1537a62022-01-27 20:32:37 -07003774 if (lru_gen_enabled()) {
3775 lru_gen_shrink_lruvec(lruvec, sc);
3776 return;
3777 }
3778
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003779 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003780
Mel Gormane82e0562013-07-03 15:01:44 -07003781 /* Record the original scan target for proportional adjustments later */
3782 memcpy(targets, nr, sizeof(nr));
3783
Mel Gorman1a501902014-06-04 16:10:49 -07003784 /*
3785 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
3786 * event that can occur when there is little memory pressure e.g.
3787 * multiple streaming readers/writers. Hence, we do not abort scanning
3788 * when the requested number of pages are reclaimed when scanning at
3789 * DEF_PRIORITY on the assumption that the fact we are direct
3790 * reclaiming implies that kswapd is not keeping up and it is best to
3791 * do a batch of work at once. For memcg reclaim one check is made to
3792 * abort proportional reclaim if either the file or anon lru has already
3793 * dropped to zero at the first pass.
3794 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08003795 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07003796 sc->priority == DEF_PRIORITY);
3797
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003798 blk_start_plug(&plug);
3799 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
3800 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07003801 unsigned long nr_anon, nr_file, percentage;
3802 unsigned long nr_scanned;
3803
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003804 for_each_evictable_lru(lru) {
3805 if (nr[lru]) {
3806 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
3807 nr[lru] -= nr_to_scan;
3808
3809 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07003810 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003811 }
3812 }
Mel Gormane82e0562013-07-03 15:01:44 -07003813
Michal Hockobd041732016-12-02 17:26:48 -08003814 cond_resched();
3815
Mel Gormane82e0562013-07-03 15:01:44 -07003816 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3817 continue;
3818
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003819 /*
Mel Gormane82e0562013-07-03 15:01:44 -07003820 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07003821 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07003822 * proportionally what was requested by get_scan_count(). We
3823 * stop reclaiming one LRU and reduce the amount scanning
3824 * proportional to the original scan target.
3825 */
3826 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3827 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3828
Mel Gorman1a501902014-06-04 16:10:49 -07003829 /*
3830 * It's just vindictive to attack the larger once the smaller
3831 * has gone to zero. And given the way we stop scanning the
3832 * smaller below, this makes sure that we only make one nudge
3833 * towards proportionality once we've got nr_to_reclaim.
3834 */
3835 if (!nr_file || !nr_anon)
3836 break;
3837
Mel Gormane82e0562013-07-03 15:01:44 -07003838 if (nr_file > nr_anon) {
3839 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3840 targets[LRU_ACTIVE_ANON] + 1;
3841 lru = LRU_BASE;
3842 percentage = nr_anon * 100 / scan_target;
3843 } else {
3844 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3845 targets[LRU_ACTIVE_FILE] + 1;
3846 lru = LRU_FILE;
3847 percentage = nr_file * 100 / scan_target;
3848 }
3849
3850 /* Stop scanning the smaller of the LRU */
3851 nr[lru] = 0;
3852 nr[lru + LRU_ACTIVE] = 0;
3853
3854 /*
3855 * Recalculate the other LRU scan count based on its original
3856 * scan target and the percentage scanning already complete
3857 */
3858 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3859 nr_scanned = targets[lru] - nr[lru];
3860 nr[lru] = targets[lru] * (100 - percentage) / 100;
3861 nr[lru] -= min(nr[lru], nr_scanned);
3862
3863 lru += LRU_ACTIVE;
3864 nr_scanned = targets[lru] - nr[lru];
3865 nr[lru] = targets[lru] * (100 - percentage) / 100;
3866 nr[lru] -= min(nr[lru], nr_scanned);
3867
3868 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003869 }
3870 blk_finish_plug(&plug);
3871 sc->nr_reclaimed += nr_reclaimed;
3872
3873 /*
3874 * Even if we did not try to evict anon pages at all, we want to
3875 * rebalance the anon lru active/inactive ratio.
3876 */
Dave Hansen2f368a92021-09-02 14:59:23 -07003877 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
3878 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003879 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3880 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003881}
3882
Mel Gorman23b9da52012-05-29 15:06:20 -07003883/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07003884static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07003885{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08003886 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07003887 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07003888 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07003889 return true;
3890
3891 return false;
3892}
3893
Rik van Riel4f98a2f2008-10-18 20:26:32 -07003894/*
Mel Gorman23b9da52012-05-29 15:06:20 -07003895 * Reclaim/compaction is used for high-order allocation requests. It reclaims
3896 * order-0 pages before compacting the zone. should_continue_reclaim() returns
3897 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07003898 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07003899 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08003900 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07003901static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08003902 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08003903 struct scan_control *sc)
3904{
3905 unsigned long pages_for_compaction;
3906 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07003907 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08003908
3909 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07003910 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08003911 return false;
3912
Vlastimil Babka5ee04712019-09-23 15:37:29 -07003913 /*
3914 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
3915 * number of pages that were scanned. This will return to the caller
3916 * with the risk reclaim/compaction and the resulting allocation attempt
3917 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
3918 * allocations through requiring that the full LRU list has been scanned
3919 * first, by assuming that zero delta of sc->nr_scanned means full LRU
3920 * scan, but that approximation was wrong, and there were corner cases
3921 * where always a non-zero amount of pages were scanned.
3922 */
3923 if (!nr_reclaimed)
3924 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08003925
Mel Gorman3e7d3442011-01-13 15:45:56 -08003926 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07003927 for (z = 0; z <= sc->reclaim_idx; z++) {
3928 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07003929 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07003930 continue;
3931
3932 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07003933 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07003934 case COMPACT_CONTINUE:
3935 return false;
3936 default:
3937 /* check next zone */
3938 ;
3939 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08003940 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07003941
3942 /*
3943 * If we have not reclaimed enough pages for compaction and the
3944 * inactive lists are large enough, continue reclaiming
3945 */
3946 pages_for_compaction = compact_gap(sc->order);
3947 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07003948 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07003949 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
3950
Vlastimil Babka5ee04712019-09-23 15:37:29 -07003951 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08003952}
3953
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08003954static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08003955{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08003956 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08003957 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08003958
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08003959 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08003960 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003961 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08003962 unsigned long reclaimed;
3963 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08003964
Xunlei Pange3336ca2020-09-04 16:35:27 -07003965 /*
3966 * This loop can become CPU-bound when target memcgs
3967 * aren't eligible for reclaim - either because they
3968 * don't have any reclaimable pages, or because their
3969 * memory is explicitly protected. Avoid soft lockups.
3970 */
3971 cond_resched();
3972
Chris Down45c7f7e2020-08-06 23:22:05 -07003973 mem_cgroup_calculate_protection(target_memcg, memcg);
3974
3975 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08003976 /*
3977 * Hard protection.
3978 * If there is no reclaimable memory, OOM.
3979 */
3980 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07003981 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08003982 /*
3983 * Soft protection.
3984 * Respect the protection only as long as
3985 * there is an unprotected supply
3986 * of reclaimable memory from other cgroups.
3987 */
3988 if (!sc->memcg_low_reclaim) {
3989 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07003990 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08003991 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08003992 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08003993 }
3994
Johannes Weinerd2af3392019-11-30 17:55:43 -08003995 reclaimed = sc->nr_reclaimed;
3996 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003997
3998 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07003999
Johannes Weinerd2af3392019-11-30 17:55:43 -08004000 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
4001 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004002
Johannes Weinerd2af3392019-11-30 17:55:43 -08004003 /* Record the group's reclaim efficiency */
4004 vmpressure(sc->gfp_mask, memcg, false,
4005 sc->nr_scanned - scanned,
4006 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004007
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004008 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
4009}
4010
Liu Song6c9e09072020-01-30 22:14:08 -08004011static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004012{
4013 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004014 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08004015 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004016 bool reclaimable = false;
4017
Johannes Weiner1b051172019-11-30 17:55:52 -08004018 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
4019
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004020again:
4021 memset(&sc->nr, 0, sizeof(sc->nr));
4022
4023 nr_reclaimed = sc->nr_reclaimed;
4024 nr_scanned = sc->nr_scanned;
4025
Yu Zhao3eb07702020-09-27 20:49:08 -06004026 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08004027
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004028 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004029
Johannes Weinerd2af3392019-11-30 17:55:43 -08004030 if (reclaim_state) {
4031 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
4032 reclaim_state->reclaimed_slab = 0;
4033 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004034
Johannes Weinerd2af3392019-11-30 17:55:43 -08004035 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08004036 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08004037 sc->nr_scanned - nr_scanned,
4038 sc->nr_reclaimed - nr_reclaimed);
4039
4040 if (sc->nr_reclaimed - nr_reclaimed)
4041 reclaimable = true;
4042
4043 if (current_is_kswapd()) {
4044 /*
4045 * If reclaim is isolating dirty pages under writeback,
4046 * it implies that the long-lived page allocation rate
4047 * is exceeding the page laundering rate. Either the
4048 * global limits are not being effective at throttling
4049 * processes due to the page distribution throughout
4050 * zones or there is heavy usage of a slow backing
4051 * device. The only option is to throttle from reclaim
4052 * context which is not ideal as there is no guarantee
4053 * the dirtying process is throttled in the same way
4054 * balance_dirty_pages() manages.
4055 *
4056 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
4057 * count the number of pages under pages flagged for
4058 * immediate reclaim and stall if any are encountered
4059 * in the nr_immediate check below.
4060 */
4061 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
4062 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004063
Johannes Weinerd2af3392019-11-30 17:55:43 -08004064 /* Allow kswapd to start writing pages during reclaim.*/
4065 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
4066 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07004067
4068 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004069 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08004070 * reclaim and under writeback (nr_immediate), it
4071 * implies that pages are cycling through the LRU
4072 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07004073 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08004074 if (sc->nr.immediate)
4075 congestion_wait(BLK_RW_ASYNC, HZ/10);
4076 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004077
Johannes Weinerd2af3392019-11-30 17:55:43 -08004078 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08004079 * Tag a node/memcg as congested if all the dirty pages
4080 * scanned were backed by a congested BDI and
4081 * wait_iff_congested will stall.
4082 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08004083 * Legacy memcg will stall in page writeback so avoid forcibly
4084 * stalling in wait_iff_congested().
4085 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004086 if ((current_is_kswapd() ||
4087 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08004088 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08004089 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08004090
4091 /*
4092 * Stall direct reclaim for IO completions if underlying BDIs
4093 * and node is congested. Allow kswapd to continue until it
4094 * starts encountering unqueued dirty pages or cycling through
4095 * the LRU too quickly.
4096 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004097 if (!current_is_kswapd() && current_may_throttle() &&
4098 !sc->hibernation_mode &&
4099 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08004100 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
4101
4102 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
4103 sc))
4104 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004105
Johannes Weinerc73322d2017-05-03 14:51:51 -07004106 /*
4107 * Kswapd gives up on balancing particular nodes after too
4108 * many failures to reclaim anything from them and goes to
4109 * sleep. On reclaim progress, reset the failure counter. A
4110 * successful direct reclaim run will revive a dormant kswapd.
4111 */
4112 if (reclaimable)
4113 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004114}
4115
Vlastimil Babka53853e22014-10-09 15:27:02 -07004116/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004117 * Returns true if compaction should go ahead for a costly-order request, or
4118 * the allocation would already succeed without compaction. Return false if we
4119 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07004120 */
Mel Gorman4f588332016-07-28 15:46:38 -07004121static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004122{
Mel Gorman31483b62016-07-28 15:45:46 -07004123 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004124 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004125
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004126 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
4127 if (suitable == COMPACT_SUCCESS)
4128 /* Allocation should succeed already. Don't reclaim. */
4129 return true;
4130 if (suitable == COMPACT_SKIPPED)
4131 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004132 return false;
4133
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004134 /*
4135 * Compaction is already possible, but it takes time to run and there
4136 * are potentially other callers using the pages just freed. So proceed
4137 * with reclaim to make a buffer of free pages available to give
4138 * compaction a reasonable chance of completing and allocating the page.
4139 * Note that we won't actually reclaim the whole buffer in one attempt
4140 * as the target watermark in should_continue_reclaim() is lower. But if
4141 * we are already above the high+gap watermark, don't reclaim at all.
4142 */
4143 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
4144
4145 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004146}
4147
Linus Torvalds1da177e2005-04-16 15:20:36 -07004148/*
4149 * This is the direct reclaim path, for page-allocating processes. We only
4150 * try to reclaim pages from zones which will satisfy the caller's allocation
4151 * request.
4152 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07004153 * If a zone is deemed to be full of pinned pages then just give it a light
4154 * scan then give up on it.
4155 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07004156static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004157{
Mel Gormandd1a2392008-04-28 02:12:17 -07004158 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07004159 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07004160 unsigned long nr_soft_reclaimed;
4161 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07004162 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07004163 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004164
Mel Gormancc715d92012-03-21 16:34:00 -07004165 /*
4166 * If the number of buffer_heads in the machine exceeds the maximum
4167 * allowed level, force direct reclaim to scan the highmem zone as
4168 * highmem pages could be pinning lowmem pages storing buffer_heads
4169 */
Weijie Yang619d0d762014-04-07 15:36:59 -07004170 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07004171 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07004172 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07004173 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07004174 }
Mel Gormancc715d92012-03-21 16:34:00 -07004175
Mel Gormand4debc62010-08-09 17:19:29 -07004176 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07004177 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07004178 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004179 * Take care memory controller reclaiming has small influence
4180 * to global LRU.
4181 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004182 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04004183 if (!cpuset_zone_allowed(zone,
4184 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004185 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004186
Johannes Weiner0b064962014-08-06 16:06:12 -07004187 /*
4188 * If we already have plenty of memory free for
4189 * compaction in this zone, don't free any more.
4190 * Even though compaction is invoked for any
4191 * non-zero order, only frequent costly order
4192 * reclamation is disruptive enough to become a
4193 * noticeable problem, like transparent huge
4194 * page allocations.
4195 */
4196 if (IS_ENABLED(CONFIG_COMPACTION) &&
4197 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07004198 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07004199 sc->compaction_ready = true;
4200 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07004201 }
Johannes Weiner0b064962014-08-06 16:06:12 -07004202
Andrew Morton0608f432013-09-24 15:27:41 -07004203 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07004204 * Shrink each node in the zonelist once. If the
4205 * zonelist is ordered by zone (not the default) then a
4206 * node may be shrunk multiple times but in that case
4207 * the user prefers lower zones being preserved.
4208 */
4209 if (zone->zone_pgdat == last_pgdat)
4210 continue;
4211
4212 /*
Andrew Morton0608f432013-09-24 15:27:41 -07004213 * This steals pages from memory cgroups over softlimit
4214 * and returns the number of reclaimed pages and
4215 * scanned pages. This works for global memory pressure
4216 * and balancing, not for a memcg's limit.
4217 */
4218 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07004219 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07004220 sc->order, sc->gfp_mask,
4221 &nr_soft_scanned);
4222 sc->nr_reclaimed += nr_soft_reclaimed;
4223 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07004224 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004225 }
Nick Piggin408d8542006-09-25 23:31:27 -07004226
Mel Gorman79dafcd2016-07-28 15:45:53 -07004227 /* See comment about same check for global reclaim above */
4228 if (zone->zone_pgdat == last_pgdat)
4229 continue;
4230 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07004231 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004232 }
Mel Gormane0c23272011-10-31 17:09:33 -07004233
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004234 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07004235 * Restore to original mask to avoid the impact on the caller if we
4236 * promoted it to __GFP_HIGHMEM.
4237 */
4238 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004239}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004240
Johannes Weinerb9107182019-11-30 17:55:59 -08004241static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004242{
Johannes Weinerb9107182019-11-30 17:55:59 -08004243 struct lruvec *target_lruvec;
4244 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004245
Yu Zhaoa1537a62022-01-27 20:32:37 -07004246 if (lru_gen_enabled())
4247 return;
4248
Johannes Weinerb9107182019-11-30 17:55:59 -08004249 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07004250 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
4251 target_lruvec->refaults[0] = refaults;
4252 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
4253 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004254}
4255
Linus Torvalds1da177e2005-04-16 15:20:36 -07004256/*
4257 * This is the main entry point to direct page reclaim.
4258 *
4259 * If a full scan of the inactive list fails to free enough memory then we
4260 * are "out of memory" and something needs to be killed.
4261 *
4262 * If the caller is !__GFP_FS then the probability of a failure is reasonably
4263 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02004264 * caller can't do much about. We kick the writeback threads and take explicit
4265 * naps in the hope that some of these pages can be written. But if the
4266 * allocating task holds filesystem locks which prevent writeout this might not
4267 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07004268 *
4269 * returns: 0, if no pages reclaimed
4270 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07004271 */
Mel Gormandac1d272008-04-28 02:12:12 -07004272static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004273 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004274{
Johannes Weiner241994ed2015-02-11 15:26:06 -08004275 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004276 pg_data_t *last_pgdat;
4277 struct zoneref *z;
4278 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004279retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07004280 delayacct_freepages_start();
4281
Johannes Weinerb5ead352019-11-30 17:55:40 -08004282 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07004283 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004284
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004285 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004286 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
4287 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08004288 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07004289 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07004290
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004291 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07004292 break;
4293
4294 if (sc->compaction_ready)
4295 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004296
4297 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08004298 * If we're getting trouble reclaiming, start doing
4299 * writepage even in laptop mode.
4300 */
4301 if (sc->priority < DEF_PRIORITY - 2)
4302 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07004303 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004304
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004305 last_pgdat = NULL;
4306 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
4307 sc->nodemask) {
4308 if (zone->zone_pgdat == last_pgdat)
4309 continue;
4310 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08004311
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004312 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08004313
4314 if (cgroup_reclaim(sc)) {
4315 struct lruvec *lruvec;
4316
4317 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
4318 zone->zone_pgdat);
4319 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4320 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004321 }
4322
Keika Kobayashi873b4772008-07-25 01:48:52 -07004323 delayacct_freepages_end();
4324
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004325 if (sc->nr_reclaimed)
4326 return sc->nr_reclaimed;
4327
Mel Gorman0cee34f2012-01-12 17:19:49 -08004328 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07004329 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08004330 return 1;
4331
Johannes Weinerb91ac372019-11-30 17:56:02 -08004332 /*
4333 * We make inactive:active ratio decisions based on the node's
4334 * composition of memory, but a restrictive reclaim_idx or a
4335 * memory.low cgroup setting can exempt large amounts of
4336 * memory from reclaim. Neither of which are very common, so
4337 * instead of doing costly eligibility calculations of the
4338 * entire cgroup subtree up front, we assume the estimates are
4339 * good, and retry with forcible deactivation if that fails.
4340 */
4341 if (sc->skipped_deactivate) {
4342 sc->priority = initial_priority;
4343 sc->force_deactivate = 1;
4344 sc->skipped_deactivate = 0;
4345 goto retry;
4346 }
4347
Johannes Weiner241994ed2015-02-11 15:26:06 -08004348 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07004349 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08004350 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004351 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07004352 sc->memcg_low_reclaim = 1;
4353 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004354 goto retry;
4355 }
4356
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004357 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004358}
4359
Johannes Weinerc73322d2017-05-03 14:51:51 -07004360static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07004361{
4362 struct zone *zone;
4363 unsigned long pfmemalloc_reserve = 0;
4364 unsigned long free_pages = 0;
4365 int i;
4366 bool wmark_ok;
4367
Johannes Weinerc73322d2017-05-03 14:51:51 -07004368 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4369 return true;
4370
Mel Gorman55150612012-07-31 16:44:35 -07004371 for (i = 0; i <= ZONE_NORMAL; i++) {
4372 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07004373 if (!managed_zone(zone))
4374 continue;
4375
4376 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07004377 continue;
4378
Mel Gorman55150612012-07-31 16:44:35 -07004379 pfmemalloc_reserve += min_wmark_pages(zone);
4380 free_pages += zone_page_state(zone, NR_FREE_PAGES);
4381 }
4382
Mel Gorman675becc2014-06-04 16:07:35 -07004383 /* If there are no reserves (unexpected config) then do not throttle */
4384 if (!pfmemalloc_reserve)
4385 return true;
4386
Mel Gorman55150612012-07-31 16:44:35 -07004387 wmark_ok = free_pages > pfmemalloc_reserve / 2;
4388
4389 /* kswapd must be awake if processes are being throttled */
4390 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004391 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
4392 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07004393
Mel Gorman55150612012-07-31 16:44:35 -07004394 wake_up_interruptible(&pgdat->kswapd_wait);
4395 }
4396
4397 return wmark_ok;
4398}
4399
4400/*
4401 * Throttle direct reclaimers if backing storage is backed by the network
4402 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
4403 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08004404 * when the low watermark is reached.
4405 *
4406 * Returns true if a fatal signal was delivered during throttling. If this
4407 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07004408 */
Mel Gorman50694c22012-11-26 16:29:48 -08004409static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07004410 nodemask_t *nodemask)
4411{
Mel Gorman675becc2014-06-04 16:07:35 -07004412 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07004413 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07004414 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07004415
4416 /*
4417 * Kernel threads should not be throttled as they may be indirectly
4418 * responsible for cleaning pages necessary for reclaim to make forward
4419 * progress. kjournald for example may enter direct reclaim while
4420 * committing a transaction where throttling it could forcing other
4421 * processes to block on log_wait_commit().
4422 */
4423 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08004424 goto out;
4425
4426 /*
4427 * If a fatal signal is pending, this process should not throttle.
4428 * It should return quickly so it can exit and free its memory
4429 */
4430 if (fatal_signal_pending(current))
4431 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004432
Mel Gorman675becc2014-06-04 16:07:35 -07004433 /*
4434 * Check if the pfmemalloc reserves are ok by finding the first node
4435 * with a usable ZONE_NORMAL or lower zone. The expectation is that
4436 * GFP_KERNEL will be required for allocating network buffers when
4437 * swapping over the network so ZONE_HIGHMEM is unusable.
4438 *
4439 * Throttling is based on the first usable node and throttled processes
4440 * wait on a queue until kswapd makes progress and wakes them. There
4441 * is an affinity then between processes waking up and where reclaim
4442 * progress has been made assuming the process wakes on the same node.
4443 * More importantly, processes running on remote nodes will not compete
4444 * for remote pfmemalloc reserves and processes on different nodes
4445 * should make reasonable progress.
4446 */
4447 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08004448 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07004449 if (zone_idx(zone) > ZONE_NORMAL)
4450 continue;
4451
4452 /* Throttle based on the first usable node */
4453 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07004454 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07004455 goto out;
4456 break;
4457 }
4458
4459 /* If no zone was usable by the allocation flags then do not throttle */
4460 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08004461 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004462
Mel Gorman68243e72012-07-31 16:44:39 -07004463 /* Account for the throttling */
4464 count_vm_event(PGSCAN_DIRECT_THROTTLE);
4465
Mel Gorman55150612012-07-31 16:44:35 -07004466 /*
4467 * If the caller cannot enter the filesystem, it's possible that it
4468 * is due to the caller holding an FS lock or performing a journal
4469 * transaction in the case of a filesystem like ext[3|4]. In this case,
4470 * it is not safe to block on pfmemalloc_wait as kswapd could be
4471 * blocked waiting on the same lock. Instead, throttle for up to a
4472 * second before continuing.
4473 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07004474 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07004475 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07004476 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07004477 else
4478 /* Throttle until kswapd wakes the process */
4479 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
4480 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08004481
Mel Gorman50694c22012-11-26 16:29:48 -08004482 if (fatal_signal_pending(current))
4483 return true;
4484
4485out:
4486 return false;
Mel Gorman55150612012-07-31 16:44:35 -07004487}
4488
Mel Gormandac1d272008-04-28 02:12:12 -07004489unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07004490 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08004491{
Mel Gorman33906bc2010-08-09 17:19:16 -07004492 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004493 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08004494 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004495 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07004496 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07004497 .order = order,
4498 .nodemask = nodemask,
4499 .priority = DEF_PRIORITY,
4500 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004501 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07004502 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08004503 };
4504
Mel Gorman55150612012-07-31 16:44:35 -07004505 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07004506 * scan_control uses s8 fields for order, priority, and reclaim_idx.
4507 * Confirm they are large enough for max values.
4508 */
4509 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
4510 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
4511 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
4512
4513 /*
Mel Gorman50694c22012-11-26 16:29:48 -08004514 * Do not enter reclaim if fatal signal was delivered while throttled.
4515 * 1 is returned so that the page allocator does not OOM kill at this
4516 * point.
Mel Gorman55150612012-07-31 16:44:35 -07004517 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004518 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07004519 return 1;
4520
Andrew Morton1732d2b012019-07-16 16:26:15 -07004521 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004522 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07004523
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004524 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07004525
4526 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004527 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07004528
4529 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004530}
4531
Andrew Mortonc255a452012-07-31 16:43:02 -07004532#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08004533
Michal Hockod2e5fb92019-08-30 16:04:50 -07004534/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004535unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004536 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07004537 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07004538 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07004539{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004540 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07004541 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07004542 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07004543 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004544 .may_writepage = !laptop_mode,
4545 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07004546 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07004547 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07004548 };
Ying Han0ae5e892011-05-26 16:25:25 -07004549
Michal Hockod2e5fb92019-08-30 16:04:50 -07004550 WARN_ON_ONCE(!current->reclaim_state);
4551
Balbir Singh4e416952009-09-23 15:56:39 -07004552 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
4553 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004554
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004555 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07004556 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004557
Balbir Singh4e416952009-09-23 15:56:39 -07004558 /*
4559 * NOTE: Although we can get the priority field, using it
4560 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07004561 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07004562 * will pick up pages from other mem cgroup's as well. We hack
4563 * the priority and make it zero.
4564 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004565 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004566
4567 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
4568
Ying Han0ae5e892011-05-26 16:25:25 -07004569 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07004570
Balbir Singh4e416952009-09-23 15:56:39 -07004571 return sc.nr_reclaimed;
4572}
4573
Johannes Weiner72835c82012-01-12 17:18:32 -08004574unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004575 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004576 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004577 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08004578{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004579 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07004580 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08004581 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004582 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07004583 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07004584 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07004585 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07004586 .target_mem_cgroup = memcg,
4587 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08004588 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004589 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004590 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07004591 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08004592 /*
4593 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
4594 * equal pressure on all the nodes. This is based on the assumption that
4595 * the reclaim does not bail out early.
4596 */
4597 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08004598
Andrew Morton1732d2b012019-07-16 16:26:15 -07004599 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004600 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07004601 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07004602
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004603 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07004604
Vlastimil Babka499118e2017-05-08 15:59:50 -07004605 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004606 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004607 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004608
4609 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004610}
4611#endif
4612
Mel Gorman1d82de62016-07-28 15:45:43 -07004613static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07004614 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08004615{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004616 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004617 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004618
Yu Zhaoa1537a62022-01-27 20:32:37 -07004619 if (lru_gen_enabled()) {
4620 lru_gen_age_node(pgdat, sc);
4621 return;
4622 }
4623
Dave Hansen2f368a92021-09-02 14:59:23 -07004624 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004625 return;
4626
Johannes Weinerb91ac372019-11-30 17:56:02 -08004627 lruvec = mem_cgroup_lruvec(NULL, pgdat);
4628 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
4629 return;
4630
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004631 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4632 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08004633 lruvec = mem_cgroup_lruvec(memcg, pgdat);
4634 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4635 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004636 memcg = mem_cgroup_iter(NULL, memcg, NULL);
4637 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08004638}
4639
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004640static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08004641{
4642 int i;
4643 struct zone *zone;
4644
4645 /*
4646 * Check for watermark boosts top-down as the higher zones
4647 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004648 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08004649 * start prematurely when there is no boosting and a lower
4650 * zone is balanced.
4651 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004652 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08004653 zone = pgdat->node_zones + i;
4654 if (!managed_zone(zone))
4655 continue;
4656
4657 if (zone->watermark_boost)
4658 return true;
4659 }
4660
4661 return false;
4662}
4663
Mel Gormane716f2e2017-05-03 14:53:45 -07004664/*
4665 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004666 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07004667 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004668static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08004669{
Mel Gormane716f2e2017-05-03 14:53:45 -07004670 int i;
4671 unsigned long mark = -1;
4672 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004673
Mel Gorman1c308442018-12-28 00:35:52 -08004674 /*
4675 * Check watermarks bottom-up as lower zones are more likely to
4676 * meet watermarks.
4677 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004678 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004679 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07004680
Mel Gormane716f2e2017-05-03 14:53:45 -07004681 if (!managed_zone(zone))
4682 continue;
4683
4684 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004685 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07004686 return true;
4687 }
4688
4689 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004690 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07004691 * need balancing by definition. This can happen if a zone-restricted
4692 * allocation tries to wake a remote kswapd.
4693 */
4694 if (mark == -1)
4695 return true;
4696
4697 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004698}
4699
Mel Gorman631b6e02017-05-03 14:53:41 -07004700/* Clear pgdat state for congested, dirty or under writeback. */
4701static void clear_pgdat_congested(pg_data_t *pgdat)
4702{
Johannes Weiner1b051172019-11-30 17:55:52 -08004703 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4704
4705 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07004706 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4707 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4708}
4709
Mel Gorman1741c872011-01-13 15:46:21 -08004710/*
Mel Gorman55150612012-07-31 16:44:35 -07004711 * Prepare kswapd for sleeping. This verifies that there are no processes
4712 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4713 *
4714 * Returns true if kswapd is ready to sleep
4715 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004716static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
4717 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08004718{
Mel Gorman55150612012-07-31 16:44:35 -07004719 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004720 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07004721 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004722 * race between when kswapd checks the watermarks and a process gets
4723 * throttled. There is also a potential race if processes get
4724 * throttled, kswapd wakes, a large process exits thereby balancing the
4725 * zones, which causes kswapd to exit balance_pgdat() before reaching
4726 * the wake up checks. If kswapd is going to sleep, no process should
4727 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4728 * the wake up is premature, processes will wake kswapd and get
4729 * throttled again. The difference from wake ups in balance_pgdat() is
4730 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07004731 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004732 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4733 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08004734
Johannes Weinerc73322d2017-05-03 14:51:51 -07004735 /* Hopeless node, leave it to direct reclaim */
4736 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4737 return true;
4738
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004739 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004740 clear_pgdat_congested(pgdat);
4741 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07004742 }
4743
Shantanu Goel333b0a42017-05-03 14:53:38 -07004744 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08004745}
4746
Linus Torvalds1da177e2005-04-16 15:20:36 -07004747/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004748 * kswapd shrinks a node of pages that are at or below the highest usable
4749 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07004750 *
4751 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07004752 * reclaim or if the lack of progress was due to pages under writeback.
4753 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07004754 */
Mel Gorman1d82de62016-07-28 15:45:43 -07004755static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07004756 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07004757{
Mel Gorman1d82de62016-07-28 15:45:43 -07004758 struct zone *zone;
4759 int z;
Mel Gorman75485362013-07-03 15:01:42 -07004760
Mel Gorman1d82de62016-07-28 15:45:43 -07004761 /* Reclaim a number of pages proportional to the number of zones */
4762 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07004763 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07004764 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07004765 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07004766 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07004767
Mel Gorman1d82de62016-07-28 15:45:43 -07004768 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07004769 }
4770
Mel Gorman1d82de62016-07-28 15:45:43 -07004771 /*
4772 * Historically care was taken to put equal pressure on all zones but
4773 * now pressure is applied based on node LRU order.
4774 */
Mel Gorman970a39a2016-07-28 15:46:35 -07004775 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07004776
4777 /*
4778 * Fragmentation may mean that the system cannot be rebalanced for
4779 * high-order allocations. If twice the allocation size has been
4780 * reclaimed then recheck watermarks only at order-0 to prevent
4781 * excessive reclaim. Assume that a process requested a high-order
4782 * can direct reclaim/compact.
4783 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07004784 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07004785 sc->order = 0;
4786
Mel Gormanb8e83b92013-07-03 15:01:45 -07004787 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07004788}
4789
Mel Gormanc49c2c42021-06-28 19:42:21 -07004790/* Page allocator PCP high watermark is lowered if reclaim is active. */
4791static inline void
4792update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4793{
4794 int i;
4795 struct zone *zone;
4796
4797 for (i = 0; i <= highest_zoneidx; i++) {
4798 zone = pgdat->node_zones + i;
4799
4800 if (!managed_zone(zone))
4801 continue;
4802
4803 if (active)
4804 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4805 else
4806 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4807 }
4808}
4809
4810static inline void
4811set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4812{
4813 update_reclaim_active(pgdat, highest_zoneidx, true);
4814}
4815
4816static inline void
4817clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4818{
4819 update_reclaim_active(pgdat, highest_zoneidx, false);
4820}
4821
Mel Gorman75485362013-07-03 15:01:42 -07004822/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004823 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4824 * that are eligible for use by the caller until at least one zone is
4825 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004826 *
Mel Gorman1d82de62016-07-28 15:45:43 -07004827 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004828 *
4829 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07004830 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08004831 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07004832 * or lower is eligible for reclaim until at least one usable zone is
4833 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004834 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004835static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004836{
Linus Torvalds1da177e2005-04-16 15:20:36 -07004837 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07004838 unsigned long nr_soft_reclaimed;
4839 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07004840 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08004841 unsigned long nr_boost_reclaim;
4842 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
4843 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07004844 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08004845 struct scan_control sc = {
4846 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07004847 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004848 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08004849 };
Omar Sandoval93781322018-06-07 17:07:02 -07004850
Andrew Morton1732d2b012019-07-16 16:26:15 -07004851 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07004852 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07004853 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07004854
Christoph Lameterf8891e52006-06-30 01:55:45 -07004855 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004856
Mel Gorman1c308442018-12-28 00:35:52 -08004857 /*
4858 * Account for the reclaim boost. Note that the zone boost is left in
4859 * place so that parallel allocations that are near the watermark will
4860 * stall or direct reclaim until kswapd is finished.
4861 */
4862 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004863 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08004864 zone = pgdat->node_zones + i;
4865 if (!managed_zone(zone))
4866 continue;
4867
4868 nr_boost_reclaim += zone->watermark_boost;
4869 zone_boosts[i] = zone->watermark_boost;
4870 }
4871 boosted = nr_boost_reclaim;
4872
4873restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07004874 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08004875 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004876 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07004877 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07004878 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08004879 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07004880 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07004881
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004882 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004883
Mel Gorman86c79f62016-07-28 15:45:59 -07004884 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07004885 * If the number of buffer_heads exceeds the maximum allowed
4886 * then consider reclaiming from all zones. This has a dual
4887 * purpose -- on 64-bit systems it is expected that
4888 * buffer_heads are stripped during active rotation. On 32-bit
4889 * systems, highmem pages can pin lowmem memory and shrinking
4890 * buffers can relieve lowmem pressure. Reclaim may still not
4891 * go ahead if all eligible zones for the original allocation
4892 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07004893 */
4894 if (buffer_heads_over_limit) {
4895 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
4896 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07004897 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07004898 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004899
Mel Gorman970a39a2016-07-28 15:46:35 -07004900 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08004901 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004902 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07004903 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08004904
Mel Gorman86c79f62016-07-28 15:45:59 -07004905 /*
Mel Gorman1c308442018-12-28 00:35:52 -08004906 * If the pgdat is imbalanced then ignore boosting and preserve
4907 * the watermarks for a later time and restart. Note that the
4908 * zone watermarks will be still reset at the end of balancing
4909 * on the grounds that the normal reclaim should be enough to
4910 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07004911 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004912 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08004913 if (!balanced && nr_boost_reclaim) {
4914 nr_boost_reclaim = 0;
4915 goto restart;
4916 }
4917
4918 /*
4919 * If boosting is not active then only reclaim if there are no
4920 * eligible zones. Note that sc.reclaim_idx is not used as
4921 * buffer_heads_over_limit may have adjusted it.
4922 */
4923 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07004924 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08004925
Mel Gorman1c308442018-12-28 00:35:52 -08004926 /* Limit the priority of boosting to avoid reclaim writeback */
4927 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
4928 raise_priority = false;
4929
4930 /*
4931 * Do not writeback or swap pages for boosted reclaim. The
4932 * intent is to relieve pressure not issue sub-optimal IO
4933 * from reclaim context. If no pages are reclaimed, the
4934 * reclaim will be aborted.
4935 */
4936 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
4937 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08004938
Linus Torvalds1da177e2005-04-16 15:20:36 -07004939 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07004940 * Do some background aging of the anon list, to give
4941 * pages a chance to be referenced before reclaiming. All
4942 * pages are rotated regardless of classzone as this is
4943 * about consistent aging.
4944 */
Mel Gormanef8f2322016-07-28 15:46:05 -07004945 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07004946
4947 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07004948 * If we're getting trouble reclaiming, start doing writepage
4949 * even in laptop mode.
4950 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07004951 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07004952 sc.may_writepage = 1;
4953
Mel Gorman1d82de62016-07-28 15:45:43 -07004954 /* Call soft limit reclaim before calling shrink_node. */
4955 sc.nr_scanned = 0;
4956 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07004957 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07004958 sc.gfp_mask, &nr_soft_scanned);
4959 sc.nr_reclaimed += nr_soft_reclaimed;
4960
Mel Gormanb7ea3c42013-07-03 15:01:53 -07004961 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07004962 * There should be no need to raise the scanning priority if
4963 * enough pages are already being scanned that that high
4964 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004965 */
Mel Gorman970a39a2016-07-28 15:46:35 -07004966 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07004967 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07004968
4969 /*
4970 * If the low watermark is met there is no need for processes
4971 * to be throttled on pfmemalloc_wait as they should not be
4972 * able to safely make forward progress. Wake them
4973 */
4974 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07004975 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08004976 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07004977
Mel Gormanb8e83b92013-07-03 15:01:45 -07004978 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07004979 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07004980 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07004981 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07004982 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07004983 break;
4984
4985 /*
4986 * Raise priority if scanning rate is too low or there was no
4987 * progress in reclaiming pages
4988 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07004989 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08004990 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
4991
4992 /*
4993 * If reclaim made no progress for a boost, stop reclaim as
4994 * IO cannot be queued and it could be an infinite loop in
4995 * extreme circumstances.
4996 */
4997 if (nr_boost_reclaim && !nr_reclaimed)
4998 break;
4999
Johannes Weinerc73322d2017-05-03 14:51:51 -07005000 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07005001 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07005002 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005003
Johannes Weinerc73322d2017-05-03 14:51:51 -07005004 if (!sc.nr_reclaimed)
5005 pgdat->kswapd_failures++;
5006
Mel Gormanb8e83b92013-07-03 15:01:45 -07005007out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005008 clear_reclaim_active(pgdat, highest_zoneidx);
5009
Mel Gorman1c308442018-12-28 00:35:52 -08005010 /* If reclaim was boosted, account for the reclaim done in this pass */
5011 if (boosted) {
5012 unsigned long flags;
5013
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005014 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005015 if (!zone_boosts[i])
5016 continue;
5017
5018 /* Increments are under the zone lock */
5019 zone = pgdat->node_zones + i;
5020 spin_lock_irqsave(&zone->lock, flags);
5021 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
5022 spin_unlock_irqrestore(&zone->lock, flags);
5023 }
5024
5025 /*
5026 * As there is now likely space, wakeup kcompact to defragment
5027 * pageblocks.
5028 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005029 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005030 }
5031
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005032 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005033 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07005034 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005035 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07005036
Mel Gorman0abdee22011-01-13 15:46:22 -08005037 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005038 * Return the order kswapd stopped reclaiming at as
5039 * prepare_kswapd_sleep() takes it into account. If another caller
5040 * entered the allocator slow path while kswapd was awake, order will
5041 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08005042 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005043 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005044}
5045
Mel Gormane716f2e2017-05-03 14:53:45 -07005046/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005047 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
5048 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
5049 * not a valid index then either kswapd runs for first time or kswapd couldn't
5050 * sleep after previous reclaim attempt (node is still unbalanced). In that
5051 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07005052 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005053static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
5054 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07005055{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005056 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005057
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005058 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07005059}
5060
Mel Gorman38087d92016-07-28 15:45:49 -07005061static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005062 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005063{
5064 long remaining = 0;
5065 DEFINE_WAIT(wait);
5066
5067 if (freezing(current) || kthread_should_stop())
5068 return;
5069
5070 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5071
Shantanu Goel333b0a42017-05-03 14:53:38 -07005072 /*
5073 * Try to sleep for a short interval. Note that kcompactd will only be
5074 * woken if it is possible to sleep for a short interval. This is
5075 * deliberate on the assumption that if reclaim cannot keep an
5076 * eligible zone balanced that it's also unlikely that compaction will
5077 * succeed.
5078 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005079 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005080 /*
5081 * Compaction records what page blocks it recently failed to
5082 * isolate pages from and skips them in the future scanning.
5083 * When kswapd is going to sleep, it is reasonable to assume
5084 * that pages and compaction may succeed so reset the cache.
5085 */
5086 reset_isolation_suitable(pgdat);
5087
5088 /*
5089 * We have freed the memory, now we should compact it to make
5090 * allocation of the requested order possible.
5091 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005092 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005093
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005094 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07005095
5096 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005097 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07005098 * order. The values will either be from a wakeup request or
5099 * the previous request that slept prematurely.
5100 */
5101 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005102 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
5103 kswapd_highest_zoneidx(pgdat,
5104 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07005105
5106 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
5107 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07005108 }
5109
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005110 finish_wait(&pgdat->kswapd_wait, &wait);
5111 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5112 }
5113
5114 /*
5115 * After a short sleep, check if it was a premature sleep. If not, then
5116 * go fully to sleep until explicitly woken up.
5117 */
Mel Gormand9f21d42016-07-28 15:46:41 -07005118 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005119 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005120 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
5121
5122 /*
5123 * vmstat counters are not perfectly accurate and the estimated
5124 * value for counters such as NR_FREE_PAGES can deviate from the
5125 * true value by nr_online_cpus * threshold. To avoid the zone
5126 * watermarks being breached while under pressure, we reduce the
5127 * per-cpu vmstat threshold while kswapd is awake and restore
5128 * them before going back to sleep.
5129 */
5130 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07005131
5132 if (!kthread_should_stop())
5133 schedule();
5134
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005135 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
5136 } else {
5137 if (remaining)
5138 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
5139 else
5140 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
5141 }
5142 finish_wait(&pgdat->kswapd_wait, &wait);
5143}
5144
Linus Torvalds1da177e2005-04-16 15:20:36 -07005145/*
5146 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005147 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005148 *
5149 * This basically trickles out pages so that we have _some_
5150 * free memory available even if there is no other activity
5151 * that frees anything up. This is needed for things like routing
5152 * etc, where we otherwise might have all activity going on in
5153 * asynchronous contexts that cannot page things out.
5154 *
5155 * If there are applications that are active memory-allocators
5156 * (most normal use), this basically shouldn't matter.
5157 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305158int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005159{
Mel Gormane716f2e2017-05-03 14:53:45 -07005160 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005161 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07005162 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005163 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10305164 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005165
Rusty Russell174596a2009-01-01 10:12:29 +10305166 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07005167 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005168
5169 /*
5170 * Tell the memory management that we're a "memory allocator",
5171 * and that if we need more memory we should get access to it
5172 * regardless (see "__alloc_pages()"). "kswapd" should
5173 * never get caught in the normal page freeing logic.
5174 *
5175 * (Kswapd normally doesn't need memory anyway, but sometimes
5176 * you need a small amount of memory in order to be able to
5177 * page out something else, and this flag essentially protects
5178 * us from recursively trying to free more memory as we're
5179 * trying to free the first piece of memory in the first place).
5180 */
Christoph Lameter930d9152006-01-08 01:00:47 -08005181 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07005182 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07005183
Qian Cai5644e1fb2020-04-01 21:10:12 -07005184 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005185 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005186 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08005187 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07005188
Qian Cai5644e1fb2020-04-01 21:10:12 -07005189 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005190 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5191 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07005192
Mel Gorman38087d92016-07-28 15:45:49 -07005193kswapd_try_sleep:
5194 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005195 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07005196
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005197 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08005198 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005199 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5200 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005201 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005202 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005203
David Rientjes8fe23e02009-12-14 17:58:33 -08005204 ret = try_to_freeze();
5205 if (kthread_should_stop())
5206 break;
5207
5208 /*
5209 * We can speed up thawing tasks if we don't call balance_pgdat
5210 * after returning from the refrigerator
5211 */
Mel Gorman38087d92016-07-28 15:45:49 -07005212 if (ret)
5213 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07005214
Mel Gorman38087d92016-07-28 15:45:49 -07005215 /*
5216 * Reclaim begins at the requested order but if a high-order
5217 * reclaim fails then kswapd falls back to reclaiming for
5218 * order-0. If that happens, kswapd will consider sleeping
5219 * for the order it finished reclaiming at (reclaim_order)
5220 * but kcompactd is woken to compact for the original
5221 * request (alloc_order).
5222 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005223 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07005224 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005225 reclaim_order = balance_pgdat(pgdat, alloc_order,
5226 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07005227 if (reclaim_order < alloc_order)
5228 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005229 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08005230
Johannes Weiner71abdc12014-06-06 14:35:35 -07005231 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07005232
Linus Torvalds1da177e2005-04-16 15:20:36 -07005233 return 0;
5234}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305235EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005236
5237/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07005238 * A zone is low on free memory or too fragmented for high-order memory. If
5239 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
5240 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
5241 * has failed or is not needed, still wake up kcompactd if only compaction is
5242 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005243 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07005244void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005245 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005246{
5247 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07005248 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005249
Mel Gorman6aa303d2016-09-01 16:14:55 -07005250 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005251 return;
5252
David Rientjes5ecd9d42018-04-05 16:25:16 -07005253 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005254 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07005255
Qian Cai5644e1fb2020-04-01 21:10:12 -07005256 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005257 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005258
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005259 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
5260 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005261
5262 if (READ_ONCE(pgdat->kswapd_order) < order)
5263 WRITE_ONCE(pgdat->kswapd_order, order);
5264
Con Kolivas8d0986e2005-09-13 01:25:07 -07005265 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005266 return;
Mel Gormane1a55632016-07-28 15:46:26 -07005267
David Rientjes5ecd9d42018-04-05 16:25:16 -07005268 /* Hopeless node, leave it to direct reclaim if possible */
5269 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005270 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
5271 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07005272 /*
5273 * There may be plenty of free memory available, but it's too
5274 * fragmented for high-order allocations. Wake up kcompactd
5275 * and rely on compaction_suitable() to determine if it's
5276 * needed. If it fails, it will defer subsequent attempts to
5277 * ratelimit its work.
5278 */
5279 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005280 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07005281 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07005282 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07005283
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005284 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07005285 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07005286 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005287}
5288
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005289#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07005290/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005291 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005292 * freed pages.
5293 *
5294 * Rather than trying to age LRUs the aim is to preserve the overall
5295 * LRU order by reclaiming preferentially
5296 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07005297 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005298unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005299{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005300 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005301 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07005302 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07005303 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005304 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07005305 .may_writepage = 1,
5306 .may_unmap = 1,
5307 .may_swap = 1,
5308 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07005309 };
Ying Hana09ed5e2011-05-24 17:12:26 -07005310 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005311 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005312 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005313
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01005314 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07005315 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07005316 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08005317
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005318 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005319
Andrew Morton1732d2b012019-07-16 16:26:15 -07005320 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005321 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005322 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005323
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005324 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005325}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005326#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07005327
Yasunori Goto3218ae12006-06-27 02:53:33 -07005328/*
5329 * This kswapd start function will be called by init and node-hot-add.
5330 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
5331 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07005332void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005333{
5334 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305335 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005336
5337 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07005338 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005339
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305340 trace_android_vh_kswapd_per_node(nid, &skip, true);
5341 if (skip)
5342 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005343 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
5344 if (IS_ERR(pgdat->kswapd)) {
5345 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02005346 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07005347 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07005348 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005349 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07005350}
5351
David Rientjes8fe23e02009-12-14 17:58:33 -08005352/*
Jiang Liud8adde12012-07-11 14:01:52 -07005353 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07005354 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08005355 */
5356void kswapd_stop(int nid)
5357{
5358 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305359 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08005360
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305361 trace_android_vh_kswapd_per_node(nid, &skip, false);
5362 if (skip)
5363 return;
Jiang Liud8adde12012-07-11 14:01:52 -07005364 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08005365 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07005366 NODE_DATA(nid)->kswapd = NULL;
5367 }
David Rientjes8fe23e02009-12-14 17:58:33 -08005368}
5369
Linus Torvalds1da177e2005-04-16 15:20:36 -07005370static int __init kswapd_init(void)
5371{
Wei Yang6b700b52020-04-01 21:10:09 -07005372 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08005373
Linus Torvalds1da177e2005-04-16 15:20:36 -07005374 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08005375 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005376 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005377 return 0;
5378}
5379
5380module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005381
5382#ifdef CONFIG_NUMA
5383/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005384 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08005385 *
Mel Gormana5f5f912016-07-28 15:46:32 -07005386 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08005387 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005388 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005389int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005390
Dave Hansen51998362021-02-24 12:09:15 -08005391/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005392 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08005393 * of a node considered for each zone_reclaim. 4 scans 1/16th of
5394 * a zone.
5395 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005396#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08005397
Christoph Lameter9eeff232006-01-18 17:42:31 -08005398/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005399 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07005400 * occur.
5401 */
5402int sysctl_min_unmapped_ratio = 1;
5403
5404/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07005405 * If the number of slab pages in a zone grows beyond this percentage then
5406 * slab reclaim needs to occur.
5407 */
5408int sysctl_min_slab_ratio = 5;
5409
Mel Gorman11fb9982016-07-28 15:46:20 -07005410static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005411{
Mel Gorman11fb9982016-07-28 15:46:20 -07005412 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
5413 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
5414 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005415
5416 /*
5417 * It's possible for there to be more file mapped pages than
5418 * accounted for by the pages on the file LRU lists because
5419 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
5420 */
5421 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
5422}
5423
5424/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07005425static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005426{
Alexandru Moised031a152015-11-05 18:48:08 -08005427 unsigned long nr_pagecache_reclaimable;
5428 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07005429
5430 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005431 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07005432 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07005433 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07005434 * a better estimate
5435 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005436 if (node_reclaim_mode & RECLAIM_UNMAP)
5437 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005438 else
Mel Gormana5f5f912016-07-28 15:46:32 -07005439 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005440
5441 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07005442 if (!(node_reclaim_mode & RECLAIM_WRITE))
5443 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005444
5445 /* Watch for any possible underflows due to delta */
5446 if (unlikely(delta > nr_pagecache_reclaimable))
5447 delta = nr_pagecache_reclaimable;
5448
5449 return nr_pagecache_reclaimable - delta;
5450}
5451
Christoph Lameter0ff38492006-09-25 23:31:52 -07005452/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005453 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005454 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005455static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005456{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08005457 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08005458 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005459 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005460 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08005461 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08005462 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005463 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07005464 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07005465 .priority = NODE_RECLAIM_PRIORITY,
5466 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
5467 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07005468 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005469 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08005470 };
Johannes Weiner57f29762021-08-19 19:04:27 -07005471 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005472
Yafang Shao132bb8c2019-05-13 17:17:53 -07005473 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
5474 sc.gfp_mask);
5475
Christoph Lameter9eeff232006-01-18 17:42:31 -08005476 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07005477 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07005478 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08005479 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005480 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08005481 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005482 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08005483 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07005484 noreclaim_flag = memalloc_noreclaim_save();
5485 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07005486 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08005487
Mel Gormana5f5f912016-07-28 15:46:32 -07005488 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07005489 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07005490 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07005491 * priorities until we have enough memory freed.
5492 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07005493 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07005494 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005495 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07005496 }
Christoph Lameterc84db232006-02-01 03:05:29 -08005497
Andrew Morton1732d2b012019-07-16 16:26:15 -07005498 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005499 current->flags &= ~PF_SWAPWRITE;
5500 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005501 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07005502 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07005503
5504 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
5505
Rik van Riela79311c2009-01-06 14:40:01 -08005506 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005507}
Andrew Morton179e9632006-03-22 00:08:18 -08005508
Mel Gormana5f5f912016-07-28 15:46:32 -07005509int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08005510{
David Rientjesd773ed62007-10-16 23:26:01 -07005511 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005512
5513 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005514 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07005515 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07005516 *
Christoph Lameter96146342006-07-03 00:24:13 -07005517 * A small portion of unmapped file backed pages is needed for
5518 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07005519 * thrown out if the node is overallocated. So we do not reclaim
5520 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07005521 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08005522 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005523 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07005524 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
5525 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07005526 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08005527
5528 /*
David Rientjesd773ed62007-10-16 23:26:01 -07005529 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08005530 */
Mel Gormand0164ad2015-11-06 16:28:21 -08005531 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07005532 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08005533
5534 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005535 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08005536 * have associated processors. This will favor the local processor
5537 * over remote processors and spread off node memory allocations
5538 * as wide as possible.
5539 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005540 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
5541 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07005542
Mel Gormana5f5f912016-07-28 15:46:32 -07005543 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
5544 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07005545
Mel Gormana5f5f912016-07-28 15:46:32 -07005546 ret = __node_reclaim(pgdat, gfp_mask, order);
5547 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07005548
Mel Gorman24cf725182009-06-16 15:33:23 -07005549 if (!ret)
5550 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
5551
David Rientjesd773ed62007-10-16 23:26:01 -07005552 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005553}
Christoph Lameter9eeff232006-01-18 17:42:31 -08005554#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07005555
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005556/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005557 * check_move_unevictable_pages - check pages for evictability and move to
5558 * appropriate zone lru list
5559 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005560 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005561 * Checks pages for evictability, if an evictable page is in the unevictable
5562 * lru list, moves it to the appropriate evictable lru list. This function
5563 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005564 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005565void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005566{
Alex Shi6168d0d2020-12-15 12:34:29 -08005567 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08005568 int pgscanned = 0;
5569 int pgrescued = 0;
5570 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005571
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005572 for (i = 0; i < pvec->nr; i++) {
5573 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005574 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07005575
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005576 if (PageTransTail(page))
5577 continue;
5578
5579 nr_pages = thp_nr_pages(page);
5580 pgscanned += nr_pages;
5581
Alex Shid25b5bd2020-12-15 12:34:16 -08005582 /* block memcg migration during page moving between lru */
5583 if (!TestClearPageLRU(page))
5584 continue;
5585
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08005586 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005587 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08005588 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08005589 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08005590 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005591 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08005592 }
Alex Shid25b5bd2020-12-15 12:34:16 -08005593 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005594 }
Hugh Dickins24513262012-01-20 14:34:21 -08005595
Alex Shi6168d0d2020-12-15 12:34:29 -08005596 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08005597 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
5598 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08005599 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005600 } else if (pgscanned) {
5601 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08005602 }
Hugh Dickins850465792012-01-20 14:34:19 -08005603}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005604EXPORT_SYMBOL_GPL(check_move_unevictable_pages);