blob: 6296b760d191c0fb526b0a024b67c1017ab61e28 [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>
Yu Zhao7f53b0e2022-09-18 02:00:05 -060053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhaobaeb9a02022-09-18 02:00:07 -060055#include <linux/ctype.h>
Yu Zhao4983c522022-09-18 02:00:09 -060056#include <linux/debugfs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070057
58#include <asm/tlbflush.h>
59#include <asm/div64.h>
60
61#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070062#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070063
Nick Piggin0f8053a2006-03-22 00:08:33 -080064#include "internal.h"
65
Mel Gorman33906bc2010-08-09 17:19:16 -070066#define CREATE_TRACE_POINTS
67#include <trace/events/vmscan.h>
68
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070069#undef CREATE_TRACE_POINTS
70#include <trace/hooks/vmscan.h>
71
Martin Liud705ab992021-06-23 12:20:18 +080072EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
73EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
74
Linus Torvalds1da177e2005-04-16 15:20:36 -070075struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080076 /* How many pages shrink_list() should reclaim */
77 unsigned long nr_to_reclaim;
78
Johannes Weineree814fe2014-08-06 16:06:19 -070079 /*
80 * Nodemask of nodes allowed by the caller. If NULL, all nodes
81 * are scanned.
82 */
83 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070084
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070085 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080086 * The memory cgroup that hit its limit and as a result is the
87 * primary target of this reclaim invocation.
88 */
89 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080090
Johannes Weiner7cf111b2020-06-03 16:03:06 -070091 /*
92 * Scan pressure balancing between anon and file LRUs
93 */
94 unsigned long anon_cost;
95 unsigned long file_cost;
96
Johannes Weinerb91ac372019-11-30 17:56:02 -080097 /* Can active pages be deactivated as part of reclaim? */
98#define DEACTIVATE_ANON 1
99#define DEACTIVATE_FILE 2
100 unsigned int may_deactivate:2;
101 unsigned int force_deactivate:1;
102 unsigned int skipped_deactivate:1;
103
Johannes Weiner1276ad62017-02-24 14:56:11 -0800104 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700105 unsigned int may_writepage:1;
106
107 /* Can mapped pages be reclaimed? */
108 unsigned int may_unmap:1;
109
110 /* Can pages be swapped as part of reclaim? */
111 unsigned int may_swap:1;
112
Yisheng Xied6622f62017-05-03 14:53:57 -0700113 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700114 * Cgroup memory below memory.low is protected as long as we
115 * don't threaten to OOM. If any cgroup is reclaimed at
116 * reduced force or passed over entirely due to its memory.low
117 * setting (memcg_low_skipped), and nothing is reclaimed as a
118 * result, then go back for one more cycle that reclaims the protected
119 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700120 */
121 unsigned int memcg_low_reclaim:1;
122 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800123
Johannes Weineree814fe2014-08-06 16:06:19 -0700124 unsigned int hibernation_mode:1;
125
126 /* One of the zones is ready for compaction */
127 unsigned int compaction_ready:1;
128
Johannes Weinerb91ac372019-11-30 17:56:02 -0800129 /* There is easily reclaimable cold cache in the current node */
130 unsigned int cache_trim_mode:1;
131
Johannes Weiner53138ce2019-11-30 17:55:56 -0800132 /* The file pages on the current node are dangerously low */
133 unsigned int file_is_tiny:1;
134
Dave Hansen26aa2d12021-09-02 14:59:16 -0700135 /* Always discard instead of demoting to lower tier memory */
136 unsigned int no_demotion:1;
137
Yu Zhaoa8a158a2022-09-18 02:00:06 -0600138#ifdef CONFIG_LRU_GEN
139 /* help kswapd make better choices among multiple memcgs */
140 unsigned int memcgs_need_aging:1;
141 unsigned long last_reclaimed;
142#endif
143
Greg Thelenbb451fd2018-08-17 15:45:19 -0700144 /* Allocation order */
145 s8 order;
146
147 /* Scan (total_size >> priority) pages at once */
148 s8 priority;
149
150 /* The highest zone to isolate pages for reclaim from */
151 s8 reclaim_idx;
152
153 /* This context's GFP mask */
154 gfp_t gfp_mask;
155
Johannes Weineree814fe2014-08-06 16:06:19 -0700156 /* Incremented by the number of inactive pages that were scanned */
157 unsigned long nr_scanned;
158
159 /* Number of pages freed so far during a call to shrink_zones() */
160 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700161
162 struct {
163 unsigned int dirty;
164 unsigned int unqueued_dirty;
165 unsigned int congested;
166 unsigned int writeback;
167 unsigned int immediate;
168 unsigned int file_taken;
169 unsigned int taken;
170 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700171
172 /* for recording the reclaimed slab by now */
173 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700174};
175
Linus Torvalds1da177e2005-04-16 15:20:36 -0700176#ifdef ARCH_HAS_PREFETCHW
177#define prefetchw_prev_lru_page(_page, _base, _field) \
178 do { \
179 if ((_page)->lru.prev != _base) { \
180 struct page *prev; \
181 \
182 prev = lru_to_page(&(_page->lru)); \
183 prefetchw(&prev->_field); \
184 } \
185 } while (0)
186#else
187#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
188#endif
189
190/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700191 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700192 */
193int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194
Yang Shi0a432dc2019-09-23 15:38:12 -0700195static void set_task_reclaim_state(struct task_struct *task,
196 struct reclaim_state *rs)
197{
198 /* Check for an overwrite */
199 WARN_ON_ONCE(rs && task->reclaim_state);
200
201 /* Check for the nulling of an already-nulled member */
202 WARN_ON_ONCE(!rs && !task->reclaim_state);
203
204 task->reclaim_state = rs;
205}
206
Linus Torvalds1da177e2005-04-16 15:20:36 -0700207static LIST_HEAD(shrinker_list);
208static DECLARE_RWSEM(shrinker_rwsem);
209
Yang Shi0a432dc2019-09-23 15:38:12 -0700210#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700211static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700212
Yang Shi3c6f17e2021-05-04 18:36:33 -0700213/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700214static inline int shrinker_map_size(int nr_items)
215{
216 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
217}
Yang Shi2bfd3632021-05-04 18:36:11 -0700218
Yang Shi3c6f17e2021-05-04 18:36:33 -0700219static inline int shrinker_defer_size(int nr_items)
220{
221 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
222}
223
Yang Shi468ab842021-05-04 18:36:26 -0700224static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
225 int nid)
226{
227 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
228 lockdep_is_held(&shrinker_rwsem));
229}
230
Yang Shie4262c42021-05-04 18:36:23 -0700231static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700232 int map_size, int defer_size,
233 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700234{
Yang Shie4262c42021-05-04 18:36:23 -0700235 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700236 struct mem_cgroup_per_node *pn;
237 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700238 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700239
Yang Shi2bfd3632021-05-04 18:36:11 -0700240 for_each_node(nid) {
241 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700242 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700243 /* Not yet online memcg */
244 if (!old)
245 return 0;
246
247 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
248 if (!new)
249 return -ENOMEM;
250
Yang Shi3c6f17e2021-05-04 18:36:33 -0700251 new->nr_deferred = (atomic_long_t *)(new + 1);
252 new->map = (void *)new->nr_deferred + defer_size;
253
254 /* map: set all old bits, clear all new bits */
255 memset(new->map, (int)0xff, old_map_size);
256 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
257 /* nr_deferred: copy old values, clear all new values */
258 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
259 memset((void *)new->nr_deferred + old_defer_size, 0,
260 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700261
Yang Shie4262c42021-05-04 18:36:23 -0700262 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700263 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700264 }
265
266 return 0;
267}
268
Yang Shie4262c42021-05-04 18:36:23 -0700269void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700270{
271 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700272 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700273 int nid;
274
Yang Shi2bfd3632021-05-04 18:36:11 -0700275 for_each_node(nid) {
276 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700277 info = rcu_dereference_protected(pn->shrinker_info, true);
278 kvfree(info);
279 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700280 }
281}
282
Yang Shie4262c42021-05-04 18:36:23 -0700283int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700284{
Yang Shie4262c42021-05-04 18:36:23 -0700285 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700286 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700287 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700288
Yang Shid27cf2a2021-05-04 18:36:14 -0700289 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700290 map_size = shrinker_map_size(shrinker_nr_max);
291 defer_size = shrinker_defer_size(shrinker_nr_max);
292 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700293 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700294 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
295 if (!info) {
296 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700297 ret = -ENOMEM;
298 break;
299 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700300 info->nr_deferred = (atomic_long_t *)(info + 1);
301 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700302 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700303 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700304 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700305
306 return ret;
307}
308
Yang Shi3c6f17e2021-05-04 18:36:33 -0700309static inline bool need_expand(int nr_max)
310{
311 return round_up(nr_max, BITS_PER_LONG) >
312 round_up(shrinker_nr_max, BITS_PER_LONG);
313}
314
Yang Shie4262c42021-05-04 18:36:23 -0700315static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700316{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700317 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700318 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700319 int map_size, defer_size = 0;
320 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700321 struct mem_cgroup *memcg;
322
Yang Shi3c6f17e2021-05-04 18:36:33 -0700323 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700324 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700325
Yang Shi2bfd3632021-05-04 18:36:11 -0700326 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700327 goto out;
328
329 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700330
Yang Shi3c6f17e2021-05-04 18:36:33 -0700331 map_size = shrinker_map_size(new_nr_max);
332 defer_size = shrinker_defer_size(new_nr_max);
333 old_map_size = shrinker_map_size(shrinker_nr_max);
334 old_defer_size = shrinker_defer_size(shrinker_nr_max);
335
Yang Shi2bfd3632021-05-04 18:36:11 -0700336 memcg = mem_cgroup_iter(NULL, NULL, NULL);
337 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700338 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
339 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700340 if (ret) {
341 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700342 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700343 }
344 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700345out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700347 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700348
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 return ret;
350}
351
352void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
353{
354 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700355 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700356
357 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700358 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700359 /* Pairs with smp mb in shrink_slab() */
360 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700361 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700362 rcu_read_unlock();
363 }
364}
365
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700366static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700367
368static int prealloc_memcg_shrinker(struct shrinker *shrinker)
369{
370 int id, ret = -ENOMEM;
371
Yang Shi476b30a2021-05-04 18:36:39 -0700372 if (mem_cgroup_disabled())
373 return -ENOSYS;
374
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700375 down_write(&shrinker_rwsem);
376 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700377 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700378 if (id < 0)
379 goto unlock;
380
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700381 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700382 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700383 idr_remove(&shrinker_idr, id);
384 goto unlock;
385 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700386 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700387 shrinker->id = id;
388 ret = 0;
389unlock:
390 up_write(&shrinker_rwsem);
391 return ret;
392}
393
394static void unregister_memcg_shrinker(struct shrinker *shrinker)
395{
396 int id = shrinker->id;
397
398 BUG_ON(id < 0);
399
Yang Shi41ca6682021-05-04 18:36:29 -0700400 lockdep_assert_held(&shrinker_rwsem);
401
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700402 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700403}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700404
Yang Shi86750832021-05-04 18:36:36 -0700405static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
406 struct mem_cgroup *memcg)
407{
408 struct shrinker_info *info;
409
410 info = shrinker_info_protected(memcg, nid);
411 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
412}
413
414static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
415 struct mem_cgroup *memcg)
416{
417 struct shrinker_info *info;
418
419 info = shrinker_info_protected(memcg, nid);
420 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
421}
422
Yang Shia1780152021-05-04 18:36:42 -0700423void reparent_shrinker_deferred(struct mem_cgroup *memcg)
424{
425 int i, nid;
426 long nr;
427 struct mem_cgroup *parent;
428 struct shrinker_info *child_info, *parent_info;
429
430 parent = parent_mem_cgroup(memcg);
431 if (!parent)
432 parent = root_mem_cgroup;
433
434 /* Prevent from concurrent shrinker_info expand */
435 down_read(&shrinker_rwsem);
436 for_each_node(nid) {
437 child_info = shrinker_info_protected(memcg, nid);
438 parent_info = shrinker_info_protected(parent, nid);
439 for (i = 0; i < shrinker_nr_max; i++) {
440 nr = atomic_long_read(&child_info->nr_deferred[i]);
441 atomic_long_add(nr, &parent_info->nr_deferred[i]);
442 }
443 }
444 up_read(&shrinker_rwsem);
445}
446
Johannes Weinerb5ead352019-11-30 17:55:40 -0800447static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800448{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800449 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800450}
Tejun Heo97c93412015-05-22 18:23:36 -0400451
452/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800453 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400454 * @sc: scan_control in question
455 *
456 * The normal page dirty throttling mechanism in balance_dirty_pages() is
457 * completely broken with the legacy memcg and direct stalling in
458 * shrink_page_list() is used for throttling instead, which lacks all the
459 * niceties such as fairness, adaptive pausing, bandwidth proportional
460 * allocation and configurability.
461 *
462 * This function tests whether the vmscan currently in progress can assume
463 * that the normal dirty throttling mechanism is operational.
464 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800465static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400466{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800467 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400468 return true;
469#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800470 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400471 return true;
472#endif
473 return false;
474}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800475#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700476static int prealloc_memcg_shrinker(struct shrinker *shrinker)
477{
Yang Shi476b30a2021-05-04 18:36:39 -0700478 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700479}
480
481static void unregister_memcg_shrinker(struct shrinker *shrinker)
482{
483}
484
Yang Shi86750832021-05-04 18:36:36 -0700485static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
486 struct mem_cgroup *memcg)
487{
488 return 0;
489}
490
491static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
492 struct mem_cgroup *memcg)
493{
494 return 0;
495}
496
Johannes Weinerb5ead352019-11-30 17:55:40 -0800497static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800498{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800499 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800500}
Tejun Heo97c93412015-05-22 18:23:36 -0400501
Johannes Weinerb5ead352019-11-30 17:55:40 -0800502static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400503{
504 return true;
505}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800506#endif
507
Yang Shi86750832021-05-04 18:36:36 -0700508static long xchg_nr_deferred(struct shrinker *shrinker,
509 struct shrink_control *sc)
510{
511 int nid = sc->nid;
512
513 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
514 nid = 0;
515
516 if (sc->memcg &&
517 (shrinker->flags & SHRINKER_MEMCG_AWARE))
518 return xchg_nr_deferred_memcg(nid, shrinker,
519 sc->memcg);
520
521 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
522}
523
524
525static long add_nr_deferred(long nr, struct shrinker *shrinker,
526 struct shrink_control *sc)
527{
528 int nid = sc->nid;
529
530 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
531 nid = 0;
532
533 if (sc->memcg &&
534 (shrinker->flags & SHRINKER_MEMCG_AWARE))
535 return add_nr_deferred_memcg(nr, nid, shrinker,
536 sc->memcg);
537
538 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
539}
540
Dave Hansen26aa2d12021-09-02 14:59:16 -0700541static bool can_demote(int nid, struct scan_control *sc)
542{
Huang Ying20b51af12021-09-02 14:59:33 -0700543 if (!numa_demotion_enabled)
544 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700545 if (sc) {
546 if (sc->no_demotion)
547 return false;
548 /* It is pointless to do demotion in memcg reclaim */
549 if (cgroup_reclaim(sc))
550 return false;
551 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700552 if (next_demotion_node(nid) == NUMA_NO_NODE)
553 return false;
554
Huang Ying20b51af12021-09-02 14:59:33 -0700555 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700556}
557
Keith Buscha2a36482021-09-02 14:59:26 -0700558static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
559 int nid,
560 struct scan_control *sc)
561{
562 if (memcg == NULL) {
563 /*
564 * For non-memcg reclaim, is there
565 * space in any swap device?
566 */
567 if (get_nr_swap_pages() > 0)
568 return true;
569 } else {
570 /* Is the memcg below its swap limit? */
571 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
572 return true;
573 }
574
575 /*
576 * The page can not be swapped.
577 *
578 * Can it be reclaimed from this node via demotion?
579 */
580 return can_demote(nid, sc);
581}
582
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700583/*
584 * This misses isolated pages which are not accounted for to save counters.
585 * As the data only determines if reclaim or compaction continues, it is
586 * not expected that isolated pages will be a dominating factor.
587 */
588unsigned long zone_reclaimable_pages(struct zone *zone)
589{
590 unsigned long nr;
591
592 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
593 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700594 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700595 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
596 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
597
598 return nr;
599}
600
Michal Hockofd538802017-02-22 15:45:58 -0800601/**
602 * lruvec_lru_size - Returns the number of pages on the given LRU list.
603 * @lruvec: lru vector
604 * @lru: lru to use
605 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
606 */
Yu Zhao20913392021-02-24 12:08:44 -0800607static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
608 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800609{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800610 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800611 int zid;
612
Johannes Weinerde3b0152019-11-30 17:55:31 -0800613 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800614 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800615
Michal Hockofd538802017-02-22 15:45:58 -0800616 if (!managed_zone(zone))
617 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800618
Michal Hockofd538802017-02-22 15:45:58 -0800619 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800620 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800621 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800622 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800623 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800624 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800625}
626
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000628 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700629 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900630int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700631{
Yang Shi476b30a2021-05-04 18:36:39 -0700632 unsigned int size;
633 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000634
Yang Shi476b30a2021-05-04 18:36:39 -0700635 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
636 err = prealloc_memcg_shrinker(shrinker);
637 if (err != -ENOSYS)
638 return err;
639
640 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
641 }
642
643 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000644 if (shrinker->flags & SHRINKER_NUMA_AWARE)
645 size *= nr_node_ids;
646
647 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
648 if (!shrinker->nr_deferred)
649 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700650
Tetsuo Handa8e049442018-04-04 19:53:07 +0900651 return 0;
652}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000653
Tetsuo Handa8e049442018-04-04 19:53:07 +0900654void free_prealloced_shrinker(struct shrinker *shrinker)
655{
Yang Shi41ca6682021-05-04 18:36:29 -0700656 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
657 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700658 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700659 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700660 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700661 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700662
Tetsuo Handa8e049442018-04-04 19:53:07 +0900663 kfree(shrinker->nr_deferred);
664 shrinker->nr_deferred = NULL;
665}
666
667void register_shrinker_prepared(struct shrinker *shrinker)
668{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700669 down_write(&shrinker_rwsem);
670 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700671 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700672 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900673}
674
675int register_shrinker(struct shrinker *shrinker)
676{
677 int err = prealloc_shrinker(shrinker);
678
679 if (err)
680 return err;
681 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000682 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700684EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700685
686/*
687 * Remove one
688 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700689void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690{
Yang Shi41ca6682021-05-04 18:36:29 -0700691 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900692 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700693
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694 down_write(&shrinker_rwsem);
695 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700696 shrinker->flags &= ~SHRINKER_REGISTERED;
697 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
698 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700700
Andrew Vaginae393322013-10-16 13:46:46 -0700701 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900702 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700703}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700704EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700705
706#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000707
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800708static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800709 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700710{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000711 unsigned long freed = 0;
712 unsigned long long delta;
713 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700714 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000715 long nr;
716 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000717 long batch_size = shrinker->batch ? shrinker->batch
718 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800719 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720
rongqianfeng8da6ee32021-05-21 10:30:14 +0800721 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
722
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700723 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700724 if (freeable == 0 || freeable == SHRINK_EMPTY)
725 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000726
727 /*
728 * copy the current shrinker scan count into a local variable
729 * and zero it so that other concurrent shrinker invocations
730 * don't also do this scanning work.
731 */
Yang Shi86750832021-05-04 18:36:36 -0700732 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000733
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700734 if (shrinker->seeks) {
735 delta = freeable >> priority;
736 delta *= 4;
737 do_div(delta, shrinker->seeks);
738 } else {
739 /*
740 * These objects don't require any IO to create. Trim
741 * them aggressively under memory pressure to keep
742 * them from causing refetches in the IO caches.
743 */
744 delta = freeable / 2;
745 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700746
Yang Shi18bb4732021-05-04 18:36:45 -0700747 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000748 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700749 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000750
751 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800752 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000753
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800754 /*
755 * Normally, we should not scan less than batch_size objects in one
756 * pass to avoid too frequent shrinker calls, but if the slab has less
757 * than batch_size objects in total and we are really tight on memory,
758 * we will try to reclaim all available objects, otherwise we can end
759 * up failing allocations although there are plenty of reclaimable
760 * objects spread over several slabs with usage less than the
761 * batch_size.
762 *
763 * We detect the "tight on memory" situations by looking at the total
764 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700765 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800766 * scanning at high prio and therefore should try to reclaim as much as
767 * possible.
768 */
769 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700770 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000771 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800772 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000773
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800774 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700775 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000776 ret = shrinker->scan_objects(shrinker, shrinkctl);
777 if (ret == SHRINK_STOP)
778 break;
779 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000780
Chris Wilsond460acb2017-09-06 16:19:26 -0700781 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
782 total_scan -= shrinkctl->nr_scanned;
783 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000784
785 cond_resched();
786 }
787
Yang Shi18bb4732021-05-04 18:36:45 -0700788 /*
789 * The deferred work is increased by any new work (delta) that wasn't
790 * done, decreased by old deferred work that was done now.
791 *
792 * And it is capped to two times of the freeable items.
793 */
794 next_deferred = max_t(long, (nr + delta - scanned), 0);
795 next_deferred = min(next_deferred, (2 * freeable));
796
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797 /*
798 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700799 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000800 */
Yang Shi86750832021-05-04 18:36:36 -0700801 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000802
Yang Shi8efb4b52021-05-04 18:36:08 -0700803 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000804 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700805}
806
Yang Shi0a432dc2019-09-23 15:38:12 -0700807#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700808static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
809 struct mem_cgroup *memcg, int priority)
810{
Yang Shie4262c42021-05-04 18:36:23 -0700811 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700812 unsigned long ret, freed = 0;
813 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700814
Yang Shi0a432dc2019-09-23 15:38:12 -0700815 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700816 return 0;
817
818 if (!down_read_trylock(&shrinker_rwsem))
819 return 0;
820
Yang Shi468ab842021-05-04 18:36:26 -0700821 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700822 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700823 goto unlock;
824
Yang Shie4262c42021-05-04 18:36:23 -0700825 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700826 struct shrink_control sc = {
827 .gfp_mask = gfp_mask,
828 .nid = nid,
829 .memcg = memcg,
830 };
831 struct shrinker *shrinker;
832
833 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700834 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700835 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700836 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700837 continue;
838 }
839
Yang Shi0a432dc2019-09-23 15:38:12 -0700840 /* Call non-slab shrinkers even though kmem is disabled */
841 if (!memcg_kmem_enabled() &&
842 !(shrinker->flags & SHRINKER_NONSLAB))
843 continue;
844
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700845 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700846 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700847 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700848 /*
849 * After the shrinker reported that it had no objects to
850 * free, but before we cleared the corresponding bit in
851 * the memcg shrinker map, a new object might have been
852 * added. To make sure, we have the bit set in this
853 * case, we invoke the shrinker one more time and reset
854 * the bit if it reports that it is not empty anymore.
855 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700856 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700857 *
858 * list_lru_add() shrink_slab_memcg()
859 * list_add_tail() clear_bit()
860 * <MB> <MB>
861 * set_bit() do_shrink_slab()
862 */
863 smp_mb__after_atomic();
864 ret = do_shrink_slab(&sc, shrinker, priority);
865 if (ret == SHRINK_EMPTY)
866 ret = 0;
867 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700868 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700869 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700870 freed += ret;
871
872 if (rwsem_is_contended(&shrinker_rwsem)) {
873 freed = freed ? : 1;
874 break;
875 }
876 }
877unlock:
878 up_read(&shrinker_rwsem);
879 return freed;
880}
Yang Shi0a432dc2019-09-23 15:38:12 -0700881#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700882static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
883 struct mem_cgroup *memcg, int priority)
884{
885 return 0;
886}
Yang Shi0a432dc2019-09-23 15:38:12 -0700887#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700888
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800889/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800890 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800891 * @gfp_mask: allocation context
892 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800893 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800894 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800896 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800898 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
899 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700900 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700901 * @memcg specifies the memory cgroup to target. Unaware shrinkers
902 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800903 *
Josef Bacik9092c712018-01-31 16:16:26 -0800904 * @priority is sc->priority, we take the number of objects and >> by priority
905 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700906 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800907 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800909unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800910 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800911 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700912{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700913 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700914 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800915 bool bypass = false;
916
917 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
918 if (bypass)
919 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700920
Yang Shifa1e5122019-08-02 21:48:44 -0700921 /*
922 * The root memcg might be allocated even though memcg is disabled
923 * via "cgroup_disable=memory" boot parameter. This could make
924 * mem_cgroup_is_root() return false, then just run memcg slab
925 * shrink, but skip global shrink. This may result in premature
926 * oom.
927 */
928 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700929 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800930
Tetsuo Handae830c632018-04-05 16:23:35 -0700931 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700932 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933
934 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800935 struct shrink_control sc = {
936 .gfp_mask = gfp_mask,
937 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800938 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800939 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800940
Kirill Tkhai9b996462018-08-17 15:48:21 -0700941 ret = do_shrink_slab(&sc, shrinker, priority);
942 if (ret == SHRINK_EMPTY)
943 ret = 0;
944 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800945 /*
946 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700947 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800948 * by parallel ongoing shrinking.
949 */
950 if (rwsem_is_contended(&shrinker_rwsem)) {
951 freed = freed ? : 1;
952 break;
953 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700954 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800955
Linus Torvalds1da177e2005-04-16 15:20:36 -0700956 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700957out:
958 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000959 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700960}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800961EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700962
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800963void drop_slab_node(int nid)
964{
965 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700966 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800967
968 do {
969 struct mem_cgroup *memcg = NULL;
970
Chunxin Zang069c4112020-10-13 16:56:46 -0700971 if (fatal_signal_pending(current))
972 return;
973
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800974 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700975 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800976 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800977 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800978 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700979 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800980}
981
982void drop_slab(void)
983{
984 int nid;
985
986 for_each_online_node(nid)
987 drop_slab_node(nid);
988}
989
Linus Torvalds1da177e2005-04-16 15:20:36 -0700990static inline int is_page_cache_freeable(struct page *page)
991{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700992 /*
993 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400994 * that isolated the page, the page cache and optional buffer
995 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700996 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700997 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400998 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700999}
1000
Yang Shicb165562019-11-30 17:55:28 -08001001static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002{
Christoph Lameter930d9152006-01-08 01:00:47 -08001003 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001004 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001005 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001007 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001008 return 1;
1009 return 0;
1010}
1011
1012/*
1013 * We detected a synchronous write error writing a page out. Probably
1014 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1015 * fsync(), msync() or close().
1016 *
1017 * The tricky part is that after writepage we cannot touch the mapping: nothing
1018 * prevents it from being freed up. But we have a ref on the page and once
1019 * that page is locked, the mapping is pinned.
1020 *
1021 * We're allowed to run sleeping lock_page() here because we know the caller has
1022 * __GFP_FS.
1023 */
1024static void handle_write_error(struct address_space *mapping,
1025 struct page *page, int error)
1026{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001027 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001028 if (page_mapping(page) == mapping)
1029 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001030 unlock_page(page);
1031}
1032
Christoph Lameter04e62a22006-06-23 02:03:38 -07001033/* possible outcome of pageout() */
1034typedef enum {
1035 /* failed to write page out, page is locked */
1036 PAGE_KEEP,
1037 /* move page to the active list, page is locked */
1038 PAGE_ACTIVATE,
1039 /* page has been sent to the disk successfully, page is unlocked */
1040 PAGE_SUCCESS,
1041 /* page is clean and locked */
1042 PAGE_CLEAN,
1043} pageout_t;
1044
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045/*
Andrew Morton1742f192006-03-22 00:08:21 -08001046 * pageout is called by shrink_page_list() for each dirty page.
1047 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048 */
Yang Shicb165562019-11-30 17:55:28 -08001049static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001050{
1051 /*
1052 * If the page is dirty, only perform writeback if that write
1053 * will be non-blocking. To prevent this allocation from being
1054 * stalled by pagecache activity. But note that there may be
1055 * stalls if we need to run get_block(). We could test
1056 * PagePrivate for that.
1057 *
Al Viro81742022014-04-03 03:17:43 -04001058 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001059 * this page's queue, we can perform writeback even if that
1060 * will block.
1061 *
1062 * If the page is swapcache, write it back even if that would
1063 * block, for some throttling. This happens by accident, because
1064 * swap_backing_dev_info is bust: it doesn't reflect the
1065 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001066 */
1067 if (!is_page_cache_freeable(page))
1068 return PAGE_KEEP;
1069 if (!mapping) {
1070 /*
1071 * Some data journaling orphaned pages can have
1072 * page->mapping == NULL while being dirty with clean buffers.
1073 */
David Howells266cf652009-04-03 16:42:36 +01001074 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 if (try_to_free_buffers(page)) {
1076 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001077 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001078 return PAGE_CLEAN;
1079 }
1080 }
1081 return PAGE_KEEP;
1082 }
1083 if (mapping->a_ops->writepage == NULL)
1084 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001085 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086 return PAGE_KEEP;
1087
1088 if (clear_page_dirty_for_io(page)) {
1089 int res;
1090 struct writeback_control wbc = {
1091 .sync_mode = WB_SYNC_NONE,
1092 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001093 .range_start = 0,
1094 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001095 .for_reclaim = 1,
1096 };
1097
1098 SetPageReclaim(page);
1099 res = mapping->a_ops->writepage(page, &wbc);
1100 if (res < 0)
1101 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001102 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001103 ClearPageReclaim(page);
1104 return PAGE_ACTIVATE;
1105 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001106
Linus Torvalds1da177e2005-04-16 15:20:36 -07001107 if (!PageWriteback(page)) {
1108 /* synchronous write or broken a_ops? */
1109 ClearPageReclaim(page);
1110 }
yalin wang3aa23852016-01-14 15:18:30 -08001111 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001112 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001113 return PAGE_SUCCESS;
1114 }
1115
1116 return PAGE_CLEAN;
1117}
1118
Andrew Mortona649fd92006-10-17 00:09:36 -07001119/*
Nick Piggine2867812008-07-25 19:45:30 -07001120 * Same as remove_mapping, but if the page is removed from the mapping, it
1121 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001122 */
Johannes Weinera5289102014-04-03 14:47:51 -07001123static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001124 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001125{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001126 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001127 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001128
Nick Piggin28e4d962006-09-25 23:31:23 -07001129 BUG_ON(!PageLocked(page));
1130 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001131
Johannes Weiner30472502021-09-02 14:53:18 -07001132 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001133 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001134 * The non racy check for a busy page.
1135 *
1136 * Must be careful with the order of the tests. When someone has
1137 * a ref to the page, it may be possible that they dirty it then
1138 * drop the reference. So if PageDirty is tested before page_count
1139 * here, then the following race may occur:
1140 *
1141 * get_user_pages(&page);
1142 * [user mapping goes away]
1143 * write_to(page);
1144 * !PageDirty(page) [good]
1145 * SetPageDirty(page);
1146 * put_page(page);
1147 * !page_count(page) [good, discard it]
1148 *
1149 * [oops, our write_to data is lost]
1150 *
1151 * Reversing the order of the tests ensures such a situation cannot
1152 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001153 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001154 *
1155 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001156 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001157 */
William Kucharski906d2782019-10-18 20:20:33 -07001158 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001159 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001160 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001161 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001162 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001163 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001164 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001165 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001166
1167 if (PageSwapCache(page)) {
1168 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001169
1170 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001171 if (reclaimed && !mapping_exiting(mapping))
1172 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001173 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001174 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001175 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001176 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001177 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001178 void (*freepage)(struct page *);
1179
1180 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001181 /*
1182 * Remember a shadow entry for reclaimed file cache in
1183 * order to detect refaults, thus thrashing, later on.
1184 *
1185 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001186 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001187 * inode reclaim needs to empty out the radix tree or
1188 * the nodes are lost. Don't plant shadows behind its
1189 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001190 *
1191 * We also don't store shadows for DAX mappings because the
1192 * only page cache pages found in these are zero pages
1193 * covering holes, and because we don't want to mix DAX
1194 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001195 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001196 */
Huang Ying9de4f222020-04-06 20:04:41 -07001197 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001198 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001199 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001200 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001201 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001202
1203 if (freepage != NULL)
1204 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001205 }
1206
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001207 return 1;
1208
1209cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001210 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001211 return 0;
1212}
1213
Linus Torvalds1da177e2005-04-16 15:20:36 -07001214/*
Nick Piggine2867812008-07-25 19:45:30 -07001215 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1216 * someone else has a ref on the page, abort and return 0. If it was
1217 * successfully detached, return 1. Assumes the caller has a single ref on
1218 * this page.
1219 */
1220int remove_mapping(struct address_space *mapping, struct page *page)
1221{
Johannes Weinerb9107182019-11-30 17:55:59 -08001222 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001223 /*
1224 * Unfreezing the refcount with 1 rather than 2 effectively
1225 * drops the pagecache ref for us without requiring another
1226 * atomic operation.
1227 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001228 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001229 return 1;
1230 }
1231 return 0;
1232}
1233
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001234/**
1235 * putback_lru_page - put previously isolated page onto appropriate LRU list
1236 * @page: page to be put back to appropriate lru list
1237 *
1238 * Add previously isolated @page to appropriate LRU list.
1239 * Page may still be unevictable for other reasons.
1240 *
1241 * lru_lock must not be held, interrupts must be enabled.
1242 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001243void putback_lru_page(struct page *page)
1244{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001245 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001246 put_page(page); /* drop ref from isolate */
1247}
1248
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001249enum page_references {
1250 PAGEREF_RECLAIM,
1251 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001252 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001253 PAGEREF_ACTIVATE,
1254};
1255
1256static enum page_references page_check_references(struct page *page,
1257 struct scan_control *sc)
1258{
Johannes Weiner645747462010-03-05 13:42:22 -08001259 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001260 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001261
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001262 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1263 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001264 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001265
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001266 /*
1267 * Mlock lost the isolation race with us. Let try_to_unmap()
1268 * move the page to the unevictable list.
1269 */
1270 if (vm_flags & VM_LOCKED)
1271 return PAGEREF_RECLAIM;
1272
Minchan Kimf74aca72022-05-19 14:08:54 -07001273 /* rmap lock contention: rotate */
1274 if (referenced_ptes == -1)
1275 return PAGEREF_KEEP;
1276
Johannes Weiner645747462010-03-05 13:42:22 -08001277 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001278 /*
1279 * All mapped pages start out with page table
1280 * references from the instantiating fault, so we need
1281 * to look twice if a mapped file page is used more
1282 * than once.
1283 *
1284 * Mark it and spare it for another trip around the
1285 * inactive list. Another page table reference will
1286 * lead to its activation.
1287 *
1288 * Note: the mark is set for activated pages as well
1289 * so that recently deactivated but used pages are
1290 * quickly recovered.
1291 */
1292 SetPageReferenced(page);
1293
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001294 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001295 return PAGEREF_ACTIVATE;
1296
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001297 /*
1298 * Activate file-backed executable pages after first usage.
1299 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001300 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001301 return PAGEREF_ACTIVATE;
1302
Johannes Weiner645747462010-03-05 13:42:22 -08001303 return PAGEREF_KEEP;
1304 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001305
1306 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001307 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001308 return PAGEREF_RECLAIM_CLEAN;
1309
1310 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001311}
1312
Mel Gormane2be15f2013-07-03 15:01:57 -07001313/* Check if a page is dirty or under writeback */
1314static void page_check_dirty_writeback(struct page *page,
1315 bool *dirty, bool *writeback)
1316{
Mel Gormanb4597222013-07-03 15:02:05 -07001317 struct address_space *mapping;
1318
Mel Gormane2be15f2013-07-03 15:01:57 -07001319 /*
1320 * Anonymous pages are not handled by flushers and must be written
1321 * from reclaim context. Do not stall reclaim based on them
1322 */
Huang Ying9de4f222020-04-06 20:04:41 -07001323 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001324 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001325 *dirty = false;
1326 *writeback = false;
1327 return;
1328 }
1329
1330 /* By default assume that the page flags are accurate */
1331 *dirty = PageDirty(page);
1332 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001333
1334 /* Verify dirty/writeback state if the filesystem supports it */
1335 if (!page_has_private(page))
1336 return;
1337
1338 mapping = page_mapping(page);
1339 if (mapping && mapping->a_ops->is_dirty_writeback)
1340 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001341}
1342
Dave Hansen26aa2d12021-09-02 14:59:16 -07001343static struct page *alloc_demote_page(struct page *page, unsigned long node)
1344{
1345 struct migration_target_control mtc = {
1346 /*
1347 * Allocate from 'node', or fail quickly and quietly.
1348 * When this happens, 'page' will likely just be discarded
1349 * instead of migrated.
1350 */
1351 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1352 __GFP_THISNODE | __GFP_NOWARN |
1353 __GFP_NOMEMALLOC | GFP_NOWAIT,
1354 .nid = node
1355 };
1356
1357 return alloc_migration_target(page, (unsigned long)&mtc);
1358}
1359
1360/*
1361 * Take pages on @demote_list and attempt to demote them to
1362 * another node. Pages which are not demoted are left on
1363 * @demote_pages.
1364 */
1365static unsigned int demote_page_list(struct list_head *demote_pages,
1366 struct pglist_data *pgdat)
1367{
1368 int target_nid = next_demotion_node(pgdat->node_id);
1369 unsigned int nr_succeeded;
1370 int err;
1371
1372 if (list_empty(demote_pages))
1373 return 0;
1374
1375 if (target_nid == NUMA_NO_NODE)
1376 return 0;
1377
1378 /* Demotion ignores all cpuset and mempolicy settings */
1379 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1380 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1381 &nr_succeeded);
1382
Yang Shi668e4142021-09-02 14:59:19 -07001383 if (current_is_kswapd())
1384 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1385 else
1386 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1387
Dave Hansen26aa2d12021-09-02 14:59:16 -07001388 return nr_succeeded;
1389}
1390
Nick Piggine2867812008-07-25 19:45:30 -07001391/*
Andrew Morton1742f192006-03-22 00:08:21 -08001392 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001394static unsigned int shrink_page_list(struct list_head *page_list,
1395 struct pglist_data *pgdat,
1396 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001397 struct reclaim_stat *stat,
1398 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001399{
1400 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001401 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001402 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001403 unsigned int nr_reclaimed = 0;
1404 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001405 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001406
Kirill Tkhai060f0052019-03-05 15:48:15 -08001407 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001408 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001409 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410
Dave Hansen26aa2d12021-09-02 14:59:16 -07001411retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412 while (!list_empty(page_list)) {
1413 struct address_space *mapping;
1414 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001415 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001416 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001417 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001418
1419 cond_resched();
1420
1421 page = lru_to_page(page_list);
1422 list_del(&page->lru);
1423
Nick Piggin529ae9a2008-08-02 12:01:03 +02001424 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001425 goto keep;
1426
Sasha Levin309381fea2014-01-23 15:52:54 -08001427 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001429 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001430
1431 /* Account the number of base pages even though THP */
1432 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001433
Hugh Dickins39b5f292012-10-08 16:33:18 -07001434 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001435 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001436
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001437 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001438 goto keep_locked;
1439
Yu Zhao0182f922022-09-18 02:00:04 -06001440 /* page_update_gen() tried to promote this page? */
1441 if (lru_gen_enabled() && !ignore_references &&
1442 page_mapped(page) && PageReferenced(page))
1443 goto keep_locked;
1444
Andy Whitcroftc661b072007-08-22 14:01:26 -07001445 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1446 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1447
Mel Gorman283aba92013-07-03 15:01:51 -07001448 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001449 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001450 * reclaim_congested which affects wait_iff_congested. kswapd
1451 * will stall and start writing pages if the tail of the LRU
1452 * is all dirty unqueued pages.
1453 */
1454 page_check_dirty_writeback(page, &dirty, &writeback);
1455 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001456 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001457
1458 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001459 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001460
Mel Gormand04e8ac2013-07-03 15:02:03 -07001461 /*
1462 * Treat this page as congested if the underlying BDI is or if
1463 * pages are cycling through the LRU so quickly that the
1464 * pages marked for immediate reclaim are making it to the
1465 * end of the LRU a second time.
1466 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001467 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001468 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001469 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001470 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001471 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001472
1473 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001474 * If a page at the tail of the LRU is under writeback, there
1475 * are three cases to consider.
1476 *
1477 * 1) If reclaim is encountering an excessive number of pages
1478 * under writeback and this page is both under writeback and
1479 * PageReclaim then it indicates that pages are being queued
1480 * for IO but are being recycled through the LRU before the
1481 * IO can complete. Waiting on the page itself risks an
1482 * indefinite stall if it is impossible to writeback the
1483 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001484 * note that the LRU is being scanned too quickly and the
1485 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001486 *
Tejun Heo97c93412015-05-22 18:23:36 -04001487 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001488 * not marked for immediate reclaim, or the caller does not
1489 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1490 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001491 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001492 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001493 * Require may_enter_fs because we would wait on fs, which
1494 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001495 * enter reclaim, and deadlock if it waits on a page for
1496 * which it is needed to do the write (loop masks off
1497 * __GFP_IO|__GFP_FS for this reason); but more thought
1498 * would probably show more reasons.
1499 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001500 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001501 * PageReclaim. memcg does not have any dirty pages
1502 * throttling so we could easily OOM just because too many
1503 * pages are in writeback and there is nothing else to
1504 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001505 *
1506 * In cases 1) and 2) we activate the pages to get them out of
1507 * the way while we continue scanning for clean pages on the
1508 * inactive list and refilling from the active list. The
1509 * observation here is that waiting for disk writes is more
1510 * expensive than potentially causing reloads down the line.
1511 * Since they're marked for immediate reclaim, they won't put
1512 * memory pressure on the cache working set any longer than it
1513 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001514 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001515 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001516 /* Case 1 above */
1517 if (current_is_kswapd() &&
1518 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001519 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001520 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001521 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001522
1523 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001524 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001525 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001526 /*
1527 * This is slightly racy - end_page_writeback()
1528 * might have just cleared PageReclaim, then
1529 * setting PageReclaim here end up interpreted
1530 * as PageReadahead - but that does not matter
1531 * enough to care. What we do want is for this
1532 * page to have PageReclaim set next time memcg
1533 * reclaim reaches the tests above, so it will
1534 * then wait_on_page_writeback() to avoid OOM;
1535 * and it's also appropriate in global reclaim.
1536 */
1537 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001538 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001539 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001540
1541 /* Case 3 above */
1542 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001543 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001544 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001545 /* then go back and try same page again */
1546 list_add_tail(&page->lru, page_list);
1547 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001548 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001549 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550
Minchan Kim8940b342019-09-25 16:49:11 -07001551 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001552 references = page_check_references(page, sc);
1553
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001554 switch (references) {
1555 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001557 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001558 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001559 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001560 case PAGEREF_RECLAIM:
1561 case PAGEREF_RECLAIM_CLEAN:
1562 ; /* try to reclaim the page below */
1563 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001564
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001566 * Before reclaiming the page, try to relocate
1567 * its contents to another node.
1568 */
1569 if (do_demote_pass &&
1570 (thp_migration_supported() || !PageTransHuge(page))) {
1571 list_add(&page->lru, &demote_pages);
1572 unlock_page(page);
1573 continue;
1574 }
1575
1576 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577 * Anonymous process memory has backing store?
1578 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001579 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001581 if (PageAnon(page) && PageSwapBacked(page)) {
1582 if (!PageSwapCache(page)) {
1583 if (!(sc->gfp_mask & __GFP_IO))
1584 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001585 if (page_maybe_dma_pinned(page))
1586 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001587 if (PageTransHuge(page)) {
1588 /* cannot split THP, skip it */
1589 if (!can_split_huge_page(page, NULL))
1590 goto activate_locked;
1591 /*
1592 * Split pages without a PMD map right
1593 * away. Chances are some or all of the
1594 * tail pages can be freed without IO.
1595 */
1596 if (!compound_mapcount(page) &&
1597 split_huge_page_to_list(page,
1598 page_list))
1599 goto activate_locked;
1600 }
1601 if (!add_to_swap(page)) {
1602 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001603 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001604 /* Fallback to swap normal pages */
1605 if (split_huge_page_to_list(page,
1606 page_list))
1607 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001608#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1609 count_vm_event(THP_SWPOUT_FALLBACK);
1610#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001611 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001612 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001613 }
Minchan Kim0f074652017-07-06 15:37:24 -07001614
Kirill Tkhai4b793062020-04-01 21:10:18 -07001615 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001616
1617 /* Adding to swap updated mapping */
1618 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001619 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001620 } else if (unlikely(PageTransHuge(page))) {
1621 /* Split file THP */
1622 if (split_huge_page_to_list(page, page_list))
1623 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001624 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625
1626 /*
Yang Shi98879b32019-07-11 20:59:30 -07001627 * THP may get split above, need minus tail pages and update
1628 * nr_pages to avoid accounting tail pages twice.
1629 *
1630 * The tail pages that are added into swap cache successfully
1631 * reach here.
1632 */
1633 if ((nr_pages > 1) && !PageTransHuge(page)) {
1634 sc->nr_scanned -= (nr_pages - 1);
1635 nr_pages = 1;
1636 }
1637
1638 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 * The page is mapped into the page tables of one or more
1640 * processes. Try to unmap it here.
1641 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001642 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001643 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001644 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001645
1646 if (unlikely(PageTransHuge(page)))
1647 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001648
Yang Shi1fb08ac2021-06-30 18:52:01 -07001649 try_to_unmap(page, flags);
1650 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001651 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001652 if (!was_swapbacked && PageSwapBacked(page))
1653 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001654 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001655 }
1656 }
1657
1658 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001659 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001660 * Only kswapd can writeback filesystem pages
1661 * to avoid risk of stack overflow. But avoid
1662 * injecting inefficient single-page IO into
1663 * flusher writeback as much as possible: only
1664 * write pages when we've encountered many
1665 * dirty pages, and when we've already scanned
1666 * the rest of the LRU for clean pages and see
1667 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001668 */
Huang Ying9de4f222020-04-06 20:04:41 -07001669 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001670 (!current_is_kswapd() || !PageReclaim(page) ||
1671 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001672 /*
1673 * Immediately reclaim when written back.
1674 * Similar in principal to deactivate_page()
1675 * except we already have the page isolated
1676 * and know it's dirty
1677 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001678 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001679 SetPageReclaim(page);
1680
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001681 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001682 }
1683
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001684 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001686 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001687 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001688 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001689 goto keep_locked;
1690
Mel Gormand950c942015-09-04 15:47:35 -07001691 /*
1692 * Page is dirty. Flush the TLB if a writable entry
1693 * potentially exists to avoid CPU writes after IO
1694 * starts and then write it out here.
1695 */
1696 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001697 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001698 case PAGE_KEEP:
1699 goto keep_locked;
1700 case PAGE_ACTIVATE:
1701 goto activate_locked;
1702 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001703 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001704
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001705 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001706 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001707 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001708 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001709
Linus Torvalds1da177e2005-04-16 15:20:36 -07001710 /*
1711 * A synchronous write - probably a ramdisk. Go
1712 * ahead and try to reclaim the page.
1713 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001714 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001715 goto keep;
1716 if (PageDirty(page) || PageWriteback(page))
1717 goto keep_locked;
1718 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001719 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001720 case PAGE_CLEAN:
1721 ; /* try to free the page below */
1722 }
1723 }
1724
1725 /*
1726 * If the page has buffers, try to free the buffer mappings
1727 * associated with this page. If we succeed we try to free
1728 * the page as well.
1729 *
1730 * We do this even if the page is PageDirty().
1731 * try_to_release_page() does not perform I/O, but it is
1732 * possible for a page to have PageDirty set, but it is actually
1733 * clean (all its buffers are clean). This happens if the
1734 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001735 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736 * try_to_release_page() will discover that cleanness and will
1737 * drop the buffers and mark the page clean - it can be freed.
1738 *
1739 * Rarely, pages can have buffers and no ->mapping. These are
1740 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001741 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001742 * and if that worked, and the page is no longer mapped into
1743 * process address space (page_count == 1) it can be freed.
1744 * Otherwise, leave the page on the LRU so it is swappable.
1745 */
David Howells266cf652009-04-03 16:42:36 +01001746 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001747 if (!try_to_release_page(page, sc->gfp_mask))
1748 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001749 if (!mapping && page_count(page) == 1) {
1750 unlock_page(page);
1751 if (put_page_testzero(page))
1752 goto free_it;
1753 else {
1754 /*
1755 * rare race with speculative reference.
1756 * the speculative reference will free
1757 * this page shortly, so we may
1758 * increment nr_reclaimed here (and
1759 * leave it off the LRU).
1760 */
1761 nr_reclaimed++;
1762 continue;
1763 }
1764 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001765 }
1766
Shaohua Li802a3a92017-05-03 14:52:32 -07001767 if (PageAnon(page) && !PageSwapBacked(page)) {
1768 /* follow __remove_mapping for reference */
1769 if (!page_ref_freeze(page, 1))
1770 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001771 /*
1772 * The page has only one reference left, which is
1773 * from the isolation. After the caller puts the
1774 * page back on lru and drops the reference, the
1775 * page will be freed anyway. It doesn't matter
1776 * which lru it goes. So we don't bother checking
1777 * PageDirty here.
1778 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001779 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001780 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001781 } else if (!mapping || !__remove_mapping(mapping, page, true,
1782 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001783 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001784
1785 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001786free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001787 /*
1788 * THP may get swapped out in a whole, need account
1789 * all base pages.
1790 */
1791 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001792
1793 /*
1794 * Is there need to periodically free_page_list? It would
1795 * appear not as the counts should be low
1796 */
Yang Shi7ae88532019-09-23 15:38:09 -07001797 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001798 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001799 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001800 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001801 continue;
1802
Yang Shi98879b32019-07-11 20:59:30 -07001803activate_locked_split:
1804 /*
1805 * The tail pages that are failed to add into swap cache
1806 * reach here. Fixup nr_scanned and nr_pages.
1807 */
1808 if (nr_pages > 1) {
1809 sc->nr_scanned -= (nr_pages - 1);
1810 nr_pages = 1;
1811 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001812activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001813 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001814 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1815 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001816 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001817 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001818 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001819 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001820 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001821 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001822 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001823 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001824keep_locked:
1825 unlock_page(page);
1826keep:
1827 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001828 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001829 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001830 /* 'page_list' is always empty here */
1831
1832 /* Migrate pages selected for demotion */
1833 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1834 /* Pages that could not be demoted are still in @demote_pages */
1835 if (!list_empty(&demote_pages)) {
1836 /* Pages which failed to demoted go back on @page_list for retry: */
1837 list_splice_init(&demote_pages, page_list);
1838 do_demote_pass = false;
1839 goto retry;
1840 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001841
Yang Shi98879b32019-07-11 20:59:30 -07001842 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1843
Johannes Weiner747db952014-08-08 14:19:24 -07001844 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001845 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001846 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001847
Linus Torvalds1da177e2005-04-16 15:20:36 -07001848 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001849 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001850
Andrew Morton05ff5132006-03-22 00:08:20 -08001851 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001852}
1853
Maninder Singh730ec8c2020-06-03 16:01:18 -07001854unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001855 struct list_head *page_list)
1856{
1857 struct scan_control sc = {
1858 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001859 .may_unmap = 1,
1860 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001861 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001862 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001863 struct page *page, *next;
1864 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001865 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001866
1867 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001868 if (!PageHuge(page) && page_is_file_lru(page) &&
1869 !PageDirty(page) && !__PageMovable(page) &&
1870 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001871 ClearPageActive(page);
1872 list_move(&page->lru, &clean_pages);
1873 }
1874 }
1875
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001876 /*
1877 * We should be safe here since we are only dealing with file pages and
1878 * we are not kswapd and therefore cannot write dirty file pages. But
1879 * call memalloc_noreclaim_save() anyway, just in case these conditions
1880 * change in the future.
1881 */
1882 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001883 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001884 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001885 memalloc_noreclaim_restore(noreclaim_flag);
1886
Minchan Kim02c6de82012-10-08 16:31:55 -07001887 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001888 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1889 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001890 /*
1891 * Since lazyfree pages are isolated from file LRU from the beginning,
1892 * they will rotate back to anonymous LRU in the end if it failed to
1893 * discard so isolated count will be mismatched.
1894 * Compensate the isolated count for both LRU lists.
1895 */
1896 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1897 stat.nr_lazyfree_fail);
1898 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001899 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001900 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001901}
1902
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001903/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001904 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001905 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001906 */
1907static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001908 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001909{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001910 int zid;
1911
Mel Gorman7ee36a12016-07-28 15:47:17 -07001912 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1913 if (!nr_zone_taken[zid])
1914 continue;
1915
Wei Yanga892cb62020-06-03 16:01:12 -07001916 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001917 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001918
Mel Gorman7ee36a12016-07-28 15:47:17 -07001919}
1920
Mel Gormanf611fab2021-06-30 18:53:19 -07001921/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001922 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1923 *
1924 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001925 * shrink the lists perform better by taking out a batch of pages
1926 * and working on them outside the LRU lock.
1927 *
1928 * For pagecache intensive workloads, this function is the hottest
1929 * spot in the kernel (apart from copy_*_user functions).
1930 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001931 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001932 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001933 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001934 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001935 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001936 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001937 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001938 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001939 *
1940 * returns how many pages were moved onto *@dst.
1941 */
Andrew Morton69e05942006-03-22 00:08:19 -08001942static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001943 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001944 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001945 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001946{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001947 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001948 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001949 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001950 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001951 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001952 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001953 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001954
Yang Shi98879b32019-07-11 20:59:30 -07001955 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001956 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001957 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001958 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001959 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001960
Linus Torvalds1da177e2005-04-16 15:20:36 -07001961 page = lru_to_page(src);
1962 prefetchw_prev_lru_page(page, src, flags);
1963
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001964 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001965 total_scan += nr_pages;
1966
Mel Gormanb2e18752016-07-28 15:45:37 -07001967 if (page_zonenum(page) > sc->reclaim_idx) {
Yang Shi98879b32019-07-11 20:59:30 -07001968 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001969 move_to = &pages_skipped;
1970 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07001971 }
1972
Minchan Kim791b48b2017-05-12 15:47:06 -07001973 /*
1974 * Do not count skipped pages because that makes the function
1975 * return with no isolated pages if the LRU mostly contains
1976 * ineligible pages. This causes the VM to not reclaim any
1977 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001978 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07001979 */
Yang Shi98879b32019-07-11 20:59:30 -07001980 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001981
1982 if (!PageLRU(page))
1983 goto move;
1984 if (!sc->may_unmap && page_mapped(page))
1985 goto move;
1986
Alex Shic2135f72021-02-24 12:08:01 -08001987 /*
1988 * Be careful not to clear PageLRU until after we're
1989 * sure the page is not being freed elsewhere -- the
1990 * page release code relies on it.
1991 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001992 if (unlikely(!get_page_unless_zero(page)))
1993 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08001994
1995 if (!TestClearPageLRU(page)) {
1996 /* Another thread is already isolating this page */
1997 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001998 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08001999 }
2000
2001 nr_taken += nr_pages;
2002 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002003 move_to = dst;
2004move:
2005 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006 }
2007
Mel Gormanb2e18752016-07-28 15:45:37 -07002008 /*
2009 * Splice any skipped pages to the start of the LRU list. Note that
2010 * this disrupts the LRU order when reclaiming for lower zones but
2011 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2012 * scanning would soon rescan the same pages to skip and put the
2013 * system at risk of premature OOM.
2014 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002015 if (!list_empty(&pages_skipped)) {
2016 int zid;
2017
Johannes Weiner3db65812017-05-03 14:52:13 -07002018 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002019 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2020 if (!nr_skipped[zid])
2021 continue;
2022
2023 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002024 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002025 }
2026 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002027 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002028 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002029 total_scan, skipped, nr_taken,
2030 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002031 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002032 return nr_taken;
2033}
2034
Nick Piggin62695a82008-10-18 20:26:09 -07002035/**
2036 * isolate_lru_page - tries to isolate a page from its LRU list
2037 * @page: page to isolate from its LRU list
2038 *
2039 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2040 * vmstat statistic corresponding to whatever LRU list the page was on.
2041 *
2042 * Returns 0 if the page was removed from an LRU list.
2043 * Returns -EBUSY if the page was not on an LRU list.
2044 *
2045 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002046 * the active list, it will have PageActive set. If it was found on
2047 * the unevictable list, it will have the PageUnevictable bit set. That flag
2048 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002049 *
2050 * The vmstat statistic corresponding to the list on which the page was
2051 * found will be decremented.
2052 *
2053 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002054 *
Nick Piggin62695a82008-10-18 20:26:09 -07002055 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002056 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002057 * without a stable reference).
2058 * (2) the lru_lock must not be held.
2059 * (3) interrupts must be enabled.
2060 */
2061int isolate_lru_page(struct page *page)
2062{
2063 int ret = -EBUSY;
2064
Sasha Levin309381fea2014-01-23 15:52:54 -08002065 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002066 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002067
Alex Shid25b5bd2020-12-15 12:34:16 -08002068 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002069 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002070
Alex Shid25b5bd2020-12-15 12:34:16 -08002071 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002072 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002073 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002074 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002075 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002076 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002077
Nick Piggin62695a82008-10-18 20:26:09 -07002078 return ret;
2079}
2080
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002081/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002082 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002083 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002084 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2085 * the LRU list will go small and be scanned faster than necessary, leading to
2086 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002087 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002088static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002089 struct scan_control *sc)
2090{
2091 unsigned long inactive, isolated;
2092
2093 if (current_is_kswapd())
2094 return 0;
2095
Johannes Weinerb5ead352019-11-30 17:55:40 -08002096 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002097 return 0;
2098
2099 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002100 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2101 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002102 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002103 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2104 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002105 }
2106
Fengguang Wu3cf23842012-12-18 14:23:31 -08002107 /*
2108 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2109 * won't get blocked by normal direct-reclaimers, forming a circular
2110 * deadlock.
2111 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002112 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002113 inactive >>= 3;
2114
Rik van Riel35cd7812009-09-21 17:01:38 -07002115 return isolated > inactive;
2116}
2117
Kirill Tkhaia222f342019-05-13 17:17:00 -07002118/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002119 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2120 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002121 *
2122 * Returns the number of pages moved to the given lruvec.
2123 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002124static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2125 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002126{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002127 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002128 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002129 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002130
Kirill Tkhaia222f342019-05-13 17:17:00 -07002131 while (!list_empty(list)) {
2132 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002133 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002134 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002135 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002136 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002137 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002138 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002139 continue;
2140 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002141
Alex Shi3d06afa2020-12-15 12:33:37 -08002142 /*
2143 * The SetPageLRU needs to be kept here for list integrity.
2144 * Otherwise:
2145 * #0 move_pages_to_lru #1 release_pages
2146 * if !put_page_testzero
2147 * if (put_page_testzero())
2148 * !PageLRU //skip lru_lock
2149 * SetPageLRU()
2150 * list_add(&page->lru,)
2151 * list_add(&page->lru,)
2152 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002153 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002154
Alex Shi3d06afa2020-12-15 12:33:37 -08002155 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002156 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002157
2158 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002159 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002160 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002161 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002162 } else
2163 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002164
2165 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002166 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002167
Alex Shiafca9152020-12-15 12:34:02 -08002168 /*
2169 * All pages were isolated from the same lruvec (and isolation
2170 * inhibits memcg migration).
2171 */
Muchun Song7467c392021-06-28 19:37:59 -07002172 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002173 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002174 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002175 nr_moved += nr_pages;
2176 if (PageActive(page))
2177 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002178 }
Mel Gorman66635622010-08-09 17:19:30 -07002179
Hugh Dickins3f797682012-01-12 17:20:07 -08002180 /*
2181 * To save our caller's stack, now use input list for pages to free.
2182 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002183 list_splice(&pages_to_free, list);
2184
2185 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002186}
2187
2188/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002189 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002190 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002191 * In that case we should only throttle if the backing device it is
2192 * writing to is congested. In other cases it is safe to throttle.
2193 */
2194static int current_may_throttle(void)
2195{
NeilBrowna37b0712020-06-01 21:48:18 -07002196 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002197 current->backing_dev_info == NULL ||
2198 bdi_write_congested(current->backing_dev_info);
2199}
2200
2201/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002202 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002203 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002204 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002205static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002206shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002207 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002208{
2209 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002210 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002211 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002212 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002213 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002214 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002215 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002216 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002217 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002218
Mel Gorman599d0c92016-07-28 15:45:31 -07002219 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002220 if (stalled)
2221 return 0;
2222
2223 /* wait a bit for the reclaimer. */
2224 msleep(100);
2225 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002226
2227 /* We are about to die and free our memory. Return now. */
2228 if (fatal_signal_pending(current))
2229 return SWAP_CLUSTER_MAX;
2230 }
2231
Linus Torvalds1da177e2005-04-16 15:20:36 -07002232 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002233
Alex Shi6168d0d2020-12-15 12:34:29 -08002234 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002235
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002236 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002237 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002238
Mel Gorman599d0c92016-07-28 15:45:31 -07002239 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002240 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002241 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002242 __count_vm_events(item, nr_scanned);
2243 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002244 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2245
Alex Shi6168d0d2020-12-15 12:34:29 -08002246 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002247
Hillf Dantond563c052012-03-21 16:34:02 -07002248 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002249 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002250
Shakeel Butt013339d2020-12-14 19:06:39 -08002251 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002252
Alex Shi6168d0d2020-12-15 12:34:29 -08002253 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002254 move_pages_to_lru(lruvec, &page_list);
2255
2256 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002257 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002258 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002259 __count_vm_events(item, nr_reclaimed);
2260 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002261 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002262 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002263
Alex Shi75cc3c92020-12-15 14:20:50 -08002264 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002265 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002266 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002267
Mel Gorman92df3a72011-10-31 17:07:56 -07002268 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002269 * If dirty pages are scanned that are not queued for IO, it
2270 * implies that flushers are not doing their job. This can
2271 * happen when memory pressure pushes dirty pages to the end of
2272 * the LRU before the dirty limits are breached and the dirty
2273 * data has expired. It can also happen when the proportion of
2274 * dirty pages grows not through writes but through memory
2275 * pressure reclaiming all the clean cache. And in some cases,
2276 * the flushers simply cannot keep up with the allocation
2277 * rate. Nudge the flusher threads in case they are asleep.
2278 */
2279 if (stat.nr_unqueued_dirty == nr_taken)
2280 wakeup_flusher_threads(WB_REASON_VMSCAN);
2281
Andrey Ryabinind108c772018-04-10 16:27:59 -07002282 sc->nr.dirty += stat.nr_dirty;
2283 sc->nr.congested += stat.nr_congested;
2284 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2285 sc->nr.writeback += stat.nr_writeback;
2286 sc->nr.immediate += stat.nr_immediate;
2287 sc->nr.taken += nr_taken;
2288 if (file)
2289 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002290
Mel Gorman599d0c92016-07-28 15:45:31 -07002291 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002292 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002293 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002294}
2295
Hugh Dickins15b44732020-12-15 14:21:31 -08002296/*
2297 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2298 *
2299 * We move them the other way if the page is referenced by one or more
2300 * processes.
2301 *
2302 * If the pages are mostly unmapped, the processing is fast and it is
2303 * appropriate to hold lru_lock across the whole operation. But if
2304 * the pages are mapped, the processing is slow (page_referenced()), so
2305 * we should drop lru_lock around each page. It's impossible to balance
2306 * this, so instead we remove the pages from the LRU while processing them.
2307 * It is safe to rely on PG_active against the non-LRU pages in here because
2308 * nobody will play with that bit on a non-LRU page.
2309 *
2310 * The downside is that we have to touch page->_refcount against each page.
2311 * But we had to alter page->flags anyway.
2312 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002313static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002314 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002315 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002316 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002317{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002318 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002319 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002320 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002321 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002322 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002323 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002324 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002325 unsigned nr_deactivate, nr_activate;
2326 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002327 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002328 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002329 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002330
2331 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002332
Alex Shi6168d0d2020-12-15 12:34:29 -08002333 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002334
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002335 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002336 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002337
Mel Gorman599d0c92016-07-28 15:45:31 -07002338 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002339
Shakeel Butt912c0572020-08-06 23:26:32 -07002340 if (!cgroup_reclaim(sc))
2341 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002342 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002343
Alex Shi6168d0d2020-12-15 12:34:29 -08002344 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002345
Linus Torvalds1da177e2005-04-16 15:20:36 -07002346 while (!list_empty(&l_hold)) {
2347 cond_resched();
2348 page = lru_to_page(&l_hold);
2349 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002350
Hugh Dickins39b5f292012-10-08 16:33:18 -07002351 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002352 putback_lru_page(page);
2353 continue;
2354 }
2355
Mel Gormancc715d92012-03-21 16:34:00 -07002356 if (unlikely(buffer_heads_over_limit)) {
2357 if (page_has_private(page) && trylock_page(page)) {
2358 if (page_has_private(page))
2359 try_to_release_page(page, 0);
2360 unlock_page(page);
2361 }
2362 }
2363
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002364 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2365 if (bypass)
2366 goto skip_page_referenced;
2367
Minchan Kimf74aca72022-05-19 14:08:54 -07002368 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002369 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002370 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002371 /*
2372 * Identify referenced, file-backed active pages and
2373 * give them one more trip around the active list. So
2374 * that executable code get better chances to stay in
2375 * memory under moderate memory pressure. Anon pages
2376 * are not likely to be evicted by use-once streaming
2377 * IO, plus JVM can create lots of anon VM_EXEC pages,
2378 * so we ignore them here.
2379 */
Huang Ying9de4f222020-04-06 20:04:41 -07002380 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002381 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002382 list_add(&page->lru, &l_active);
2383 continue;
2384 }
2385 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002386skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002387 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002388 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002389 list_add(&page->lru, &l_inactive);
2390 }
2391
Andrew Mortonb5557492009-01-06 14:40:13 -08002392 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002393 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002394 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002395 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002396
Kirill Tkhaia222f342019-05-13 17:17:00 -07002397 nr_activate = move_pages_to_lru(lruvec, &l_active);
2398 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002399 /* Keep all free pages in l_active list */
2400 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002401
2402 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2403 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2404
Mel Gorman599d0c92016-07-28 15:45:31 -07002405 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002406 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002407
Kirill Tkhaif372d892019-05-13 17:16:57 -07002408 mem_cgroup_uncharge_list(&l_active);
2409 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002410 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2411 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002412}
2413
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002414unsigned long reclaim_pages(struct list_head *page_list)
2415{
Yang Shif661d002020-04-01 21:10:05 -07002416 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002417 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002418 LIST_HEAD(node_page_list);
2419 struct reclaim_stat dummy_stat;
2420 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002421 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002422 struct scan_control sc = {
2423 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002424 .may_writepage = 1,
2425 .may_unmap = 1,
2426 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002427 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002428 };
2429
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002430 noreclaim_flag = memalloc_noreclaim_save();
2431
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002432 while (!list_empty(page_list)) {
2433 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002434 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002435 nid = page_to_nid(page);
2436 INIT_LIST_HEAD(&node_page_list);
2437 }
2438
2439 if (nid == page_to_nid(page)) {
2440 ClearPageActive(page);
2441 list_move(&page->lru, &node_page_list);
2442 continue;
2443 }
2444
2445 nr_reclaimed += shrink_page_list(&node_page_list,
2446 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002447 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002448 while (!list_empty(&node_page_list)) {
2449 page = lru_to_page(&node_page_list);
2450 list_del(&page->lru);
2451 putback_lru_page(page);
2452 }
2453
Yang Shif661d002020-04-01 21:10:05 -07002454 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002455 }
2456
2457 if (!list_empty(&node_page_list)) {
2458 nr_reclaimed += shrink_page_list(&node_page_list,
2459 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002460 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002461 while (!list_empty(&node_page_list)) {
2462 page = lru_to_page(&node_page_list);
2463 list_del(&page->lru);
2464 putback_lru_page(page);
2465 }
2466 }
2467
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002468 memalloc_noreclaim_restore(noreclaim_flag);
2469
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002470 return nr_reclaimed;
2471}
2472
Johannes Weinerb91ac372019-11-30 17:56:02 -08002473static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2474 struct lruvec *lruvec, struct scan_control *sc)
2475{
2476 if (is_active_lru(lru)) {
2477 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2478 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2479 else
2480 sc->skipped_deactivate = 1;
2481 return 0;
2482 }
2483
2484 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2485}
2486
Rik van Riel59dc76b2016-05-20 16:56:31 -07002487/*
2488 * The inactive anon list should be small enough that the VM never has
2489 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002490 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002491 * The inactive file list should be small enough to leave most memory
2492 * to the established workingset on the scan-resistant active list,
2493 * but large enough to avoid thrashing the aggregate readahead window.
2494 *
2495 * Both inactive lists should also be large enough that each inactive
2496 * page has a chance to be referenced again before it is reclaimed.
2497 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002498 * If that fails and refaulting is observed, the inactive list grows.
2499 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002500 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002501 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002502 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2503 *
2504 * total target max
2505 * memory ratio inactive
2506 * -------------------------------------
2507 * 10MB 1 5MB
2508 * 100MB 1 50MB
2509 * 1GB 3 250MB
2510 * 10GB 10 0.9GB
2511 * 100GB 31 3GB
2512 * 1TB 101 10GB
2513 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002514 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002515static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002516{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002517 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002518 unsigned long inactive, active;
2519 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002520 unsigned long gb;
2521
Johannes Weinerb91ac372019-11-30 17:56:02 -08002522 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2523 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002524
Johannes Weinerb91ac372019-11-30 17:56:02 -08002525 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002526 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002527 inactive_ratio = int_sqrt(10 * gb);
2528 else
2529 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002530
Rik van Riel59dc76b2016-05-20 16:56:31 -07002531 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002532}
2533
Johannes Weiner9a265112013-02-22 16:32:17 -08002534enum scan_balance {
2535 SCAN_EQUAL,
2536 SCAN_FRACT,
2537 SCAN_ANON,
2538 SCAN_FILE,
2539};
2540
Yu Zhao6d313442022-09-18 02:00:00 -06002541static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2542{
2543 unsigned long file;
2544 struct lruvec *target_lruvec;
2545
Yu Zhao37397872022-09-18 02:00:03 -06002546 if (lru_gen_enabled())
2547 return;
2548
Yu Zhao6d313442022-09-18 02:00:00 -06002549 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2550
2551 /*
2552 * Flush the memory cgroup stats, so that we read accurate per-memcg
2553 * lruvec stats for heuristics.
2554 */
2555 mem_cgroup_flush_stats();
2556
2557 /*
2558 * Determine the scan balance between anon and file LRUs.
2559 */
2560 spin_lock_irq(&target_lruvec->lru_lock);
2561 sc->anon_cost = target_lruvec->anon_cost;
2562 sc->file_cost = target_lruvec->file_cost;
2563 spin_unlock_irq(&target_lruvec->lru_lock);
2564
2565 /*
2566 * Target desirable inactive:active list ratios for the anon
2567 * and file LRU lists.
2568 */
2569 if (!sc->force_deactivate) {
2570 unsigned long refaults;
2571
2572 refaults = lruvec_page_state(target_lruvec,
2573 WORKINGSET_ACTIVATE_ANON);
2574 if (refaults != target_lruvec->refaults[0] ||
2575 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2576 sc->may_deactivate |= DEACTIVATE_ANON;
2577 else
2578 sc->may_deactivate &= ~DEACTIVATE_ANON;
2579
2580 /*
2581 * When refaults are being observed, it means a new
2582 * workingset is being established. Deactivate to get
2583 * rid of any stale active pages quickly.
2584 */
2585 refaults = lruvec_page_state(target_lruvec,
2586 WORKINGSET_ACTIVATE_FILE);
2587 if (refaults != target_lruvec->refaults[1] ||
2588 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2589 sc->may_deactivate |= DEACTIVATE_FILE;
2590 else
2591 sc->may_deactivate &= ~DEACTIVATE_FILE;
2592 } else
2593 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2594
2595 /*
2596 * If we have plenty of inactive file pages that aren't
2597 * thrashing, try to reclaim those first before touching
2598 * anonymous pages.
2599 */
2600 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2601 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2602 sc->cache_trim_mode = 1;
2603 else
2604 sc->cache_trim_mode = 0;
2605
2606 /*
2607 * Prevent the reclaimer from falling into the cache trap: as
2608 * cache pages start out inactive, every cache fault will tip
2609 * the scan balance towards the file LRU. And as the file LRU
2610 * shrinks, so does the window for rotation from references.
2611 * This means we have a runaway feedback loop where a tiny
2612 * thrashing file LRU becomes infinitely more attractive than
2613 * anon pages. Try to detect this based on file LRU size.
2614 */
2615 if (!cgroup_reclaim(sc)) {
2616 unsigned long total_high_wmark = 0;
2617 unsigned long free, anon;
2618 int z;
2619
2620 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2621 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2622 node_page_state(pgdat, NR_INACTIVE_FILE);
2623
2624 for (z = 0; z < MAX_NR_ZONES; z++) {
2625 struct zone *zone = &pgdat->node_zones[z];
2626
2627 if (!managed_zone(zone))
2628 continue;
2629
2630 total_high_wmark += high_wmark_pages(zone);
2631 }
2632
2633 /*
2634 * Consider anon: if that's low too, this isn't a
2635 * runaway file reclaim problem, but rather just
2636 * extreme pressure. Reclaim as per usual then.
2637 */
2638 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2639
2640 sc->file_is_tiny =
2641 file + free <= total_high_wmark &&
2642 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2643 anon >> sc->priority;
2644 }
2645}
2646
Linus Torvalds1da177e2005-04-16 15:20:36 -07002647/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002648 * Determine how aggressively the anon and file LRU lists should be
2649 * scanned. The relative value of each set of LRU lists is determined
2650 * by looking at the fraction of the pages scanned we did rotate back
2651 * onto the active list instead of evict.
2652 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002653 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2654 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002655 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002656static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2657 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002658{
Keith Buscha2a36482021-09-02 14:59:26 -07002659 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002660 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002661 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002662 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002663 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002664 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002665 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002666 unsigned long ap, fp;
2667 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002668 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002669
2670 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002671 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002672 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002673 goto out;
2674 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002675
Johannes Weiner10316b32013-02-22 16:32:14 -08002676 /*
2677 * Global reclaim will swap to prevent OOM even with no
2678 * swappiness, but memcg users want to use this knob to
2679 * disable swapping for individual groups completely when
2680 * using the memory controller's swap limit feature would be
2681 * too expensive.
2682 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002683 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002684 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002685 goto out;
2686 }
2687
2688 /*
2689 * Do not apply any pressure balancing cleverness when the
2690 * system is close to OOM, scan both anon and file equally
2691 * (unless the swappiness setting disagrees with swapping).
2692 */
Johannes Weiner02695172014-08-06 16:06:17 -07002693 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002694 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002695 goto out;
2696 }
2697
Johannes Weiner11d16c22013-02-22 16:32:15 -08002698 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002699 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002700 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002701 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002702 scan_balance = SCAN_ANON;
2703 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002704 }
2705
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002706 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2707
Johannes Weiner62376252014-05-06 12:50:07 -07002708 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002709 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002710 * anything from the anonymous working right now. But when balancing
2711 * anon and page cache files for reclaim, allow swapping of anon pages
2712 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002713 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002714 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002715 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002716 goto out;
2717 }
2718
Johannes Weiner9a265112013-02-22 16:32:17 -08002719 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002720 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002721 * Calculate the pressure balance between anon and file pages.
2722 *
2723 * The amount of pressure we put on each LRU is inversely
2724 * proportional to the cost of reclaiming each list, as
2725 * determined by the share of pages that are refaulting, times
2726 * the relative IO cost of bringing back a swapped out
2727 * anonymous page vs reloading a filesystem page (swappiness).
2728 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002729 * Although we limit that influence to ensure no list gets
2730 * left behind completely: at least a third of the pressure is
2731 * applied, before swappiness.
2732 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002733 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002734 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002735 total_cost = sc->anon_cost + sc->file_cost;
2736 anon_cost = total_cost + sc->anon_cost;
2737 file_cost = total_cost + sc->file_cost;
2738 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002739
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002740 ap = swappiness * (total_cost + 1);
2741 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002742
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002743 fp = (200 - swappiness) * (total_cost + 1);
2744 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002745
Shaohua Li76a33fc2010-05-24 14:32:36 -07002746 fraction[0] = ap;
2747 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002748 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002749out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002750 for_each_evictable_lru(lru) {
2751 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002752 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002753 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002754 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002755
Chris Down9783aa92019-10-06 17:58:32 -07002756 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002757 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2758 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002759
Johannes Weinerf56ce412021-08-19 19:04:21 -07002760 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002761 /*
2762 * Scale a cgroup's reclaim pressure by proportioning
2763 * its current usage to its memory.low or memory.min
2764 * setting.
2765 *
2766 * This is important, as otherwise scanning aggression
2767 * becomes extremely binary -- from nothing as we
2768 * approach the memory protection threshold, to totally
2769 * nominal as we exceed it. This results in requiring
2770 * setting extremely liberal protection thresholds. It
2771 * also means we simply get no protection at all if we
2772 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002773 *
2774 * If there is any protection in place, we reduce scan
2775 * pressure by how much of the total memory used is
2776 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002777 *
Chris Down9de7ca42019-10-06 17:58:35 -07002778 * There is one special case: in the first reclaim pass,
2779 * we skip over all groups that are within their low
2780 * protection. If that fails to reclaim enough pages to
2781 * satisfy the reclaim goal, we come back and override
2782 * the best-effort low protection. However, we still
2783 * ideally want to honor how well-behaved groups are in
2784 * that case instead of simply punishing them all
2785 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002786 * memory they are using, reducing the scan pressure
2787 * again by how much of the total memory used is under
2788 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002789 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002790 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002791 unsigned long protection;
2792
2793 /* memory.low scaling, make sure we retry before OOM */
2794 if (!sc->memcg_low_reclaim && low > min) {
2795 protection = low;
2796 sc->memcg_low_skipped = 1;
2797 } else {
2798 protection = min;
2799 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002800
2801 /* Avoid TOCTOU with earlier protection check */
2802 cgroup_size = max(cgroup_size, protection);
2803
2804 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002805 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002806
2807 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002808 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002809 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002810 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002811 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002812 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002813 } else {
2814 scan = lruvec_size;
2815 }
2816
2817 scan >>= sc->priority;
2818
Johannes Weiner688035f2017-05-03 14:52:07 -07002819 /*
2820 * If the cgroup's already been deleted, make sure to
2821 * scrape out the remaining cache.
2822 */
2823 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002824 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002825
Johannes Weiner688035f2017-05-03 14:52:07 -07002826 switch (scan_balance) {
2827 case SCAN_EQUAL:
2828 /* Scan lists relative to size */
2829 break;
2830 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002831 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002832 * Scan types proportional to swappiness and
2833 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002834 * Make sure we don't miss the last page on
2835 * the offlined memory cgroups because of a
2836 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002837 */
Gavin Shan76073c62020-02-20 20:04:24 -08002838 scan = mem_cgroup_online(memcg) ?
2839 div64_u64(scan * fraction[file], denominator) :
2840 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002841 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002842 break;
2843 case SCAN_FILE:
2844 case SCAN_ANON:
2845 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002846 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002847 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002848 break;
2849 default:
2850 /* Look ma, no brain */
2851 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002852 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002853
Johannes Weiner688035f2017-05-03 14:52:07 -07002854 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002855 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002856}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002857
Dave Hansen2f368a92021-09-02 14:59:23 -07002858/*
2859 * Anonymous LRU management is a waste if there is
2860 * ultimately no way to reclaim the memory.
2861 */
2862static bool can_age_anon_pages(struct pglist_data *pgdat,
2863 struct scan_control *sc)
2864{
2865 /* Aging the anon LRU is valuable if swap is present: */
2866 if (total_swap_pages > 0)
2867 return true;
2868
2869 /* Also valuable if anon pages can be demoted: */
2870 return can_demote(pgdat->node_id, sc);
2871}
2872
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002873#ifdef CONFIG_LRU_GEN
2874
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002875#ifdef CONFIG_LRU_GEN_ENABLED
2876DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2877#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2878#else
2879DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2880#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2881#endif
2882
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002883/******************************************************************************
2884 * shorthand helpers
2885 ******************************************************************************/
2886
Yu Zhao37397872022-09-18 02:00:03 -06002887#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2888
2889#define DEFINE_MAX_SEQ(lruvec) \
2890 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2891
2892#define DEFINE_MIN_SEQ(lruvec) \
2893 unsigned long min_seq[ANON_AND_FILE] = { \
2894 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2895 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2896 }
2897
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002898#define for_each_gen_type_zone(gen, type, zone) \
2899 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2900 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2901 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2902
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002903static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002904{
2905 struct pglist_data *pgdat = NODE_DATA(nid);
2906
2907#ifdef CONFIG_MEMCG
2908 if (memcg) {
2909 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2910
2911 /* for hotadd_new_pgdat() */
2912 if (!lruvec->pgdat)
2913 lruvec->pgdat = pgdat;
2914
2915 return lruvec;
2916 }
2917#endif
2918 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2919
2920 return pgdat ? &pgdat->__lruvec : NULL;
2921}
2922
Yu Zhao37397872022-09-18 02:00:03 -06002923static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2924{
2925 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2926 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2927
2928 if (!can_demote(pgdat->node_id, sc) &&
2929 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2930 return 0;
2931
2932 return mem_cgroup_swappiness(memcg);
2933}
2934
2935static int get_nr_gens(struct lruvec *lruvec, int type)
2936{
2937 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2938}
2939
2940static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2941{
2942 /* see the comment on lru_gen_struct */
2943 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2944 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2945 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2946}
2947
2948/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002949 * mm_struct list
2950 ******************************************************************************/
2951
2952static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2953{
2954 static struct lru_gen_mm_list mm_list = {
2955 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2956 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2957 };
2958
2959#ifdef CONFIG_MEMCG
2960 if (memcg)
2961 return &memcg->mm_list;
2962#endif
2963 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2964
2965 return &mm_list;
2966}
2967
2968void lru_gen_add_mm(struct mm_struct *mm)
2969{
2970 int nid;
2971 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2972 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2973
2974 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2975#ifdef CONFIG_MEMCG
2976 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2977 mm->lru_gen.memcg = memcg;
2978#endif
2979 spin_lock(&mm_list->lock);
2980
2981 for_each_node_state(nid, N_MEMORY) {
2982 struct lruvec *lruvec = get_lruvec(memcg, nid);
2983
2984 if (!lruvec)
2985 continue;
2986
2987 /* the first addition since the last iteration */
2988 if (lruvec->mm_state.tail == &mm_list->fifo)
2989 lruvec->mm_state.tail = &mm->lru_gen.list;
2990 }
2991
2992 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2993
2994 spin_unlock(&mm_list->lock);
2995}
2996
2997void lru_gen_del_mm(struct mm_struct *mm)
2998{
2999 int nid;
3000 struct lru_gen_mm_list *mm_list;
3001 struct mem_cgroup *memcg = NULL;
3002
3003 if (list_empty(&mm->lru_gen.list))
3004 return;
3005
3006#ifdef CONFIG_MEMCG
3007 memcg = mm->lru_gen.memcg;
3008#endif
3009 mm_list = get_mm_list(memcg);
3010
3011 spin_lock(&mm_list->lock);
3012
3013 for_each_node(nid) {
3014 struct lruvec *lruvec = get_lruvec(memcg, nid);
3015
3016 if (!lruvec)
3017 continue;
3018
3019 /* where the last iteration ended (exclusive) */
3020 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3021 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3022
3023 /* where the current iteration continues (inclusive) */
3024 if (lruvec->mm_state.head != &mm->lru_gen.list)
3025 continue;
3026
3027 lruvec->mm_state.head = lruvec->mm_state.head->next;
3028 /* the deletion ends the current iteration */
3029 if (lruvec->mm_state.head == &mm_list->fifo)
3030 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3031 }
3032
3033 list_del_init(&mm->lru_gen.list);
3034
3035 spin_unlock(&mm_list->lock);
3036
3037#ifdef CONFIG_MEMCG
3038 mem_cgroup_put(mm->lru_gen.memcg);
3039 mm->lru_gen.memcg = NULL;
3040#endif
3041}
3042
3043#ifdef CONFIG_MEMCG
3044void lru_gen_migrate_mm(struct mm_struct *mm)
3045{
3046 struct mem_cgroup *memcg;
3047 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3048
3049 VM_WARN_ON_ONCE(task->mm != mm);
3050 lockdep_assert_held(&task->alloc_lock);
3051
3052 /* for mm_update_next_owner() */
3053 if (mem_cgroup_disabled())
3054 return;
3055
3056 rcu_read_lock();
3057 memcg = mem_cgroup_from_task(task);
3058 rcu_read_unlock();
3059 if (memcg == mm->lru_gen.memcg)
3060 return;
3061
3062 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3063 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3064
3065 lru_gen_del_mm(mm);
3066 lru_gen_add_mm(mm);
3067}
3068#endif
3069
3070/*
3071 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3072 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3073 * bits in a bitmap, k is the number of hash functions and n is the number of
3074 * inserted items.
3075 *
3076 * Page table walkers use one of the two filters to reduce their search space.
3077 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3078 * aging uses the double-buffering technique to flip to the other filter each
3079 * time it produces a new generation. For non-leaf entries that have enough
3080 * leaf entries, the aging carries them over to the next generation in
3081 * walk_pmd_range(); the eviction also report them when walking the rmap
3082 * in lru_gen_look_around().
3083 *
3084 * For future optimizations:
3085 * 1. It's not necessary to keep both filters all the time. The spare one can be
3086 * freed after the RCU grace period and reallocated if needed again.
3087 * 2. And when reallocating, it's worth scaling its size according to the number
3088 * of inserted entries in the other filter, to reduce the memory overhead on
3089 * small systems and false positives on large systems.
3090 * 3. Jenkins' hash function is an alternative to Knuth's.
3091 */
3092#define BLOOM_FILTER_SHIFT 15
3093
3094static inline int filter_gen_from_seq(unsigned long seq)
3095{
3096 return seq % NR_BLOOM_FILTERS;
3097}
3098
3099static void get_item_key(void *item, int *key)
3100{
3101 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3102
3103 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3104
3105 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3106 key[1] = hash >> BLOOM_FILTER_SHIFT;
3107}
3108
3109static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3110{
3111 unsigned long *filter;
3112 int gen = filter_gen_from_seq(seq);
3113
3114 filter = lruvec->mm_state.filters[gen];
3115 if (filter) {
3116 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3117 return;
3118 }
3119
3120 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3121 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3122 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3123}
3124
3125static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3126{
3127 int key[2];
3128 unsigned long *filter;
3129 int gen = filter_gen_from_seq(seq);
3130
3131 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3132 if (!filter)
3133 return;
3134
3135 get_item_key(item, key);
3136
3137 if (!test_bit(key[0], filter))
3138 set_bit(key[0], filter);
3139 if (!test_bit(key[1], filter))
3140 set_bit(key[1], filter);
3141}
3142
3143static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3144{
3145 int key[2];
3146 unsigned long *filter;
3147 int gen = filter_gen_from_seq(seq);
3148
3149 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3150 if (!filter)
3151 return true;
3152
3153 get_item_key(item, key);
3154
3155 return test_bit(key[0], filter) && test_bit(key[1], filter);
3156}
3157
3158static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3159{
3160 int i;
3161 int hist;
3162
3163 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3164
3165 if (walk) {
3166 hist = lru_hist_from_seq(walk->max_seq);
3167
3168 for (i = 0; i < NR_MM_STATS; i++) {
3169 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3170 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3171 walk->mm_stats[i] = 0;
3172 }
3173 }
3174
3175 if (NR_HIST_GENS > 1 && last) {
3176 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3177
3178 for (i = 0; i < NR_MM_STATS; i++)
3179 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3180 }
3181}
3182
3183static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3184{
3185 int type;
3186 unsigned long size = 0;
3187 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3188 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3189
3190 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3191 return true;
3192
3193 clear_bit(key, &mm->lru_gen.bitmap);
3194
3195 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3196 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3197 get_mm_counter(mm, MM_ANONPAGES) +
3198 get_mm_counter(mm, MM_SHMEMPAGES);
3199 }
3200
3201 if (size < MIN_LRU_BATCH)
3202 return true;
3203
3204 return !mmget_not_zero(mm);
3205}
3206
3207static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3208 struct mm_struct **iter)
3209{
3210 bool first = false;
3211 bool last = true;
3212 struct mm_struct *mm = NULL;
3213 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3214 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3215 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3216
3217 /*
3218 * There are four interesting cases for this page table walker:
3219 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3220 * there is nothing left to do.
3221 * 2. It's the first of the current generation, and it needs to reset
3222 * the Bloom filter for the next generation.
3223 * 3. It reaches the end of mm_list, and it needs to increment
3224 * mm_state->seq; the iteration is done.
3225 * 4. It's the last of the current generation, and it needs to reset the
3226 * mm stats counters for the next generation.
3227 */
3228 spin_lock(&mm_list->lock);
3229
3230 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3231 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3232 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3233
3234 if (walk->max_seq <= mm_state->seq) {
3235 if (!*iter)
3236 last = false;
3237 goto done;
3238 }
3239
3240 if (!mm_state->nr_walkers) {
3241 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3242
3243 mm_state->head = mm_list->fifo.next;
3244 first = true;
3245 }
3246
3247 while (!mm && mm_state->head != &mm_list->fifo) {
3248 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3249
3250 mm_state->head = mm_state->head->next;
3251
3252 /* force scan for those added after the last iteration */
3253 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3254 mm_state->tail = mm_state->head;
3255 walk->force_scan = true;
3256 }
3257
3258 if (should_skip_mm(mm, walk))
3259 mm = NULL;
3260 }
3261
3262 if (mm_state->head == &mm_list->fifo)
3263 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3264done:
3265 if (*iter && !mm)
3266 mm_state->nr_walkers--;
3267 if (!*iter && mm)
3268 mm_state->nr_walkers++;
3269
3270 if (mm_state->nr_walkers)
3271 last = false;
3272
3273 if (*iter || last)
3274 reset_mm_stats(lruvec, walk, last);
3275
3276 spin_unlock(&mm_list->lock);
3277
3278 if (mm && first)
3279 reset_bloom_filter(lruvec, walk->max_seq + 1);
3280
3281 if (*iter)
3282 mmput_async(*iter);
3283
3284 *iter = mm;
3285
3286 return last;
3287}
3288
3289static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3290{
3291 bool success = false;
3292 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3293 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3294 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3295
3296 spin_lock(&mm_list->lock);
3297
3298 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3299
3300 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3301 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3302
3303 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3304 reset_mm_stats(lruvec, NULL, true);
3305 success = true;
3306 }
3307
3308 spin_unlock(&mm_list->lock);
3309
3310 return success;
3311}
3312
3313/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003314 * refault feedback loop
3315 ******************************************************************************/
3316
3317/*
3318 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3319 *
3320 * The P term is refaulted/(evicted+protected) from a tier in the generation
3321 * currently being evicted; the I term is the exponential moving average of the
3322 * P term over the generations previously evicted, using the smoothing factor
3323 * 1/2; the D term isn't supported.
3324 *
3325 * The setpoint (SP) is always the first tier of one type; the process variable
3326 * (PV) is either any tier of the other type or any other tier of the same
3327 * type.
3328 *
3329 * The error is the difference between the SP and the PV; the correction is to
3330 * turn off protection when SP>PV or turn on protection when SP<PV.
3331 *
3332 * For future optimizations:
3333 * 1. The D term may discount the other two terms over time so that long-lived
3334 * generations can resist stale information.
3335 */
3336struct ctrl_pos {
3337 unsigned long refaulted;
3338 unsigned long total;
3339 int gain;
3340};
3341
3342static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3343 struct ctrl_pos *pos)
3344{
3345 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3346 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3347
3348 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3349 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3350 pos->total = lrugen->avg_total[type][tier] +
3351 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3352 if (tier)
3353 pos->total += lrugen->protected[hist][type][tier - 1];
3354 pos->gain = gain;
3355}
3356
3357static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3358{
3359 int hist, tier;
3360 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3361 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3362 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3363
3364 lockdep_assert_held(&lruvec->lru_lock);
3365
3366 if (!carryover && !clear)
3367 return;
3368
3369 hist = lru_hist_from_seq(seq);
3370
3371 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3372 if (carryover) {
3373 unsigned long sum;
3374
3375 sum = lrugen->avg_refaulted[type][tier] +
3376 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3377 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3378
3379 sum = lrugen->avg_total[type][tier] +
3380 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3381 if (tier)
3382 sum += lrugen->protected[hist][type][tier - 1];
3383 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3384 }
3385
3386 if (clear) {
3387 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3388 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3389 if (tier)
3390 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3391 }
3392 }
3393}
3394
3395static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3396{
3397 /*
3398 * Return true if the PV has a limited number of refaults or a lower
3399 * refaulted/total than the SP.
3400 */
3401 return pv->refaulted < MIN_LRU_BATCH ||
3402 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3403 (sp->refaulted + 1) * pv->total * pv->gain;
3404}
3405
3406/******************************************************************************
3407 * the aging
3408 ******************************************************************************/
3409
Yu Zhao0182f922022-09-18 02:00:04 -06003410/* promote pages accessed through page tables */
3411static int page_update_gen(struct page *page, int gen)
3412{
3413 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3414
3415 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3416 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3417
3418 do {
3419 /* lru_gen_del_page() has isolated this page? */
3420 if (!(old_flags & LRU_GEN_MASK)) {
3421 /* for shrink_page_list() */
3422 new_flags = old_flags | BIT(PG_referenced);
3423 continue;
3424 }
3425
3426 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3427 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3428 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3429
3430 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3431}
3432
Yu Zhao37397872022-09-18 02:00:03 -06003433/* protect pages accessed multiple times through file descriptors */
3434static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3435{
3436 int type = page_is_file_lru(page);
3437 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3438 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3439 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3440
3441 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3442
3443 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003444 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3445 /* page_update_gen() has promoted this page? */
3446 if (new_gen >= 0 && new_gen != old_gen)
3447 return new_gen;
3448
Yu Zhao37397872022-09-18 02:00:03 -06003449 new_gen = (old_gen + 1) % MAX_NR_GENS;
3450
3451 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3452 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3453 /* for end_page_writeback() */
3454 if (reclaiming)
3455 new_flags |= BIT(PG_reclaim);
3456 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3457
3458 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3459
3460 return new_gen;
3461}
3462
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003463static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3464 int old_gen, int new_gen)
3465{
3466 int type = page_is_file_lru(page);
3467 int zone = page_zonenum(page);
3468 int delta = thp_nr_pages(page);
3469
3470 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3471 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3472
3473 walk->batched++;
3474
3475 walk->nr_pages[old_gen][type][zone] -= delta;
3476 walk->nr_pages[new_gen][type][zone] += delta;
3477}
3478
3479static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3480{
3481 int gen, type, zone;
3482 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3483
3484 walk->batched = 0;
3485
3486 for_each_gen_type_zone(gen, type, zone) {
3487 enum lru_list lru = type * LRU_INACTIVE_FILE;
3488 int delta = walk->nr_pages[gen][type][zone];
3489
3490 if (!delta)
3491 continue;
3492
3493 walk->nr_pages[gen][type][zone] = 0;
3494 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3495 lrugen->nr_pages[gen][type][zone] + delta);
3496
3497 if (lru_gen_is_active(lruvec, gen))
3498 lru += LRU_ACTIVE;
3499 __update_lru_size(lruvec, lru, zone, delta);
3500 }
3501}
3502
3503static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3504{
3505 struct address_space *mapping;
3506 struct vm_area_struct *vma = args->vma;
3507 struct lru_gen_mm_walk *walk = args->private;
3508
3509 if (!vma_is_accessible(vma))
3510 return true;
3511
3512 if (is_vm_hugetlb_page(vma))
3513 return true;
3514
3515 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3516 return true;
3517
3518 if (vma == get_gate_vma(vma->vm_mm))
3519 return true;
3520
3521 if (vma_is_anonymous(vma))
3522 return !walk->can_swap;
3523
3524 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3525 return true;
3526
3527 mapping = vma->vm_file->f_mapping;
3528 if (mapping_unevictable(mapping))
3529 return true;
3530
3531 if (shmem_mapping(mapping))
3532 return !walk->can_swap;
3533
3534 /* to exclude special mappings like dax, etc. */
3535 return !mapping->a_ops->readpage;
3536}
3537
3538/*
3539 * Some userspace memory allocators map many single-page VMAs. Instead of
3540 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3541 * table to reduce zigzags and improve cache performance.
3542 */
3543static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3544 unsigned long *vm_start, unsigned long *vm_end)
3545{
3546 unsigned long start = round_up(*vm_end, size);
3547 unsigned long end = (start | ~mask) + 1;
3548
3549 VM_WARN_ON_ONCE(mask & size);
3550 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3551
3552 while (args->vma) {
3553 if (start >= args->vma->vm_end) {
3554 args->vma = args->vma->vm_next;
3555 continue;
3556 }
3557
3558 if (end && end <= args->vma->vm_start)
3559 return false;
3560
3561 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3562 args->vma = args->vma->vm_next;
3563 continue;
3564 }
3565
3566 *vm_start = max(start, args->vma->vm_start);
3567 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3568
3569 return true;
3570 }
3571
3572 return false;
3573}
3574
Yu Zhao0182f922022-09-18 02:00:04 -06003575static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3576{
3577 unsigned long pfn = pte_pfn(pte);
3578
3579 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3580
3581 if (!pte_present(pte) || is_zero_pfn(pfn))
3582 return -1;
3583
3584 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3585 return -1;
3586
3587 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3588 return -1;
3589
3590 return pfn;
3591}
3592
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003593#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3594static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3595{
3596 unsigned long pfn = pmd_pfn(pmd);
3597
3598 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3599
3600 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3601 return -1;
3602
3603 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3604 return -1;
3605
3606 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3607 return -1;
3608
3609 return pfn;
3610}
3611#endif
3612
Yu Zhao0182f922022-09-18 02:00:04 -06003613static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003614 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003615{
3616 struct page *page;
3617
3618 /* try to avoid unnecessary memory loads */
3619 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3620 return NULL;
3621
3622 page = compound_head(pfn_to_page(pfn));
3623 if (page_to_nid(page) != pgdat->node_id)
3624 return NULL;
3625
3626 if (page_memcg_rcu(page) != memcg)
3627 return NULL;
3628
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003629 /* file VMAs can contain anon pages from COW */
3630 if (!page_is_file_lru(page) && !can_swap)
3631 return NULL;
3632
Yu Zhao0182f922022-09-18 02:00:04 -06003633 return page;
3634}
3635
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003636static bool suitable_to_scan(int total, int young)
3637{
3638 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3639
3640 /* suitable if the average number of young PTEs per cacheline is >=1 */
3641 return young * n >= total;
3642}
3643
3644static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3645 struct mm_walk *args)
3646{
3647 int i;
3648 pte_t *pte;
3649 spinlock_t *ptl;
3650 unsigned long addr;
3651 int total = 0;
3652 int young = 0;
3653 struct lru_gen_mm_walk *walk = args->private;
3654 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3655 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3656 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3657
3658 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3659
3660 ptl = pte_lockptr(args->mm, pmd);
3661 if (!spin_trylock(ptl))
3662 return false;
3663
3664 arch_enter_lazy_mmu_mode();
3665
3666 pte = pte_offset_map(pmd, start & PMD_MASK);
3667restart:
3668 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3669 unsigned long pfn;
3670 struct page *page;
3671
3672 total++;
3673 walk->mm_stats[MM_LEAF_TOTAL]++;
3674
3675 pfn = get_pte_pfn(pte[i], args->vma, addr);
3676 if (pfn == -1)
3677 continue;
3678
3679 if (!pte_young(pte[i])) {
3680 walk->mm_stats[MM_LEAF_OLD]++;
3681 continue;
3682 }
3683
3684 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3685 if (!page)
3686 continue;
3687
3688 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3689 VM_WARN_ON_ONCE(true);
3690
3691 young++;
3692 walk->mm_stats[MM_LEAF_YOUNG]++;
3693
3694 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3695 !(PageAnon(page) && PageSwapBacked(page) &&
3696 !PageSwapCache(page)))
3697 set_page_dirty(page);
3698
3699 old_gen = page_update_gen(page, new_gen);
3700 if (old_gen >= 0 && old_gen != new_gen)
3701 update_batch_size(walk, page, old_gen, new_gen);
3702 }
3703
3704 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3705 goto restart;
3706
3707 pte_unmap(pte);
3708
3709 arch_leave_lazy_mmu_mode();
3710 spin_unlock(ptl);
3711
3712 return suitable_to_scan(total, young);
3713}
3714
3715#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3716static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3717 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3718{
3719 int i;
3720 pmd_t *pmd;
3721 spinlock_t *ptl;
3722 struct lru_gen_mm_walk *walk = args->private;
3723 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3724 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3725 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3726
3727 VM_WARN_ON_ONCE(pud_leaf(*pud));
3728
3729 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3730 if (*start == -1) {
3731 *start = next;
3732 return;
3733 }
3734
3735 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3736 if (i && i <= MIN_LRU_BATCH) {
3737 __set_bit(i - 1, bitmap);
3738 return;
3739 }
3740
3741 pmd = pmd_offset(pud, *start);
3742
3743 ptl = pmd_lockptr(args->mm, pmd);
3744 if (!spin_trylock(ptl))
3745 goto done;
3746
3747 arch_enter_lazy_mmu_mode();
3748
3749 do {
3750 unsigned long pfn;
3751 struct page *page;
3752 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3753
3754 pfn = get_pmd_pfn(pmd[i], vma, addr);
3755 if (pfn == -1)
3756 goto next;
3757
3758 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003759 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3760 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003761 pmdp_test_and_clear_young(vma, addr, pmd + i);
3762 goto next;
3763 }
3764
3765 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3766 if (!page)
3767 goto next;
3768
3769 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3770 goto next;
3771
3772 walk->mm_stats[MM_LEAF_YOUNG]++;
3773
3774 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3775 !(PageAnon(page) && PageSwapBacked(page) &&
3776 !PageSwapCache(page)))
3777 set_page_dirty(page);
3778
3779 old_gen = page_update_gen(page, new_gen);
3780 if (old_gen >= 0 && old_gen != new_gen)
3781 update_batch_size(walk, page, old_gen, new_gen);
3782next:
3783 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3784 } while (i <= MIN_LRU_BATCH);
3785
3786 arch_leave_lazy_mmu_mode();
3787 spin_unlock(ptl);
3788done:
3789 *start = -1;
3790 bitmap_zero(bitmap, MIN_LRU_BATCH);
3791}
3792#else
3793static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3794 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3795{
3796}
3797#endif
3798
3799static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3800 struct mm_walk *args)
3801{
3802 int i;
3803 pmd_t *pmd;
3804 unsigned long next;
3805 unsigned long addr;
3806 struct vm_area_struct *vma;
3807 unsigned long pos = -1;
3808 struct lru_gen_mm_walk *walk = args->private;
3809 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3810
3811 VM_WARN_ON_ONCE(pud_leaf(*pud));
3812
3813 /*
3814 * Finish an entire PMD in two passes: the first only reaches to PTE
3815 * tables to avoid taking the PMD lock; the second, if necessary, takes
3816 * the PMD lock to clear the accessed bit in PMD entries.
3817 */
3818 pmd = pmd_offset(pud, start & PUD_MASK);
3819restart:
3820 /* walk_pte_range() may call get_next_vma() */
3821 vma = args->vma;
3822 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3823 pmd_t val = pmd_read_atomic(pmd + i);
3824
3825 /* for pmd_read_atomic() */
3826 barrier();
3827
3828 next = pmd_addr_end(addr, end);
3829
3830 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3831 walk->mm_stats[MM_LEAF_TOTAL]++;
3832 continue;
3833 }
3834
3835#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3836 if (pmd_trans_huge(val)) {
3837 unsigned long pfn = pmd_pfn(val);
3838 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3839
3840 walk->mm_stats[MM_LEAF_TOTAL]++;
3841
3842 if (!pmd_young(val)) {
3843 walk->mm_stats[MM_LEAF_OLD]++;
3844 continue;
3845 }
3846
3847 /* try to avoid unnecessary memory loads */
3848 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3849 continue;
3850
3851 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3852 continue;
3853 }
3854#endif
3855 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3856
3857#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003858 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3859 if (!pmd_young(val))
3860 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003861
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003862 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3863 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003864#endif
3865 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3866 continue;
3867
3868 walk->mm_stats[MM_NONLEAF_FOUND]++;
3869
3870 if (!walk_pte_range(&val, addr, next, args))
3871 continue;
3872
3873 walk->mm_stats[MM_NONLEAF_ADDED]++;
3874
3875 /* carry over to the next generation */
3876 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3877 }
3878
3879 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3880
3881 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3882 goto restart;
3883}
3884
3885static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3886 struct mm_walk *args)
3887{
3888 int i;
3889 pud_t *pud;
3890 unsigned long addr;
3891 unsigned long next;
3892 struct lru_gen_mm_walk *walk = args->private;
3893
3894 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3895
3896 pud = pud_offset(p4d, start & P4D_MASK);
3897restart:
3898 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3899 pud_t val = READ_ONCE(pud[i]);
3900
3901 next = pud_addr_end(addr, end);
3902
3903 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3904 continue;
3905
3906 walk_pmd_range(&val, addr, next, args);
3907
3908 /* a racy check to curtail the waiting time */
3909 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3910 return 1;
3911
3912 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3913 end = (addr | ~PUD_MASK) + 1;
3914 goto done;
3915 }
3916 }
3917
3918 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3919 goto restart;
3920
3921 end = round_up(end, P4D_SIZE);
3922done:
3923 if (!end || !args->vma)
3924 return 1;
3925
3926 walk->next_addr = max(end, args->vma->vm_start);
3927
3928 return -EAGAIN;
3929}
3930
3931static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3932{
3933 static const struct mm_walk_ops mm_walk_ops = {
3934 .test_walk = should_skip_vma,
3935 .p4d_entry = walk_pud_range,
3936 };
3937
3938 int err;
3939 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3940
3941 walk->next_addr = FIRST_USER_ADDRESS;
3942
3943 do {
3944 err = -EBUSY;
3945
3946 /* page_update_gen() requires stable page_memcg() */
3947 if (!mem_cgroup_trylock_pages(memcg))
3948 break;
3949
3950 /* the caller might be holding the lock for write */
3951 if (mmap_read_trylock(mm)) {
3952 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3953
3954 mmap_read_unlock(mm);
3955 }
3956
3957 mem_cgroup_unlock_pages();
3958
3959 if (walk->batched) {
3960 spin_lock_irq(&lruvec->lru_lock);
3961 reset_batch_size(lruvec, walk);
3962 spin_unlock_irq(&lruvec->lru_lock);
3963 }
3964
3965 cond_resched();
3966 } while (err == -EAGAIN);
3967}
3968
3969static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3970{
3971 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3972
3973 if (pgdat && current_is_kswapd()) {
3974 VM_WARN_ON_ONCE(walk);
3975
3976 walk = &pgdat->mm_walk;
3977 } else if (!pgdat && !walk) {
3978 VM_WARN_ON_ONCE(current_is_kswapd());
3979
3980 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3981 }
3982
3983 current->reclaim_state->mm_walk = walk;
3984
3985 return walk;
3986}
3987
3988static void clear_mm_walk(void)
3989{
3990 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3991
3992 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3993 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3994
3995 current->reclaim_state->mm_walk = NULL;
3996
3997 if (!current_is_kswapd())
3998 kfree(walk);
3999}
4000
Yu Zhao4983c522022-09-18 02:00:09 -06004001static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004002{
Yu Zhao4983c522022-09-18 02:00:09 -06004003 int zone;
4004 int remaining = MAX_LRU_BATCH;
Yu Zhao37397872022-09-18 02:00:03 -06004005 struct lru_gen_struct *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004006 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004007
Yu Zhao4983c522022-09-18 02:00:09 -06004008 if (type == LRU_GEN_ANON && !can_swap)
4009 goto done;
4010
4011 /* prevent cold/hot inversion if force_scan is true */
4012 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4013 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4014
4015 while (!list_empty(head)) {
4016 struct page *page = lru_to_page(head);
4017
4018 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4019 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4020 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4021 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4022
4023 new_gen = page_inc_gen(lruvec, page, false);
4024 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
4025
4026 if (!--remaining)
4027 return false;
4028 }
4029 }
4030done:
Yu Zhao37397872022-09-18 02:00:03 -06004031 reset_ctrl_pos(lruvec, type, true);
4032 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004033
4034 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004035}
4036
4037static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4038{
4039 int gen, type, zone;
4040 bool success = false;
4041 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4042 DEFINE_MIN_SEQ(lruvec);
4043
4044 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4045
4046 /* find the oldest populated generation */
4047 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4048 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4049 gen = lru_gen_from_seq(min_seq[type]);
4050
4051 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4052 if (!list_empty(&lrugen->lists[gen][type][zone]))
4053 goto next;
4054 }
4055
4056 min_seq[type]++;
4057 }
4058next:
4059 ;
4060 }
4061
4062 /* see the comment on lru_gen_struct */
4063 if (can_swap) {
4064 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4065 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4066 }
4067
4068 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4069 if (min_seq[type] == lrugen->min_seq[type])
4070 continue;
4071
4072 reset_ctrl_pos(lruvec, type, true);
4073 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4074 success = true;
4075 }
4076
4077 return success;
4078}
4079
Yu Zhao4983c522022-09-18 02:00:09 -06004080static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004081{
4082 int prev, next;
4083 int type, zone;
4084 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4085
4086 spin_lock_irq(&lruvec->lru_lock);
4087
4088 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4089
Yu Zhao37397872022-09-18 02:00:03 -06004090 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4091 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4092 continue;
4093
Yu Zhao4983c522022-09-18 02:00:09 -06004094 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004095
Yu Zhao4983c522022-09-18 02:00:09 -06004096 while (!inc_min_seq(lruvec, type, can_swap)) {
4097 spin_unlock_irq(&lruvec->lru_lock);
4098 cond_resched();
4099 spin_lock_irq(&lruvec->lru_lock);
4100 }
Yu Zhao37397872022-09-18 02:00:03 -06004101 }
4102
4103 /*
4104 * Update the active/inactive LRU sizes for compatibility. Both sides of
4105 * the current max_seq need to be covered, since max_seq+1 can overlap
4106 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4107 * overlap, cold/hot inversion happens.
4108 */
4109 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4110 next = lru_gen_from_seq(lrugen->max_seq + 1);
4111
4112 for (type = 0; type < ANON_AND_FILE; type++) {
4113 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4114 enum lru_list lru = type * LRU_INACTIVE_FILE;
4115 long delta = lrugen->nr_pages[prev][type][zone] -
4116 lrugen->nr_pages[next][type][zone];
4117
4118 if (!delta)
4119 continue;
4120
4121 __update_lru_size(lruvec, lru, zone, delta);
4122 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4123 }
4124 }
4125
4126 for (type = 0; type < ANON_AND_FILE; type++)
4127 reset_ctrl_pos(lruvec, type, false);
4128
Yu Zhao430499c2022-09-18 02:00:08 -06004129 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004130 /* make sure preceding modifications appear */
4131 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004132
Yu Zhao37397872022-09-18 02:00:03 -06004133 spin_unlock_irq(&lruvec->lru_lock);
4134}
4135
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004136static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004137 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004138{
4139 bool success;
4140 struct lru_gen_mm_walk *walk;
4141 struct mm_struct *mm = NULL;
4142 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4143
4144 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4145
4146 /* see the comment in iterate_mm_list() */
4147 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4148 success = false;
4149 goto done;
4150 }
4151
4152 /*
4153 * If the hardware doesn't automatically set the accessed bit, fallback
4154 * to lru_gen_look_around(), which only clears the accessed bit in a
4155 * handful of PTEs. Spreading the work out over a period of time usually
4156 * is less efficient, but it avoids bursty page faults.
4157 */
Yu Zhao4983c522022-09-18 02:00:09 -06004158 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004159 success = iterate_mm_list_nowalk(lruvec, max_seq);
4160 goto done;
4161 }
4162
4163 walk = set_mm_walk(NULL);
4164 if (!walk) {
4165 success = iterate_mm_list_nowalk(lruvec, max_seq);
4166 goto done;
4167 }
4168
4169 walk->lruvec = lruvec;
4170 walk->max_seq = max_seq;
4171 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004172 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004173
4174 do {
4175 success = iterate_mm_list(lruvec, walk, &mm);
4176 if (mm)
4177 walk_mm(lruvec, mm, walk);
4178
4179 cond_resched();
4180 } while (mm);
4181done:
4182 if (!success) {
4183 if (sc->priority <= DEF_PRIORITY - 2)
4184 wait_event_killable(lruvec->mm_state.wait,
4185 max_seq < READ_ONCE(lrugen->max_seq));
4186
4187 return max_seq < READ_ONCE(lrugen->max_seq);
4188 }
4189
4190 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4191
Yu Zhao4983c522022-09-18 02:00:09 -06004192 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004193 /* either this sees any waiters or they will see updated max_seq */
4194 if (wq_has_sleeper(&lruvec->mm_state.wait))
4195 wake_up_all(&lruvec->mm_state.wait);
4196
4197 return true;
4198}
4199
Yu Zhao37397872022-09-18 02:00:03 -06004200static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4201 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4202{
4203 int gen, type, zone;
4204 unsigned long old = 0;
4205 unsigned long young = 0;
4206 unsigned long total = 0;
4207 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4208 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4209
4210 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4211 unsigned long seq;
4212
4213 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4214 unsigned long size = 0;
4215
4216 gen = lru_gen_from_seq(seq);
4217
4218 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4219 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4220
4221 total += size;
4222 if (seq == max_seq)
4223 young += size;
4224 else if (seq + MIN_NR_GENS == max_seq)
4225 old += size;
4226 }
4227 }
4228
4229 /* try to scrape all its memory if this memcg was deleted */
4230 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4231
4232 /*
4233 * The aging tries to be lazy to reduce the overhead, while the eviction
4234 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4235 * ideal number of generations is MIN_NR_GENS+1.
4236 */
4237 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4238 return true;
4239 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4240 return false;
4241
4242 /*
4243 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4244 * of the total number of pages for each generation. A reasonable range
4245 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4246 * aging cares about the upper bound of hot pages, while the eviction
4247 * cares about the lower bound of cold pages.
4248 */
4249 if (young * MIN_NR_GENS > total)
4250 return true;
4251 if (old * (MIN_NR_GENS + 2) < total)
4252 return true;
4253
4254 return false;
4255}
4256
Yu Zhao430499c2022-09-18 02:00:08 -06004257static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004258{
4259 bool need_aging;
4260 unsigned long nr_to_scan;
4261 int swappiness = get_swappiness(lruvec, sc);
4262 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4263 DEFINE_MAX_SEQ(lruvec);
4264 DEFINE_MIN_SEQ(lruvec);
4265
4266 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4267
4268 mem_cgroup_calculate_protection(NULL, memcg);
4269
4270 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004271 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004272
4273 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004274
4275 if (min_ttl) {
4276 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4277 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4278
4279 if (time_is_after_jiffies(birth + min_ttl))
4280 return false;
4281
4282 /* the size is likely too small to be helpful */
4283 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4284 return false;
4285 }
4286
Yu Zhao37397872022-09-18 02:00:03 -06004287 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004288 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004289
4290 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004291}
4292
Yu Zhao430499c2022-09-18 02:00:08 -06004293/* to protect the working set of the last N jiffies */
4294static unsigned long lru_gen_min_ttl __read_mostly;
4295
Yu Zhao37397872022-09-18 02:00:03 -06004296static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4297{
4298 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004299 bool success = false;
4300 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004301
4302 VM_WARN_ON_ONCE(!current_is_kswapd());
4303
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004304 sc->last_reclaimed = sc->nr_reclaimed;
4305
4306 /*
4307 * To reduce the chance of going into the aging path, which can be
4308 * costly, optimistically skip it if the flag below was cleared in the
4309 * eviction path. This improves the overall performance when multiple
4310 * memcgs are available.
4311 */
4312 if (!sc->memcgs_need_aging) {
4313 sc->memcgs_need_aging = true;
4314 return;
4315 }
4316
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004317 set_mm_walk(pgdat);
4318
Yu Zhao37397872022-09-18 02:00:03 -06004319 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4320 do {
4321 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4322
Yu Zhao430499c2022-09-18 02:00:08 -06004323 if (age_lruvec(lruvec, sc, min_ttl))
4324 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004325
4326 cond_resched();
4327 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004328
4329 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004330
4331 /* check the order to exclude compaction-induced reclaim */
4332 if (success || !min_ttl || sc->order)
4333 return;
4334
4335 /*
4336 * The main goal is to OOM kill if every generation from all memcgs is
4337 * younger than min_ttl. However, another possibility is all memcgs are
4338 * either below min or empty.
4339 */
4340 if (mutex_trylock(&oom_lock)) {
4341 struct oom_control oc = {
4342 .gfp_mask = sc->gfp_mask,
4343 };
4344
4345 out_of_memory(&oc);
4346
4347 mutex_unlock(&oom_lock);
4348 }
Yu Zhao37397872022-09-18 02:00:03 -06004349}
4350
Yu Zhao0182f922022-09-18 02:00:04 -06004351/*
4352 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004353 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4354 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4355 * the PTE table to the Bloom filter. This forms a feedback loop between the
4356 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004357 */
4358void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4359{
4360 int i;
4361 pte_t *pte;
4362 unsigned long start;
4363 unsigned long end;
4364 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004365 struct lru_gen_mm_walk *walk;
4366 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004367 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4368 struct page *page = pvmw->page;
4369 struct mem_cgroup *memcg = page_memcg(page);
4370 struct pglist_data *pgdat = page_pgdat(page);
4371 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4372 DEFINE_MAX_SEQ(lruvec);
4373 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4374
4375 lockdep_assert_held(pvmw->ptl);
4376 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4377
4378 if (spin_is_contended(pvmw->ptl))
4379 return;
4380
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004381 /* avoid taking the LRU lock under the PTL when possible */
4382 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4383
Yu Zhao0182f922022-09-18 02:00:04 -06004384 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4385 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4386
4387 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4388 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4389 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4390 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4391 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4392 else {
4393 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4394 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4395 }
4396 }
4397
4398 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4399
4400 rcu_read_lock();
4401 arch_enter_lazy_mmu_mode();
4402
4403 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4404 unsigned long pfn;
4405
4406 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4407 if (pfn == -1)
4408 continue;
4409
4410 if (!pte_young(pte[i]))
4411 continue;
4412
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004413 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004414 if (!page)
4415 continue;
4416
4417 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4418 VM_WARN_ON_ONCE(true);
4419
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004420 young++;
4421
Yu Zhao0182f922022-09-18 02:00:04 -06004422 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4423 !(PageAnon(page) && PageSwapBacked(page) &&
4424 !PageSwapCache(page)))
4425 set_page_dirty(page);
4426
4427 old_gen = page_lru_gen(page);
4428 if (old_gen < 0)
4429 SetPageReferenced(page);
4430 else if (old_gen != new_gen)
4431 __set_bit(i, bitmap);
4432 }
4433
4434 arch_leave_lazy_mmu_mode();
4435 rcu_read_unlock();
4436
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004437 /* feedback from rmap walkers to page table walkers */
4438 if (suitable_to_scan(i, young))
4439 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4440
4441 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004442 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4443 page = pte_page(pte[i]);
4444 activate_page(page);
4445 }
4446 return;
4447 }
4448
4449 /* page_update_gen() requires stable page_memcg() */
4450 if (!mem_cgroup_trylock_pages(memcg))
4451 return;
4452
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004453 if (!walk) {
4454 spin_lock_irq(&lruvec->lru_lock);
4455 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4456 }
Yu Zhao0182f922022-09-18 02:00:04 -06004457
4458 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4459 page = compound_head(pte_page(pte[i]));
4460 if (page_memcg_rcu(page) != memcg)
4461 continue;
4462
4463 old_gen = page_update_gen(page, new_gen);
4464 if (old_gen < 0 || old_gen == new_gen)
4465 continue;
4466
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004467 if (walk)
4468 update_batch_size(walk, page, old_gen, new_gen);
4469 else
4470 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004471 }
4472
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004473 if (!walk)
4474 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004475
4476 mem_cgroup_unlock_pages();
4477}
4478
Yu Zhao37397872022-09-18 02:00:03 -06004479/******************************************************************************
4480 * the eviction
4481 ******************************************************************************/
4482
4483static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4484{
4485 bool success;
4486 int gen = page_lru_gen(page);
4487 int type = page_is_file_lru(page);
4488 int zone = page_zonenum(page);
4489 int delta = thp_nr_pages(page);
4490 int refs = page_lru_refs(page);
4491 int tier = lru_tier_from_refs(refs);
4492 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4493
4494 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4495
4496 /* unevictable */
4497 if (!page_evictable(page)) {
4498 success = lru_gen_del_page(lruvec, page, true);
4499 VM_WARN_ON_ONCE_PAGE(!success, page);
4500 SetPageUnevictable(page);
4501 add_page_to_lru_list(page, lruvec);
4502 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4503 return true;
4504 }
4505
4506 /* dirty lazyfree */
4507 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4508 success = lru_gen_del_page(lruvec, page, true);
4509 VM_WARN_ON_ONCE_PAGE(!success, page);
4510 SetPageSwapBacked(page);
4511 add_page_to_lru_list_tail(page, lruvec);
4512 return true;
4513 }
4514
Yu Zhao0182f922022-09-18 02:00:04 -06004515 /* promoted */
4516 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4517 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4518 return true;
4519 }
4520
Yu Zhao37397872022-09-18 02:00:03 -06004521 /* protected */
4522 if (tier > tier_idx) {
4523 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4524
4525 gen = page_inc_gen(lruvec, page, false);
4526 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4527
4528 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4529 lrugen->protected[hist][type][tier - 1] + delta);
4530 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4531 return true;
4532 }
4533
4534 /* waiting for writeback */
4535 if (PageLocked(page) || PageWriteback(page) ||
4536 (type == LRU_GEN_FILE && PageDirty(page))) {
4537 gen = page_inc_gen(lruvec, page, true);
4538 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4539 return true;
4540 }
4541
4542 return false;
4543}
4544
4545static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4546{
4547 bool success;
4548
4549 /* unmapping inhibited */
4550 if (!sc->may_unmap && page_mapped(page))
4551 return false;
4552
4553 /* swapping inhibited */
4554 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4555 (PageDirty(page) ||
4556 (PageAnon(page) && !PageSwapCache(page))))
4557 return false;
4558
4559 /* raced with release_pages() */
4560 if (!get_page_unless_zero(page))
4561 return false;
4562
4563 /* raced with another isolation */
4564 if (!TestClearPageLRU(page)) {
4565 put_page(page);
4566 return false;
4567 }
4568
4569 /* see the comment on MAX_NR_TIERS */
4570 if (!PageReferenced(page))
4571 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4572
4573 /* for shrink_page_list() */
4574 ClearPageReclaim(page);
4575 ClearPageReferenced(page);
4576
4577 success = lru_gen_del_page(lruvec, page, true);
4578 VM_WARN_ON_ONCE_PAGE(!success, page);
4579
4580 return true;
4581}
4582
4583static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4584 int type, int tier, struct list_head *list)
4585{
4586 int gen, zone;
4587 enum vm_event_item item;
4588 int sorted = 0;
4589 int scanned = 0;
4590 int isolated = 0;
4591 int remaining = MAX_LRU_BATCH;
4592 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4593 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4594
4595 VM_WARN_ON_ONCE(!list_empty(list));
4596
4597 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4598 return 0;
4599
4600 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4601
4602 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4603 LIST_HEAD(moved);
4604 int skipped = 0;
4605 struct list_head *head = &lrugen->lists[gen][type][zone];
4606
4607 while (!list_empty(head)) {
4608 struct page *page = lru_to_page(head);
4609 int delta = thp_nr_pages(page);
4610
4611 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4612 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4613 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4614 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4615
4616 scanned += delta;
4617
4618 if (sort_page(lruvec, page, tier))
4619 sorted += delta;
4620 else if (isolate_page(lruvec, page, sc)) {
4621 list_add(&page->lru, list);
4622 isolated += delta;
4623 } else {
4624 list_move(&page->lru, &moved);
4625 skipped += delta;
4626 }
4627
4628 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4629 break;
4630 }
4631
4632 if (skipped) {
4633 list_splice(&moved, head);
4634 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4635 }
4636
4637 if (!remaining || isolated >= MIN_LRU_BATCH)
4638 break;
4639 }
4640
4641 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4642 if (!cgroup_reclaim(sc)) {
4643 __count_vm_events(item, isolated);
4644 __count_vm_events(PGREFILL, sorted);
4645 }
4646 __count_memcg_events(memcg, item, isolated);
4647 __count_memcg_events(memcg, PGREFILL, sorted);
4648 __count_vm_events(PGSCAN_ANON + type, isolated);
4649
4650 /*
4651 * There might not be eligible pages due to reclaim_idx, may_unmap and
4652 * may_writepage. Check the remaining to prevent livelock if it's not
4653 * making progress.
4654 */
4655 return isolated || !remaining ? scanned : 0;
4656}
4657
4658static int get_tier_idx(struct lruvec *lruvec, int type)
4659{
4660 int tier;
4661 struct ctrl_pos sp, pv;
4662
4663 /*
4664 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4665 * This value is chosen because any other tier would have at least twice
4666 * as many refaults as the first tier.
4667 */
4668 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4669 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4670 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4671 if (!positive_ctrl_err(&sp, &pv))
4672 break;
4673 }
4674
4675 return tier - 1;
4676}
4677
4678static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4679{
4680 int type, tier;
4681 struct ctrl_pos sp, pv;
4682 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4683
4684 /*
4685 * Compare the first tier of anon with that of file to determine which
4686 * type to scan. Also need to compare other tiers of the selected type
4687 * with the first tier of the other type to determine the last tier (of
4688 * the selected type) to evict.
4689 */
4690 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4691 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4692 type = positive_ctrl_err(&sp, &pv);
4693
4694 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4695 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4696 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4697 if (!positive_ctrl_err(&sp, &pv))
4698 break;
4699 }
4700
4701 *tier_idx = tier - 1;
4702
4703 return type;
4704}
4705
4706static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4707 int *type_scanned, struct list_head *list)
4708{
4709 int i;
4710 int type;
4711 int scanned;
4712 int tier = -1;
4713 DEFINE_MIN_SEQ(lruvec);
4714
4715 /*
4716 * Try to make the obvious choice first. When anon and file are both
4717 * available from the same generation, interpret swappiness 1 as file
4718 * first and 200 as anon first.
4719 */
4720 if (!swappiness)
4721 type = LRU_GEN_FILE;
4722 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4723 type = LRU_GEN_ANON;
4724 else if (swappiness == 1)
4725 type = LRU_GEN_FILE;
4726 else if (swappiness == 200)
4727 type = LRU_GEN_ANON;
4728 else
4729 type = get_type_to_scan(lruvec, swappiness, &tier);
4730
4731 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4732 if (tier < 0)
4733 tier = get_tier_idx(lruvec, type);
4734
4735 scanned = scan_pages(lruvec, sc, type, tier, list);
4736 if (scanned)
4737 break;
4738
4739 type = !type;
4740 tier = -1;
4741 }
4742
4743 *type_scanned = type;
4744
4745 return scanned;
4746}
4747
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004748static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4749 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004750{
4751 int type;
4752 int scanned;
4753 int reclaimed;
4754 LIST_HEAD(list);
4755 struct page *page;
4756 enum vm_event_item item;
4757 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004758 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004759 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4760 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4761
4762 spin_lock_irq(&lruvec->lru_lock);
4763
4764 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4765
4766 scanned += try_to_inc_min_seq(lruvec, swappiness);
4767
4768 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4769 scanned = 0;
4770
4771 spin_unlock_irq(&lruvec->lru_lock);
4772
4773 if (list_empty(&list))
4774 return scanned;
4775
4776 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4777
4778 list_for_each_entry(page, &list, lru) {
4779 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4780 if (PageWorkingset(page))
4781 SetPageReferenced(page);
4782
4783 /* don't add rejected pages to the oldest generation */
4784 if (PageReclaim(page) &&
4785 (PageDirty(page) || PageWriteback(page)))
4786 ClearPageActive(page);
4787 else
4788 SetPageActive(page);
4789 }
4790
4791 spin_lock_irq(&lruvec->lru_lock);
4792
4793 move_pages_to_lru(lruvec, &list);
4794
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004795 walk = current->reclaim_state->mm_walk;
4796 if (walk && walk->batched)
4797 reset_batch_size(lruvec, walk);
4798
Yu Zhao37397872022-09-18 02:00:03 -06004799 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4800 if (!cgroup_reclaim(sc))
4801 __count_vm_events(item, reclaimed);
4802 __count_memcg_events(memcg, item, reclaimed);
4803 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4804
4805 spin_unlock_irq(&lruvec->lru_lock);
4806
4807 mem_cgroup_uncharge_list(&list);
4808 free_unref_page_list(&list);
4809
4810 sc->nr_reclaimed += reclaimed;
4811
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004812 if (need_swapping && type == LRU_GEN_ANON)
4813 *need_swapping = true;
4814
Yu Zhao37397872022-09-18 02:00:03 -06004815 return scanned;
4816}
4817
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004818/*
4819 * For future optimizations:
4820 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4821 * reclaim.
4822 */
Yu Zhao37397872022-09-18 02:00:03 -06004823static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004824 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004825{
Yu Zhao37397872022-09-18 02:00:03 -06004826 unsigned long nr_to_scan;
4827 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4828 DEFINE_MAX_SEQ(lruvec);
4829 DEFINE_MIN_SEQ(lruvec);
4830
4831 if (mem_cgroup_below_min(memcg) ||
4832 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4833 return 0;
4834
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004835 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4836 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004837 return nr_to_scan;
4838
4839 /* skip the aging path at the default priority */
4840 if (sc->priority == DEF_PRIORITY)
4841 goto done;
4842
4843 /* leave the work to lru_gen_age_node() */
4844 if (current_is_kswapd())
4845 return 0;
4846
Yu Zhao4983c522022-09-18 02:00:09 -06004847 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004848 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004849done:
4850 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4851}
4852
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004853static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4854 struct scan_control *sc, bool need_swapping)
4855{
4856 int i;
4857 DEFINE_MAX_SEQ(lruvec);
4858
4859 if (!current_is_kswapd()) {
4860 /* age each memcg at most once to ensure fairness */
4861 if (max_seq - seq > 1)
4862 return true;
4863
4864 /* over-swapping can increase allocation latency */
4865 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4866 return true;
4867
4868 /* give this thread a chance to exit and free its memory */
4869 if (fatal_signal_pending(current)) {
4870 sc->nr_reclaimed += MIN_LRU_BATCH;
4871 return true;
4872 }
4873
4874 if (cgroup_reclaim(sc))
4875 return false;
4876 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4877 return false;
4878
4879 /* keep scanning at low priorities to ensure fairness */
4880 if (sc->priority > DEF_PRIORITY - 2)
4881 return false;
4882
4883 /*
4884 * A minimum amount of work was done under global memory pressure. For
4885 * kswapd, it may be overshooting. For direct reclaim, the allocation
4886 * may succeed if all suitable zones are somewhat safe. In either case,
4887 * it's better to stop now, and restart later if necessary.
4888 */
4889 for (i = 0; i <= sc->reclaim_idx; i++) {
4890 unsigned long wmark;
4891 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4892
4893 if (!managed_zone(zone))
4894 continue;
4895
4896 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4897 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4898 return false;
4899 }
4900
4901 sc->nr_reclaimed += MIN_LRU_BATCH;
4902
4903 return true;
4904}
4905
Yu Zhao37397872022-09-18 02:00:03 -06004906static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4907{
4908 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004909 bool need_aging = false;
4910 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004911 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004912 unsigned long reclaimed = sc->nr_reclaimed;
4913 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004914
4915 lru_add_drain();
4916
4917 blk_start_plug(&plug);
4918
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004919 set_mm_walk(lruvec_pgdat(lruvec));
4920
Yu Zhao37397872022-09-18 02:00:03 -06004921 while (true) {
4922 int delta;
4923 int swappiness;
4924 unsigned long nr_to_scan;
4925
4926 if (sc->may_swap)
4927 swappiness = get_swappiness(lruvec, sc);
4928 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4929 swappiness = 1;
4930 else
4931 swappiness = 0;
4932
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004933 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004934 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004935 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004936
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004937 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004938 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004939 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004940
4941 scanned += delta;
4942 if (scanned >= nr_to_scan)
4943 break;
4944
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004945 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4946 break;
4947
Yu Zhao37397872022-09-18 02:00:03 -06004948 cond_resched();
4949 }
4950
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004951 /* see the comment in lru_gen_age_node() */
4952 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4953 sc->memcgs_need_aging = false;
4954done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004955 clear_mm_walk();
4956
Yu Zhao37397872022-09-18 02:00:03 -06004957 blk_finish_plug(&plug);
4958}
4959
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004960/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004961 * state change
4962 ******************************************************************************/
4963
4964static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4965{
4966 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4967
4968 if (lrugen->enabled) {
4969 enum lru_list lru;
4970
4971 for_each_evictable_lru(lru) {
4972 if (!list_empty(&lruvec->lists[lru]))
4973 return false;
4974 }
4975 } else {
4976 int gen, type, zone;
4977
4978 for_each_gen_type_zone(gen, type, zone) {
4979 if (!list_empty(&lrugen->lists[gen][type][zone]))
4980 return false;
4981 }
4982 }
4983
4984 return true;
4985}
4986
4987static bool fill_evictable(struct lruvec *lruvec)
4988{
4989 enum lru_list lru;
4990 int remaining = MAX_LRU_BATCH;
4991
4992 for_each_evictable_lru(lru) {
4993 int type = is_file_lru(lru);
4994 bool active = is_active_lru(lru);
4995 struct list_head *head = &lruvec->lists[lru];
4996
4997 while (!list_empty(head)) {
4998 bool success;
4999 struct page *page = lru_to_page(head);
5000
5001 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5002 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5003 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5004 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5005
5006 del_page_from_lru_list(page, lruvec);
5007 success = lru_gen_add_page(lruvec, page, false);
5008 VM_WARN_ON_ONCE(!success);
5009
5010 if (!--remaining)
5011 return false;
5012 }
5013 }
5014
5015 return true;
5016}
5017
5018static bool drain_evictable(struct lruvec *lruvec)
5019{
5020 int gen, type, zone;
5021 int remaining = MAX_LRU_BATCH;
5022
5023 for_each_gen_type_zone(gen, type, zone) {
5024 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5025
5026 while (!list_empty(head)) {
5027 bool success;
5028 struct page *page = lru_to_page(head);
5029
5030 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5031 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5032 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5033 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5034
5035 success = lru_gen_del_page(lruvec, page, false);
5036 VM_WARN_ON_ONCE(!success);
5037 add_page_to_lru_list(page, lruvec);
5038
5039 if (!--remaining)
5040 return false;
5041 }
5042 }
5043
5044 return true;
5045}
5046
5047static void lru_gen_change_state(bool enabled)
5048{
5049 static DEFINE_MUTEX(state_mutex);
5050
5051 struct mem_cgroup *memcg;
5052
5053 cgroup_lock();
5054 cpus_read_lock();
5055 get_online_mems();
5056 mutex_lock(&state_mutex);
5057
5058 if (enabled == lru_gen_enabled())
5059 goto unlock;
5060
5061 if (enabled)
5062 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5063 else
5064 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5065
5066 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5067 do {
5068 int nid;
5069
5070 for_each_node(nid) {
5071 struct lruvec *lruvec = get_lruvec(memcg, nid);
5072
5073 if (!lruvec)
5074 continue;
5075
5076 spin_lock_irq(&lruvec->lru_lock);
5077
5078 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5079 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5080
5081 lruvec->lrugen.enabled = enabled;
5082
5083 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5084 spin_unlock_irq(&lruvec->lru_lock);
5085 cond_resched();
5086 spin_lock_irq(&lruvec->lru_lock);
5087 }
5088
5089 spin_unlock_irq(&lruvec->lru_lock);
5090 }
5091
5092 cond_resched();
5093 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5094unlock:
5095 mutex_unlock(&state_mutex);
5096 put_online_mems();
5097 cpus_read_unlock();
5098 cgroup_unlock();
5099}
5100
5101/******************************************************************************
5102 * sysfs interface
5103 ******************************************************************************/
5104
Yu Zhao430499c2022-09-18 02:00:08 -06005105static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5106{
5107 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5108}
5109
Yu Zhao642d9862022-09-18 02:00:10 -06005110/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005111static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5112 const char *buf, size_t len)
5113{
5114 unsigned int msecs;
5115
5116 if (kstrtouint(buf, 0, &msecs))
5117 return -EINVAL;
5118
5119 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5120
5121 return len;
5122}
5123
5124static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5125 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5126);
5127
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005128static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5129{
5130 unsigned int caps = 0;
5131
5132 if (get_cap(LRU_GEN_CORE))
5133 caps |= BIT(LRU_GEN_CORE);
5134
5135 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5136 caps |= BIT(LRU_GEN_MM_WALK);
5137
5138 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5139 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5140
5141 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5142}
5143
Yu Zhao642d9862022-09-18 02:00:10 -06005144/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005145static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5146 const char *buf, size_t len)
5147{
5148 int i;
5149 unsigned int caps;
5150
5151 if (tolower(*buf) == 'n')
5152 caps = 0;
5153 else if (tolower(*buf) == 'y')
5154 caps = -1;
5155 else if (kstrtouint(buf, 0, &caps))
5156 return -EINVAL;
5157
5158 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5159 bool enabled = caps & BIT(i);
5160
5161 if (i == LRU_GEN_CORE)
5162 lru_gen_change_state(enabled);
5163 else if (enabled)
5164 static_branch_enable(&lru_gen_caps[i]);
5165 else
5166 static_branch_disable(&lru_gen_caps[i]);
5167 }
5168
5169 return len;
5170}
5171
5172static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5173 enabled, 0644, show_enabled, store_enabled
5174);
5175
5176static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005177 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005178 &lru_gen_enabled_attr.attr,
5179 NULL
5180};
5181
5182static struct attribute_group lru_gen_attr_group = {
5183 .name = "lru_gen",
5184 .attrs = lru_gen_attrs,
5185};
5186
5187/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005188 * debugfs interface
5189 ******************************************************************************/
5190
5191static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5192{
5193 struct mem_cgroup *memcg;
5194 loff_t nr_to_skip = *pos;
5195
5196 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5197 if (!m->private)
5198 return ERR_PTR(-ENOMEM);
5199
5200 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5201 do {
5202 int nid;
5203
5204 for_each_node_state(nid, N_MEMORY) {
5205 if (!nr_to_skip--)
5206 return get_lruvec(memcg, nid);
5207 }
5208 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5209
5210 return NULL;
5211}
5212
5213static void lru_gen_seq_stop(struct seq_file *m, void *v)
5214{
5215 if (!IS_ERR_OR_NULL(v))
5216 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5217
5218 kvfree(m->private);
5219 m->private = NULL;
5220}
5221
5222static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5223{
5224 int nid = lruvec_pgdat(v)->node_id;
5225 struct mem_cgroup *memcg = lruvec_memcg(v);
5226
5227 ++*pos;
5228
5229 nid = next_memory_node(nid);
5230 if (nid == MAX_NUMNODES) {
5231 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5232 if (!memcg)
5233 return NULL;
5234
5235 nid = first_memory_node;
5236 }
5237
5238 return get_lruvec(memcg, nid);
5239}
5240
5241static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5242 unsigned long max_seq, unsigned long *min_seq,
5243 unsigned long seq)
5244{
5245 int i;
5246 int type, tier;
5247 int hist = lru_hist_from_seq(seq);
5248 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5249
5250 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5251 seq_printf(m, " %10d", tier);
5252 for (type = 0; type < ANON_AND_FILE; type++) {
5253 const char *s = " ";
5254 unsigned long n[3] = {};
5255
5256 if (seq == max_seq) {
5257 s = "RT ";
5258 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5259 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5260 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5261 s = "rep";
5262 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5263 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5264 if (tier)
5265 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5266 }
5267
5268 for (i = 0; i < 3; i++)
5269 seq_printf(m, " %10lu%c", n[i], s[i]);
5270 }
5271 seq_putc(m, '\n');
5272 }
5273
5274 seq_puts(m, " ");
5275 for (i = 0; i < NR_MM_STATS; i++) {
5276 const char *s = " ";
5277 unsigned long n = 0;
5278
5279 if (seq == max_seq && NR_HIST_GENS == 1) {
5280 s = "LOYNFA";
5281 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5282 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5283 s = "loynfa";
5284 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5285 }
5286
5287 seq_printf(m, " %10lu%c", n, s[i]);
5288 }
5289 seq_putc(m, '\n');
5290}
5291
Yu Zhao642d9862022-09-18 02:00:10 -06005292/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005293static int lru_gen_seq_show(struct seq_file *m, void *v)
5294{
5295 unsigned long seq;
5296 bool full = !debugfs_real_fops(m->file)->write;
5297 struct lruvec *lruvec = v;
5298 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5299 int nid = lruvec_pgdat(lruvec)->node_id;
5300 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5301 DEFINE_MAX_SEQ(lruvec);
5302 DEFINE_MIN_SEQ(lruvec);
5303
5304 if (nid == first_memory_node) {
5305 const char *path = memcg ? m->private : "";
5306
5307#ifdef CONFIG_MEMCG
5308 if (memcg)
5309 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5310#endif
5311 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5312 }
5313
5314 seq_printf(m, " node %5d\n", nid);
5315
5316 if (!full)
5317 seq = min_seq[LRU_GEN_ANON];
5318 else if (max_seq >= MAX_NR_GENS)
5319 seq = max_seq - MAX_NR_GENS + 1;
5320 else
5321 seq = 0;
5322
5323 for (; seq <= max_seq; seq++) {
5324 int type, zone;
5325 int gen = lru_gen_from_seq(seq);
5326 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5327
5328 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5329
5330 for (type = 0; type < ANON_AND_FILE; type++) {
5331 unsigned long size = 0;
5332 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5333
5334 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5335 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5336
5337 seq_printf(m, " %10lu%c", size, mark);
5338 }
5339
5340 seq_putc(m, '\n');
5341
5342 if (full)
5343 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5344 }
5345
5346 return 0;
5347}
5348
5349static const struct seq_operations lru_gen_seq_ops = {
5350 .start = lru_gen_seq_start,
5351 .stop = lru_gen_seq_stop,
5352 .next = lru_gen_seq_next,
5353 .show = lru_gen_seq_show,
5354};
5355
5356static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5357 bool can_swap, bool force_scan)
5358{
5359 DEFINE_MAX_SEQ(lruvec);
5360 DEFINE_MIN_SEQ(lruvec);
5361
5362 if (seq < max_seq)
5363 return 0;
5364
5365 if (seq > max_seq)
5366 return -EINVAL;
5367
5368 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5369 return -ERANGE;
5370
5371 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5372
5373 return 0;
5374}
5375
5376static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5377 int swappiness, unsigned long nr_to_reclaim)
5378{
5379 DEFINE_MAX_SEQ(lruvec);
5380
5381 if (seq + MIN_NR_GENS > max_seq)
5382 return -EINVAL;
5383
5384 sc->nr_reclaimed = 0;
5385
5386 while (!signal_pending(current)) {
5387 DEFINE_MIN_SEQ(lruvec);
5388
5389 if (seq < min_seq[!swappiness])
5390 return 0;
5391
5392 if (sc->nr_reclaimed >= nr_to_reclaim)
5393 return 0;
5394
5395 if (!evict_pages(lruvec, sc, swappiness, NULL))
5396 return 0;
5397
5398 cond_resched();
5399 }
5400
5401 return -EINTR;
5402}
5403
5404static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5405 struct scan_control *sc, int swappiness, unsigned long opt)
5406{
5407 struct lruvec *lruvec;
5408 int err = -EINVAL;
5409 struct mem_cgroup *memcg = NULL;
5410
5411 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5412 return -EINVAL;
5413
5414 if (!mem_cgroup_disabled()) {
5415 rcu_read_lock();
5416 memcg = mem_cgroup_from_id(memcg_id);
5417#ifdef CONFIG_MEMCG
5418 if (memcg && !css_tryget(&memcg->css))
5419 memcg = NULL;
5420#endif
5421 rcu_read_unlock();
5422
5423 if (!memcg)
5424 return -EINVAL;
5425 }
5426
5427 if (memcg_id != mem_cgroup_id(memcg))
5428 goto done;
5429
5430 lruvec = get_lruvec(memcg, nid);
5431
5432 if (swappiness < 0)
5433 swappiness = get_swappiness(lruvec, sc);
5434 else if (swappiness > 200)
5435 goto done;
5436
5437 switch (cmd) {
5438 case '+':
5439 err = run_aging(lruvec, seq, sc, swappiness, opt);
5440 break;
5441 case '-':
5442 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5443 break;
5444 }
5445done:
5446 mem_cgroup_put(memcg);
5447
5448 return err;
5449}
5450
Yu Zhao642d9862022-09-18 02:00:10 -06005451/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005452static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5453 size_t len, loff_t *pos)
5454{
5455 void *buf;
5456 char *cur, *next;
5457 unsigned int flags;
5458 struct blk_plug plug;
5459 int err = -EINVAL;
5460 struct scan_control sc = {
5461 .may_writepage = true,
5462 .may_unmap = true,
5463 .may_swap = true,
5464 .reclaim_idx = MAX_NR_ZONES - 1,
5465 .gfp_mask = GFP_KERNEL,
5466 };
5467
5468 buf = kvmalloc(len + 1, GFP_KERNEL);
5469 if (!buf)
5470 return -ENOMEM;
5471
5472 if (copy_from_user(buf, src, len)) {
5473 kvfree(buf);
5474 return -EFAULT;
5475 }
5476
5477 set_task_reclaim_state(current, &sc.reclaim_state);
5478 flags = memalloc_noreclaim_save();
5479 blk_start_plug(&plug);
5480 if (!set_mm_walk(NULL)) {
5481 err = -ENOMEM;
5482 goto done;
5483 }
5484
5485 next = buf;
5486 next[len] = '\0';
5487
5488 while ((cur = strsep(&next, ",;\n"))) {
5489 int n;
5490 int end;
5491 char cmd;
5492 unsigned int memcg_id;
5493 unsigned int nid;
5494 unsigned long seq;
5495 unsigned int swappiness = -1;
5496 unsigned long opt = -1;
5497
5498 cur = skip_spaces(cur);
5499 if (!*cur)
5500 continue;
5501
5502 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5503 &seq, &end, &swappiness, &end, &opt, &end);
5504 if (n < 4 || cur[end]) {
5505 err = -EINVAL;
5506 break;
5507 }
5508
5509 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5510 if (err)
5511 break;
5512 }
5513done:
5514 clear_mm_walk();
5515 blk_finish_plug(&plug);
5516 memalloc_noreclaim_restore(flags);
5517 set_task_reclaim_state(current, NULL);
5518
5519 kvfree(buf);
5520
5521 return err ? : len;
5522}
5523
5524static int lru_gen_seq_open(struct inode *inode, struct file *file)
5525{
5526 return seq_open(file, &lru_gen_seq_ops);
5527}
5528
5529static const struct file_operations lru_gen_rw_fops = {
5530 .open = lru_gen_seq_open,
5531 .read = seq_read,
5532 .write = lru_gen_seq_write,
5533 .llseek = seq_lseek,
5534 .release = seq_release,
5535};
5536
5537static const struct file_operations lru_gen_ro_fops = {
5538 .open = lru_gen_seq_open,
5539 .read = seq_read,
5540 .llseek = seq_lseek,
5541 .release = seq_release,
5542};
5543
5544/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005545 * initialization
5546 ******************************************************************************/
5547
5548void lru_gen_init_lruvec(struct lruvec *lruvec)
5549{
Yu Zhao430499c2022-09-18 02:00:08 -06005550 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005551 int gen, type, zone;
5552 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5553
5554 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005555 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005556
Yu Zhao430499c2022-09-18 02:00:08 -06005557 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5558 lrugen->timestamps[i] = jiffies;
5559
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005560 for_each_gen_type_zone(gen, type, zone)
5561 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005562
5563 lruvec->mm_state.seq = MIN_NR_GENS;
5564 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005565}
5566
5567#ifdef CONFIG_MEMCG
5568void lru_gen_init_memcg(struct mem_cgroup *memcg)
5569{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005570 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5571 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005572}
5573
5574void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5575{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005576 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005577 int nid;
5578
5579 for_each_node(nid) {
5580 struct lruvec *lruvec = get_lruvec(memcg, nid);
5581
5582 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5583 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005584
5585 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5586 bitmap_free(lruvec->mm_state.filters[i]);
5587 lruvec->mm_state.filters[i] = NULL;
5588 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005589 }
5590}
5591#endif
5592
5593static int __init init_lru_gen(void)
5594{
5595 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5596 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5597
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005598 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5599 pr_err("lru_gen: failed to create sysfs group\n");
5600
Yu Zhao4983c522022-09-18 02:00:09 -06005601 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5602 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5603
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005604 return 0;
5605};
5606late_initcall(init_lru_gen);
5607
Yu Zhao37397872022-09-18 02:00:03 -06005608#else /* !CONFIG_LRU_GEN */
5609
5610static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5611{
5612}
5613
5614static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5615{
5616}
5617
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005618#endif /* CONFIG_LRU_GEN */
5619
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005620static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005621{
5622 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005623 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005624 unsigned long nr_to_scan;
5625 enum lru_list lru;
5626 unsigned long nr_reclaimed = 0;
5627 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005628 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005629 struct blk_plug plug;
5630
Yu Zhao37397872022-09-18 02:00:03 -06005631 if (lru_gen_enabled()) {
5632 lru_gen_shrink_lruvec(lruvec, sc);
5633 return;
5634 }
5635
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005636 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005637
Mel Gormane82e0562013-07-03 15:01:44 -07005638 /* Record the original scan target for proportional adjustments later */
5639 memcpy(targets, nr, sizeof(nr));
5640
Mel Gorman1a501902014-06-04 16:10:49 -07005641 /*
5642 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5643 * event that can occur when there is little memory pressure e.g.
5644 * multiple streaming readers/writers. Hence, we do not abort scanning
5645 * when the requested number of pages are reclaimed when scanning at
5646 * DEF_PRIORITY on the assumption that the fact we are direct
5647 * reclaiming implies that kswapd is not keeping up and it is best to
5648 * do a batch of work at once. For memcg reclaim one check is made to
5649 * abort proportional reclaim if either the file or anon lru has already
5650 * dropped to zero at the first pass.
5651 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005652 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5653 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005654
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005655 blk_start_plug(&plug);
5656 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5657 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005658 unsigned long nr_anon, nr_file, percentage;
5659 unsigned long nr_scanned;
5660
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005661 for_each_evictable_lru(lru) {
5662 if (nr[lru]) {
5663 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5664 nr[lru] -= nr_to_scan;
5665
5666 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005667 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005668 }
5669 }
Mel Gormane82e0562013-07-03 15:01:44 -07005670
Michal Hockobd041732016-12-02 17:26:48 -08005671 cond_resched();
5672
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005673 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005674 continue;
5675
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005676 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005677 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005678 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005679 * proportionally what was requested by get_scan_count(). We
5680 * stop reclaiming one LRU and reduce the amount scanning
5681 * proportional to the original scan target.
5682 */
5683 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5684 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5685
Mel Gorman1a501902014-06-04 16:10:49 -07005686 /*
5687 * It's just vindictive to attack the larger once the smaller
5688 * has gone to zero. And given the way we stop scanning the
5689 * smaller below, this makes sure that we only make one nudge
5690 * towards proportionality once we've got nr_to_reclaim.
5691 */
5692 if (!nr_file || !nr_anon)
5693 break;
5694
Mel Gormane82e0562013-07-03 15:01:44 -07005695 if (nr_file > nr_anon) {
5696 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5697 targets[LRU_ACTIVE_ANON] + 1;
5698 lru = LRU_BASE;
5699 percentage = nr_anon * 100 / scan_target;
5700 } else {
5701 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5702 targets[LRU_ACTIVE_FILE] + 1;
5703 lru = LRU_FILE;
5704 percentage = nr_file * 100 / scan_target;
5705 }
5706
5707 /* Stop scanning the smaller of the LRU */
5708 nr[lru] = 0;
5709 nr[lru + LRU_ACTIVE] = 0;
5710
5711 /*
5712 * Recalculate the other LRU scan count based on its original
5713 * scan target and the percentage scanning already complete
5714 */
5715 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5716 nr_scanned = targets[lru] - nr[lru];
5717 nr[lru] = targets[lru] * (100 - percentage) / 100;
5718 nr[lru] -= min(nr[lru], nr_scanned);
5719
5720 lru += LRU_ACTIVE;
5721 nr_scanned = targets[lru] - nr[lru];
5722 nr[lru] = targets[lru] * (100 - percentage) / 100;
5723 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005724 }
5725 blk_finish_plug(&plug);
5726 sc->nr_reclaimed += nr_reclaimed;
5727
5728 /*
5729 * Even if we did not try to evict anon pages at all, we want to
5730 * rebalance the anon lru active/inactive ratio.
5731 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005732 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5733 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005734 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5735 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005736}
5737
Mel Gorman23b9da52012-05-29 15:06:20 -07005738/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005739static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005740{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005741 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005742 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005743 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005744 return true;
5745
5746 return false;
5747}
5748
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005749/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005750 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5751 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5752 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005753 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005754 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005755 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005756static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005757 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005758 struct scan_control *sc)
5759{
5760 unsigned long pages_for_compaction;
5761 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005762 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005763
5764 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005765 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005766 return false;
5767
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005768 /*
5769 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5770 * number of pages that were scanned. This will return to the caller
5771 * with the risk reclaim/compaction and the resulting allocation attempt
5772 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5773 * allocations through requiring that the full LRU list has been scanned
5774 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5775 * scan, but that approximation was wrong, and there were corner cases
5776 * where always a non-zero amount of pages were scanned.
5777 */
5778 if (!nr_reclaimed)
5779 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005780
Mel Gorman3e7d3442011-01-13 15:45:56 -08005781 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005782 for (z = 0; z <= sc->reclaim_idx; z++) {
5783 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005784 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005785 continue;
5786
5787 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005788 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005789 case COMPACT_CONTINUE:
5790 return false;
5791 default:
5792 /* check next zone */
5793 ;
5794 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005795 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005796
5797 /*
5798 * If we have not reclaimed enough pages for compaction and the
5799 * inactive lists are large enough, continue reclaiming
5800 */
5801 pages_for_compaction = compact_gap(sc->order);
5802 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005803 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005804 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5805
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005806 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005807}
5808
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005809static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005810{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005811 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005812 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005813
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005814 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005815 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005816 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005817 unsigned long reclaimed;
5818 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005819 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005820
Xunlei Pange3336ca2020-09-04 16:35:27 -07005821 /*
5822 * This loop can become CPU-bound when target memcgs
5823 * aren't eligible for reclaim - either because they
5824 * don't have any reclaimable pages, or because their
5825 * memory is explicitly protected. Avoid soft lockups.
5826 */
5827 cond_resched();
5828
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005829 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5830 if (skip)
5831 continue;
5832
Chris Down45c7f7e2020-08-06 23:22:05 -07005833 mem_cgroup_calculate_protection(target_memcg, memcg);
5834
5835 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005836 /*
5837 * Hard protection.
5838 * If there is no reclaimable memory, OOM.
5839 */
5840 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005841 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005842 /*
5843 * Soft protection.
5844 * Respect the protection only as long as
5845 * there is an unprotected supply
5846 * of reclaimable memory from other cgroups.
5847 */
5848 if (!sc->memcg_low_reclaim) {
5849 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005850 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005851 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005852 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005853 }
5854
Johannes Weinerd2af3392019-11-30 17:55:43 -08005855 reclaimed = sc->nr_reclaimed;
5856 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005857
5858 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005859
Johannes Weinerd2af3392019-11-30 17:55:43 -08005860 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5861 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005862
Johannes Weinerd2af3392019-11-30 17:55:43 -08005863 /* Record the group's reclaim efficiency */
5864 vmpressure(sc->gfp_mask, memcg, false,
5865 sc->nr_scanned - scanned,
5866 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005867
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005868 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5869}
5870
Liu Song6c9e09072020-01-30 22:14:08 -08005871static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005872{
5873 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005874 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005875 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005876 bool reclaimable = false;
5877
Johannes Weiner1b051172019-11-30 17:55:52 -08005878 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5879
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005880again:
5881 memset(&sc->nr, 0, sizeof(sc->nr));
5882
5883 nr_reclaimed = sc->nr_reclaimed;
5884 nr_scanned = sc->nr_scanned;
5885
Yu Zhao6d313442022-09-18 02:00:00 -06005886 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005887
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005888 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005889
Johannes Weinerd2af3392019-11-30 17:55:43 -08005890 if (reclaim_state) {
5891 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5892 reclaim_state->reclaimed_slab = 0;
5893 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005894
Johannes Weinerd2af3392019-11-30 17:55:43 -08005895 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005896 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005897 sc->nr_scanned - nr_scanned,
5898 sc->nr_reclaimed - nr_reclaimed);
5899
5900 if (sc->nr_reclaimed - nr_reclaimed)
5901 reclaimable = true;
5902
5903 if (current_is_kswapd()) {
5904 /*
5905 * If reclaim is isolating dirty pages under writeback,
5906 * it implies that the long-lived page allocation rate
5907 * is exceeding the page laundering rate. Either the
5908 * global limits are not being effective at throttling
5909 * processes due to the page distribution throughout
5910 * zones or there is heavy usage of a slow backing
5911 * device. The only option is to throttle from reclaim
5912 * context which is not ideal as there is no guarantee
5913 * the dirtying process is throttled in the same way
5914 * balance_dirty_pages() manages.
5915 *
5916 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5917 * count the number of pages under pages flagged for
5918 * immediate reclaim and stall if any are encountered
5919 * in the nr_immediate check below.
5920 */
5921 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5922 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005923
Johannes Weinerd2af3392019-11-30 17:55:43 -08005924 /* Allow kswapd to start writing pages during reclaim.*/
5925 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5926 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005927
5928 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005929 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005930 * reclaim and under writeback (nr_immediate), it
5931 * implies that pages are cycling through the LRU
5932 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005933 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005934 if (sc->nr.immediate)
5935 congestion_wait(BLK_RW_ASYNC, HZ/10);
5936 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005937
Johannes Weinerd2af3392019-11-30 17:55:43 -08005938 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005939 * Tag a node/memcg as congested if all the dirty pages
5940 * scanned were backed by a congested BDI and
5941 * wait_iff_congested will stall.
5942 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005943 * Legacy memcg will stall in page writeback so avoid forcibly
5944 * stalling in wait_iff_congested().
5945 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005946 if ((current_is_kswapd() ||
5947 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005948 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005949 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005950
5951 /*
5952 * Stall direct reclaim for IO completions if underlying BDIs
5953 * and node is congested. Allow kswapd to continue until it
5954 * starts encountering unqueued dirty pages or cycling through
5955 * the LRU too quickly.
5956 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005957 if (!current_is_kswapd() && current_may_throttle() &&
5958 !sc->hibernation_mode &&
5959 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005960 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5961
5962 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5963 sc))
5964 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005965
Johannes Weinerc73322d2017-05-03 14:51:51 -07005966 /*
5967 * Kswapd gives up on balancing particular nodes after too
5968 * many failures to reclaim anything from them and goes to
5969 * sleep. On reclaim progress, reset the failure counter. A
5970 * successful direct reclaim run will revive a dormant kswapd.
5971 */
5972 if (reclaimable)
5973 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005974}
5975
Vlastimil Babka53853e22014-10-09 15:27:02 -07005976/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005977 * Returns true if compaction should go ahead for a costly-order request, or
5978 * the allocation would already succeed without compaction. Return false if we
5979 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005980 */
Mel Gorman4f588332016-07-28 15:46:38 -07005981static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005982{
Mel Gorman31483b62016-07-28 15:45:46 -07005983 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005984 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005985
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005986 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5987 if (suitable == COMPACT_SUCCESS)
5988 /* Allocation should succeed already. Don't reclaim. */
5989 return true;
5990 if (suitable == COMPACT_SKIPPED)
5991 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005992 return false;
5993
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005994 /*
5995 * Compaction is already possible, but it takes time to run and there
5996 * are potentially other callers using the pages just freed. So proceed
5997 * with reclaim to make a buffer of free pages available to give
5998 * compaction a reasonable chance of completing and allocating the page.
5999 * Note that we won't actually reclaim the whole buffer in one attempt
6000 * as the target watermark in should_continue_reclaim() is lower. But if
6001 * we are already above the high+gap watermark, don't reclaim at all.
6002 */
6003 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6004
6005 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006006}
6007
Linus Torvalds1da177e2005-04-16 15:20:36 -07006008/*
6009 * This is the direct reclaim path, for page-allocating processes. We only
6010 * try to reclaim pages from zones which will satisfy the caller's allocation
6011 * request.
6012 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006013 * If a zone is deemed to be full of pinned pages then just give it a light
6014 * scan then give up on it.
6015 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006016static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006017{
Mel Gormandd1a2392008-04-28 02:12:17 -07006018 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006019 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006020 unsigned long nr_soft_reclaimed;
6021 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006022 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006023 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006024
Mel Gormancc715d92012-03-21 16:34:00 -07006025 /*
6026 * If the number of buffer_heads in the machine exceeds the maximum
6027 * allowed level, force direct reclaim to scan the highmem zone as
6028 * highmem pages could be pinning lowmem pages storing buffer_heads
6029 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006030 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006031 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006032 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006033 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006034 }
Mel Gormancc715d92012-03-21 16:34:00 -07006035
Mel Gormand4debc62010-08-09 17:19:29 -07006036 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006037 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006038 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006039 * Take care memory controller reclaiming has small influence
6040 * to global LRU.
6041 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006042 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006043 if (!cpuset_zone_allowed(zone,
6044 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006045 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006046
Johannes Weiner0b064962014-08-06 16:06:12 -07006047 /*
6048 * If we already have plenty of memory free for
6049 * compaction in this zone, don't free any more.
6050 * Even though compaction is invoked for any
6051 * non-zero order, only frequent costly order
6052 * reclamation is disruptive enough to become a
6053 * noticeable problem, like transparent huge
6054 * page allocations.
6055 */
6056 if (IS_ENABLED(CONFIG_COMPACTION) &&
6057 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006058 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006059 sc->compaction_ready = true;
6060 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006061 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006062
Andrew Morton0608f432013-09-24 15:27:41 -07006063 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006064 * Shrink each node in the zonelist once. If the
6065 * zonelist is ordered by zone (not the default) then a
6066 * node may be shrunk multiple times but in that case
6067 * the user prefers lower zones being preserved.
6068 */
6069 if (zone->zone_pgdat == last_pgdat)
6070 continue;
6071
6072 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006073 * This steals pages from memory cgroups over softlimit
6074 * and returns the number of reclaimed pages and
6075 * scanned pages. This works for global memory pressure
6076 * and balancing, not for a memcg's limit.
6077 */
6078 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006079 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006080 sc->order, sc->gfp_mask,
6081 &nr_soft_scanned);
6082 sc->nr_reclaimed += nr_soft_reclaimed;
6083 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006084 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006085 }
Nick Piggin408d8542006-09-25 23:31:27 -07006086
Mel Gorman79dafcd2016-07-28 15:45:53 -07006087 /* See comment about same check for global reclaim above */
6088 if (zone->zone_pgdat == last_pgdat)
6089 continue;
6090 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006091 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006092 }
Mel Gormane0c23272011-10-31 17:09:33 -07006093
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006094 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006095 * Restore to original mask to avoid the impact on the caller if we
6096 * promoted it to __GFP_HIGHMEM.
6097 */
6098 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006099}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006100
Johannes Weinerb9107182019-11-30 17:55:59 -08006101static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006102{
Johannes Weinerb9107182019-11-30 17:55:59 -08006103 struct lruvec *target_lruvec;
6104 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006105
Yu Zhao37397872022-09-18 02:00:03 -06006106 if (lru_gen_enabled())
6107 return;
6108
Johannes Weinerb9107182019-11-30 17:55:59 -08006109 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006110 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6111 target_lruvec->refaults[0] = refaults;
6112 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6113 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006114}
6115
Linus Torvalds1da177e2005-04-16 15:20:36 -07006116/*
6117 * This is the main entry point to direct page reclaim.
6118 *
6119 * If a full scan of the inactive list fails to free enough memory then we
6120 * are "out of memory" and something needs to be killed.
6121 *
6122 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6123 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006124 * caller can't do much about. We kick the writeback threads and take explicit
6125 * naps in the hope that some of these pages can be written. But if the
6126 * allocating task holds filesystem locks which prevent writeout this might not
6127 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006128 *
6129 * returns: 0, if no pages reclaimed
6130 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006131 */
Mel Gormandac1d272008-04-28 02:12:12 -07006132static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006133 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006134{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006135 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006136 pg_data_t *last_pgdat;
6137 struct zoneref *z;
6138 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006139retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006140 delayacct_freepages_start();
6141
Johannes Weinerb5ead352019-11-30 17:55:40 -08006142 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006143 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006144
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006145 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006146 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6147 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006148 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006149 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006150
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006151 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006152 break;
6153
6154 if (sc->compaction_ready)
6155 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006156
6157 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006158 * If we're getting trouble reclaiming, start doing
6159 * writepage even in laptop mode.
6160 */
6161 if (sc->priority < DEF_PRIORITY - 2)
6162 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006163 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006164
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006165 last_pgdat = NULL;
6166 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6167 sc->nodemask) {
6168 if (zone->zone_pgdat == last_pgdat)
6169 continue;
6170 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006171
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006172 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006173
6174 if (cgroup_reclaim(sc)) {
6175 struct lruvec *lruvec;
6176
6177 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6178 zone->zone_pgdat);
6179 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6180 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006181 }
6182
Keika Kobayashi873b4772008-07-25 01:48:52 -07006183 delayacct_freepages_end();
6184
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006185 if (sc->nr_reclaimed)
6186 return sc->nr_reclaimed;
6187
Mel Gorman0cee34f2012-01-12 17:19:49 -08006188 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006189 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006190 return 1;
6191
Johannes Weinerb91ac372019-11-30 17:56:02 -08006192 /*
6193 * We make inactive:active ratio decisions based on the node's
6194 * composition of memory, but a restrictive reclaim_idx or a
6195 * memory.low cgroup setting can exempt large amounts of
6196 * memory from reclaim. Neither of which are very common, so
6197 * instead of doing costly eligibility calculations of the
6198 * entire cgroup subtree up front, we assume the estimates are
6199 * good, and retry with forcible deactivation if that fails.
6200 */
6201 if (sc->skipped_deactivate) {
6202 sc->priority = initial_priority;
6203 sc->force_deactivate = 1;
6204 sc->skipped_deactivate = 0;
6205 goto retry;
6206 }
6207
Johannes Weiner241994ed2015-02-11 15:26:06 -08006208 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006209 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006210 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006211 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006212 sc->memcg_low_reclaim = 1;
6213 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006214 goto retry;
6215 }
6216
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006217 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006218}
6219
Johannes Weinerc73322d2017-05-03 14:51:51 -07006220static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006221{
6222 struct zone *zone;
6223 unsigned long pfmemalloc_reserve = 0;
6224 unsigned long free_pages = 0;
6225 int i;
6226 bool wmark_ok;
6227
Johannes Weinerc73322d2017-05-03 14:51:51 -07006228 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6229 return true;
6230
Mel Gorman55150612012-07-31 16:44:35 -07006231 for (i = 0; i <= ZONE_NORMAL; i++) {
6232 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006233 if (!managed_zone(zone))
6234 continue;
6235
6236 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006237 continue;
6238
Mel Gorman55150612012-07-31 16:44:35 -07006239 pfmemalloc_reserve += min_wmark_pages(zone);
6240 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6241 }
6242
Mel Gorman675becc2014-06-04 16:07:35 -07006243 /* If there are no reserves (unexpected config) then do not throttle */
6244 if (!pfmemalloc_reserve)
6245 return true;
6246
Mel Gorman55150612012-07-31 16:44:35 -07006247 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6248
6249 /* kswapd must be awake if processes are being throttled */
6250 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006251 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6252 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006253
Mel Gorman55150612012-07-31 16:44:35 -07006254 wake_up_interruptible(&pgdat->kswapd_wait);
6255 }
6256
6257 return wmark_ok;
6258}
6259
6260/*
6261 * Throttle direct reclaimers if backing storage is backed by the network
6262 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6263 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006264 * when the low watermark is reached.
6265 *
6266 * Returns true if a fatal signal was delivered during throttling. If this
6267 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006268 */
Mel Gorman50694c22012-11-26 16:29:48 -08006269static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006270 nodemask_t *nodemask)
6271{
Mel Gorman675becc2014-06-04 16:07:35 -07006272 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006273 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006274 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006275
6276 /*
6277 * Kernel threads should not be throttled as they may be indirectly
6278 * responsible for cleaning pages necessary for reclaim to make forward
6279 * progress. kjournald for example may enter direct reclaim while
6280 * committing a transaction where throttling it could forcing other
6281 * processes to block on log_wait_commit().
6282 */
6283 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006284 goto out;
6285
6286 /*
6287 * If a fatal signal is pending, this process should not throttle.
6288 * It should return quickly so it can exit and free its memory
6289 */
6290 if (fatal_signal_pending(current))
6291 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006292
Mel Gorman675becc2014-06-04 16:07:35 -07006293 /*
6294 * Check if the pfmemalloc reserves are ok by finding the first node
6295 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6296 * GFP_KERNEL will be required for allocating network buffers when
6297 * swapping over the network so ZONE_HIGHMEM is unusable.
6298 *
6299 * Throttling is based on the first usable node and throttled processes
6300 * wait on a queue until kswapd makes progress and wakes them. There
6301 * is an affinity then between processes waking up and where reclaim
6302 * progress has been made assuming the process wakes on the same node.
6303 * More importantly, processes running on remote nodes will not compete
6304 * for remote pfmemalloc reserves and processes on different nodes
6305 * should make reasonable progress.
6306 */
6307 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006308 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006309 if (zone_idx(zone) > ZONE_NORMAL)
6310 continue;
6311
6312 /* Throttle based on the first usable node */
6313 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006314 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006315 goto out;
6316 break;
6317 }
6318
6319 /* If no zone was usable by the allocation flags then do not throttle */
6320 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006321 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006322
Mel Gorman68243e72012-07-31 16:44:39 -07006323 /* Account for the throttling */
6324 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6325
Mel Gorman55150612012-07-31 16:44:35 -07006326 /*
6327 * If the caller cannot enter the filesystem, it's possible that it
6328 * is due to the caller holding an FS lock or performing a journal
6329 * transaction in the case of a filesystem like ext[3|4]. In this case,
6330 * it is not safe to block on pfmemalloc_wait as kswapd could be
6331 * blocked waiting on the same lock. Instead, throttle for up to a
6332 * second before continuing.
6333 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006334 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006335 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006336 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006337 else
6338 /* Throttle until kswapd wakes the process */
6339 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6340 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006341
Mel Gorman50694c22012-11-26 16:29:48 -08006342 if (fatal_signal_pending(current))
6343 return true;
6344
6345out:
6346 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006347}
6348
Mel Gormandac1d272008-04-28 02:12:12 -07006349unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006350 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006351{
Mel Gorman33906bc2010-08-09 17:19:16 -07006352 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006353 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006354 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006355 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006356 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006357 .order = order,
6358 .nodemask = nodemask,
6359 .priority = DEF_PRIORITY,
6360 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006361 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006362 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006363 };
6364
Mel Gorman55150612012-07-31 16:44:35 -07006365 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006366 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6367 * Confirm they are large enough for max values.
6368 */
6369 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6370 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6371 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6372
6373 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006374 * Do not enter reclaim if fatal signal was delivered while throttled.
6375 * 1 is returned so that the page allocator does not OOM kill at this
6376 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006377 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006378 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006379 return 1;
6380
Andrew Morton1732d2b012019-07-16 16:26:15 -07006381 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006382 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006383
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006384 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006385
6386 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006387 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006388
6389 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006390}
6391
Andrew Mortonc255a452012-07-31 16:43:02 -07006392#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006393
Michal Hockod2e5fb92019-08-30 16:04:50 -07006394/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006395unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006396 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006397 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006398 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006399{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006400 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006401 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006402 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006403 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006404 .may_writepage = !laptop_mode,
6405 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006406 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006407 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006408 };
Ying Han0ae5e892011-05-26 16:25:25 -07006409
Michal Hockod2e5fb92019-08-30 16:04:50 -07006410 WARN_ON_ONCE(!current->reclaim_state);
6411
Balbir Singh4e416952009-09-23 15:56:39 -07006412 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6413 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006414
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006415 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006416 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006417
Balbir Singh4e416952009-09-23 15:56:39 -07006418 /*
6419 * NOTE: Although we can get the priority field, using it
6420 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006421 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006422 * will pick up pages from other mem cgroup's as well. We hack
6423 * the priority and make it zero.
6424 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006425 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006426
6427 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6428
Ying Han0ae5e892011-05-26 16:25:25 -07006429 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006430
Balbir Singh4e416952009-09-23 15:56:39 -07006431 return sc.nr_reclaimed;
6432}
6433
Johannes Weiner72835c82012-01-12 17:18:32 -08006434unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006435 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006436 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006437 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006438{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006439 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006440 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006441 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006442 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006443 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006444 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006445 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006446 .target_mem_cgroup = memcg,
6447 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006448 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006449 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006450 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006451 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006452 /*
6453 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6454 * equal pressure on all the nodes. This is based on the assumption that
6455 * the reclaim does not bail out early.
6456 */
6457 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006458
Andrew Morton1732d2b012019-07-16 16:26:15 -07006459 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006460 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006461 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006462
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006463 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006464
Vlastimil Babka499118e2017-05-08 15:59:50 -07006465 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006466 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006467 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006468
6469 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006470}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006471EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006472#endif
6473
Yu Zhao37397872022-09-18 02:00:03 -06006474static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006475{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006476 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006477 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006478
Yu Zhao37397872022-09-18 02:00:03 -06006479 if (lru_gen_enabled()) {
6480 lru_gen_age_node(pgdat, sc);
6481 return;
6482 }
6483
Dave Hansen2f368a92021-09-02 14:59:23 -07006484 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006485 return;
6486
Johannes Weinerb91ac372019-11-30 17:56:02 -08006487 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6488 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6489 return;
6490
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006491 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6492 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006493 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6494 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6495 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006496 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6497 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006498}
6499
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006500static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006501{
6502 int i;
6503 struct zone *zone;
6504
6505 /*
6506 * Check for watermark boosts top-down as the higher zones
6507 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006508 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006509 * start prematurely when there is no boosting and a lower
6510 * zone is balanced.
6511 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006512 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006513 zone = pgdat->node_zones + i;
6514 if (!managed_zone(zone))
6515 continue;
6516
6517 if (zone->watermark_boost)
6518 return true;
6519 }
6520
6521 return false;
6522}
6523
Mel Gormane716f2e2017-05-03 14:53:45 -07006524/*
6525 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006526 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006527 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006528static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006529{
Mel Gormane716f2e2017-05-03 14:53:45 -07006530 int i;
6531 unsigned long mark = -1;
6532 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006533
Mel Gorman1c308442018-12-28 00:35:52 -08006534 /*
6535 * Check watermarks bottom-up as lower zones are more likely to
6536 * meet watermarks.
6537 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006538 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006539 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006540
Mel Gormane716f2e2017-05-03 14:53:45 -07006541 if (!managed_zone(zone))
6542 continue;
6543
6544 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006545 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006546 return true;
6547 }
6548
6549 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006550 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006551 * need balancing by definition. This can happen if a zone-restricted
6552 * allocation tries to wake a remote kswapd.
6553 */
6554 if (mark == -1)
6555 return true;
6556
6557 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006558}
6559
Mel Gorman631b6e02017-05-03 14:53:41 -07006560/* Clear pgdat state for congested, dirty or under writeback. */
6561static void clear_pgdat_congested(pg_data_t *pgdat)
6562{
Johannes Weiner1b051172019-11-30 17:55:52 -08006563 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6564
6565 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006566 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6567 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6568}
6569
Mel Gorman1741c872011-01-13 15:46:21 -08006570/*
Mel Gorman55150612012-07-31 16:44:35 -07006571 * Prepare kswapd for sleeping. This verifies that there are no processes
6572 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6573 *
6574 * Returns true if kswapd is ready to sleep
6575 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006576static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6577 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006578{
Mel Gorman55150612012-07-31 16:44:35 -07006579 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006580 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006581 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006582 * race between when kswapd checks the watermarks and a process gets
6583 * throttled. There is also a potential race if processes get
6584 * throttled, kswapd wakes, a large process exits thereby balancing the
6585 * zones, which causes kswapd to exit balance_pgdat() before reaching
6586 * the wake up checks. If kswapd is going to sleep, no process should
6587 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6588 * the wake up is premature, processes will wake kswapd and get
6589 * throttled again. The difference from wake ups in balance_pgdat() is
6590 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006591 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006592 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6593 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006594
Johannes Weinerc73322d2017-05-03 14:51:51 -07006595 /* Hopeless node, leave it to direct reclaim */
6596 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6597 return true;
6598
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006599 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006600 clear_pgdat_congested(pgdat);
6601 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006602 }
6603
Shantanu Goel333b0a42017-05-03 14:53:38 -07006604 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006605}
6606
Linus Torvalds1da177e2005-04-16 15:20:36 -07006607/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006608 * kswapd shrinks a node of pages that are at or below the highest usable
6609 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006610 *
6611 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006612 * reclaim or if the lack of progress was due to pages under writeback.
6613 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006614 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006615static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006616 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006617{
Mel Gorman1d82de62016-07-28 15:45:43 -07006618 struct zone *zone;
6619 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006620
Mel Gorman1d82de62016-07-28 15:45:43 -07006621 /* Reclaim a number of pages proportional to the number of zones */
6622 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006623 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006624 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006625 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006626 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006627
Mel Gorman1d82de62016-07-28 15:45:43 -07006628 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006629 }
6630
Mel Gorman1d82de62016-07-28 15:45:43 -07006631 /*
6632 * Historically care was taken to put equal pressure on all zones but
6633 * now pressure is applied based on node LRU order.
6634 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006635 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006636
6637 /*
6638 * Fragmentation may mean that the system cannot be rebalanced for
6639 * high-order allocations. If twice the allocation size has been
6640 * reclaimed then recheck watermarks only at order-0 to prevent
6641 * excessive reclaim. Assume that a process requested a high-order
6642 * can direct reclaim/compact.
6643 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006644 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006645 sc->order = 0;
6646
Mel Gormanb8e83b92013-07-03 15:01:45 -07006647 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006648}
6649
Mel Gormanc49c2c42021-06-28 19:42:21 -07006650/* Page allocator PCP high watermark is lowered if reclaim is active. */
6651static inline void
6652update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6653{
6654 int i;
6655 struct zone *zone;
6656
6657 for (i = 0; i <= highest_zoneidx; i++) {
6658 zone = pgdat->node_zones + i;
6659
6660 if (!managed_zone(zone))
6661 continue;
6662
6663 if (active)
6664 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6665 else
6666 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6667 }
6668}
6669
6670static inline void
6671set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6672{
6673 update_reclaim_active(pgdat, highest_zoneidx, true);
6674}
6675
6676static inline void
6677clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6678{
6679 update_reclaim_active(pgdat, highest_zoneidx, false);
6680}
6681
Mel Gorman75485362013-07-03 15:01:42 -07006682/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006683 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6684 * that are eligible for use by the caller until at least one zone is
6685 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006686 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006687 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006688 *
6689 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006690 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006691 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006692 * or lower is eligible for reclaim until at least one usable zone is
6693 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006694 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006695static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006696{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006697 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006698 unsigned long nr_soft_reclaimed;
6699 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006700 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006701 unsigned long nr_boost_reclaim;
6702 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6703 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006704 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006705 struct scan_control sc = {
6706 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006707 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006708 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006709 };
Omar Sandoval93781322018-06-07 17:07:02 -07006710
Andrew Morton1732d2b012019-07-16 16:26:15 -07006711 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006712 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006713 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006714
Christoph Lameterf8891e52006-06-30 01:55:45 -07006715 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006716
Mel Gorman1c308442018-12-28 00:35:52 -08006717 /*
6718 * Account for the reclaim boost. Note that the zone boost is left in
6719 * place so that parallel allocations that are near the watermark will
6720 * stall or direct reclaim until kswapd is finished.
6721 */
6722 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006723 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006724 zone = pgdat->node_zones + i;
6725 if (!managed_zone(zone))
6726 continue;
6727
6728 nr_boost_reclaim += zone->watermark_boost;
6729 zone_boosts[i] = zone->watermark_boost;
6730 }
6731 boosted = nr_boost_reclaim;
6732
6733restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006734 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006735 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006736 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006737 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006738 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006739 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006740 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006741
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006742 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006743
Mel Gorman86c79f62016-07-28 15:45:59 -07006744 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006745 * If the number of buffer_heads exceeds the maximum allowed
6746 * then consider reclaiming from all zones. This has a dual
6747 * purpose -- on 64-bit systems it is expected that
6748 * buffer_heads are stripped during active rotation. On 32-bit
6749 * systems, highmem pages can pin lowmem memory and shrinking
6750 * buffers can relieve lowmem pressure. Reclaim may still not
6751 * go ahead if all eligible zones for the original allocation
6752 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006753 */
6754 if (buffer_heads_over_limit) {
6755 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6756 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006757 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006758 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006759
Mel Gorman970a39a2016-07-28 15:46:35 -07006760 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006761 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006762 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006763 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006764
Mel Gorman86c79f62016-07-28 15:45:59 -07006765 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006766 * If the pgdat is imbalanced then ignore boosting and preserve
6767 * the watermarks for a later time and restart. Note that the
6768 * zone watermarks will be still reset at the end of balancing
6769 * on the grounds that the normal reclaim should be enough to
6770 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006771 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006772 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006773 if (!balanced && nr_boost_reclaim) {
6774 nr_boost_reclaim = 0;
6775 goto restart;
6776 }
6777
6778 /*
6779 * If boosting is not active then only reclaim if there are no
6780 * eligible zones. Note that sc.reclaim_idx is not used as
6781 * buffer_heads_over_limit may have adjusted it.
6782 */
6783 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006784 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006785
Mel Gorman1c308442018-12-28 00:35:52 -08006786 /* Limit the priority of boosting to avoid reclaim writeback */
6787 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6788 raise_priority = false;
6789
6790 /*
6791 * Do not writeback or swap pages for boosted reclaim. The
6792 * intent is to relieve pressure not issue sub-optimal IO
6793 * from reclaim context. If no pages are reclaimed, the
6794 * reclaim will be aborted.
6795 */
6796 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6797 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006798
Linus Torvalds1da177e2005-04-16 15:20:36 -07006799 /*
Yu Zhao37397872022-09-18 02:00:03 -06006800 * Do some background aging, to give pages a chance to be
6801 * referenced before reclaiming. All pages are rotated
6802 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006803 */
Yu Zhao37397872022-09-18 02:00:03 -06006804 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006805
6806 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006807 * If we're getting trouble reclaiming, start doing writepage
6808 * even in laptop mode.
6809 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006810 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006811 sc.may_writepage = 1;
6812
Mel Gorman1d82de62016-07-28 15:45:43 -07006813 /* Call soft limit reclaim before calling shrink_node. */
6814 sc.nr_scanned = 0;
6815 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006816 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006817 sc.gfp_mask, &nr_soft_scanned);
6818 sc.nr_reclaimed += nr_soft_reclaimed;
6819
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006820 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006821 * There should be no need to raise the scanning priority if
6822 * enough pages are already being scanned that that high
6823 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006824 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006825 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006826 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006827
6828 /*
6829 * If the low watermark is met there is no need for processes
6830 * to be throttled on pfmemalloc_wait as they should not be
6831 * able to safely make forward progress. Wake them
6832 */
6833 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006834 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006835 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006836
Mel Gormanb8e83b92013-07-03 15:01:45 -07006837 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006838 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006839 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006840 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006841 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006842 break;
6843
6844 /*
6845 * Raise priority if scanning rate is too low or there was no
6846 * progress in reclaiming pages
6847 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006848 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006849 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6850
6851 /*
6852 * If reclaim made no progress for a boost, stop reclaim as
6853 * IO cannot be queued and it could be an infinite loop in
6854 * extreme circumstances.
6855 */
6856 if (nr_boost_reclaim && !nr_reclaimed)
6857 break;
6858
Johannes Weinerc73322d2017-05-03 14:51:51 -07006859 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006860 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006861 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006862
Johannes Weinerc73322d2017-05-03 14:51:51 -07006863 if (!sc.nr_reclaimed)
6864 pgdat->kswapd_failures++;
6865
Mel Gormanb8e83b92013-07-03 15:01:45 -07006866out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006867 clear_reclaim_active(pgdat, highest_zoneidx);
6868
Mel Gorman1c308442018-12-28 00:35:52 -08006869 /* If reclaim was boosted, account for the reclaim done in this pass */
6870 if (boosted) {
6871 unsigned long flags;
6872
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006873 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006874 if (!zone_boosts[i])
6875 continue;
6876
6877 /* Increments are under the zone lock */
6878 zone = pgdat->node_zones + i;
6879 spin_lock_irqsave(&zone->lock, flags);
6880 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6881 spin_unlock_irqrestore(&zone->lock, flags);
6882 }
6883
6884 /*
6885 * As there is now likely space, wakeup kcompact to defragment
6886 * pageblocks.
6887 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006888 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006889 }
6890
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006891 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006892 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006893 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006894 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006895
Mel Gorman0abdee22011-01-13 15:46:22 -08006896 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006897 * Return the order kswapd stopped reclaiming at as
6898 * prepare_kswapd_sleep() takes it into account. If another caller
6899 * entered the allocator slow path while kswapd was awake, order will
6900 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006901 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006902 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006903}
6904
Mel Gormane716f2e2017-05-03 14:53:45 -07006905/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006906 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6907 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6908 * not a valid index then either kswapd runs for first time or kswapd couldn't
6909 * sleep after previous reclaim attempt (node is still unbalanced). In that
6910 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006911 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006912static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6913 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006914{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006915 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006916
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006917 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006918}
6919
Mel Gorman38087d92016-07-28 15:45:49 -07006920static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006921 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006922{
6923 long remaining = 0;
6924 DEFINE_WAIT(wait);
6925
6926 if (freezing(current) || kthread_should_stop())
6927 return;
6928
6929 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6930
Shantanu Goel333b0a42017-05-03 14:53:38 -07006931 /*
6932 * Try to sleep for a short interval. Note that kcompactd will only be
6933 * woken if it is possible to sleep for a short interval. This is
6934 * deliberate on the assumption that if reclaim cannot keep an
6935 * eligible zone balanced that it's also unlikely that compaction will
6936 * succeed.
6937 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006938 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006939 /*
6940 * Compaction records what page blocks it recently failed to
6941 * isolate pages from and skips them in the future scanning.
6942 * When kswapd is going to sleep, it is reasonable to assume
6943 * that pages and compaction may succeed so reset the cache.
6944 */
6945 reset_isolation_suitable(pgdat);
6946
6947 /*
6948 * We have freed the memory, now we should compact it to make
6949 * allocation of the requested order possible.
6950 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006951 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006952
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006953 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006954
6955 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006956 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006957 * order. The values will either be from a wakeup request or
6958 * the previous request that slept prematurely.
6959 */
6960 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006961 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6962 kswapd_highest_zoneidx(pgdat,
6963 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006964
6965 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6966 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006967 }
6968
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006969 finish_wait(&pgdat->kswapd_wait, &wait);
6970 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6971 }
6972
6973 /*
6974 * After a short sleep, check if it was a premature sleep. If not, then
6975 * go fully to sleep until explicitly woken up.
6976 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006977 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006978 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006979 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6980
6981 /*
6982 * vmstat counters are not perfectly accurate and the estimated
6983 * value for counters such as NR_FREE_PAGES can deviate from the
6984 * true value by nr_online_cpus * threshold. To avoid the zone
6985 * watermarks being breached while under pressure, we reduce the
6986 * per-cpu vmstat threshold while kswapd is awake and restore
6987 * them before going back to sleep.
6988 */
6989 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006990
6991 if (!kthread_should_stop())
6992 schedule();
6993
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006994 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6995 } else {
6996 if (remaining)
6997 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6998 else
6999 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7000 }
7001 finish_wait(&pgdat->kswapd_wait, &wait);
7002}
7003
Linus Torvalds1da177e2005-04-16 15:20:36 -07007004/*
7005 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007006 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007007 *
7008 * This basically trickles out pages so that we have _some_
7009 * free memory available even if there is no other activity
7010 * that frees anything up. This is needed for things like routing
7011 * etc, where we otherwise might have all activity going on in
7012 * asynchronous contexts that cannot page things out.
7013 *
7014 * If there are applications that are active memory-allocators
7015 * (most normal use), this basically shouldn't matter.
7016 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307017int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007018{
Mel Gormane716f2e2017-05-03 14:53:45 -07007019 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007020 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007021 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007022 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307023 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007024
Rusty Russell174596a2009-01-01 10:12:29 +10307025 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007026 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007027
7028 /*
7029 * Tell the memory management that we're a "memory allocator",
7030 * and that if we need more memory we should get access to it
7031 * regardless (see "__alloc_pages()"). "kswapd" should
7032 * never get caught in the normal page freeing logic.
7033 *
7034 * (Kswapd normally doesn't need memory anyway, but sometimes
7035 * you need a small amount of memory in order to be able to
7036 * page out something else, and this flag essentially protects
7037 * us from recursively trying to free more memory as we're
7038 * trying to free the first piece of memory in the first place).
7039 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007040 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007041 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007042
Qian Cai5644e1fb2020-04-01 21:10:12 -07007043 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007044 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007045 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007046 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007047
Qian Cai5644e1fb2020-04-01 21:10:12 -07007048 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007049 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7050 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007051
Mel Gorman38087d92016-07-28 15:45:49 -07007052kswapd_try_sleep:
7053 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007054 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007055
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007056 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007057 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007058 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7059 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007060 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007061 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007062
David Rientjes8fe23e02009-12-14 17:58:33 -08007063 ret = try_to_freeze();
7064 if (kthread_should_stop())
7065 break;
7066
7067 /*
7068 * We can speed up thawing tasks if we don't call balance_pgdat
7069 * after returning from the refrigerator
7070 */
Mel Gorman38087d92016-07-28 15:45:49 -07007071 if (ret)
7072 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007073
Mel Gorman38087d92016-07-28 15:45:49 -07007074 /*
7075 * Reclaim begins at the requested order but if a high-order
7076 * reclaim fails then kswapd falls back to reclaiming for
7077 * order-0. If that happens, kswapd will consider sleeping
7078 * for the order it finished reclaiming at (reclaim_order)
7079 * but kcompactd is woken to compact for the original
7080 * request (alloc_order).
7081 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007082 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007083 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007084 reclaim_order = balance_pgdat(pgdat, alloc_order,
7085 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007086 if (reclaim_order < alloc_order)
7087 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007088 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007089
Johannes Weiner71abdc12014-06-06 14:35:35 -07007090 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007091
Linus Torvalds1da177e2005-04-16 15:20:36 -07007092 return 0;
7093}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307094EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007095
7096/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007097 * A zone is low on free memory or too fragmented for high-order memory. If
7098 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7099 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7100 * has failed or is not needed, still wake up kcompactd if only compaction is
7101 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007102 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007103void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007104 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007105{
7106 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007107 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007108
Mel Gorman6aa303d2016-09-01 16:14:55 -07007109 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007110 return;
7111
David Rientjes5ecd9d42018-04-05 16:25:16 -07007112 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007113 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007114
Qian Cai5644e1fb2020-04-01 21:10:12 -07007115 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007116 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007117
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007118 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7119 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007120
7121 if (READ_ONCE(pgdat->kswapd_order) < order)
7122 WRITE_ONCE(pgdat->kswapd_order, order);
7123
Con Kolivas8d0986e2005-09-13 01:25:07 -07007124 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007125 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007126
David Rientjes5ecd9d42018-04-05 16:25:16 -07007127 /* Hopeless node, leave it to direct reclaim if possible */
7128 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007129 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7130 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007131 /*
7132 * There may be plenty of free memory available, but it's too
7133 * fragmented for high-order allocations. Wake up kcompactd
7134 * and rely on compaction_suitable() to determine if it's
7135 * needed. If it fails, it will defer subsequent attempts to
7136 * ratelimit its work.
7137 */
7138 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007139 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007140 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007141 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007142
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007143 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007144 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007145 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007146}
7147
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007148#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007149/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007150 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007151 * freed pages.
7152 *
7153 * Rather than trying to age LRUs the aim is to preserve the overall
7154 * LRU order by reclaiming preferentially
7155 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007156 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007157unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007158{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007159 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007160 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007161 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007162 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007163 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007164 .may_writepage = 1,
7165 .may_unmap = 1,
7166 .may_swap = 1,
7167 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007168 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007169 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007170 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007171 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007172
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007173 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007174 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007175 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007176
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007177 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007178
Andrew Morton1732d2b012019-07-16 16:26:15 -07007179 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007180 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007181 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007182
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007183 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007184}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007185#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007186
Yasunori Goto3218ae12006-06-27 02:53:33 -07007187/*
7188 * This kswapd start function will be called by init and node-hot-add.
7189 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7190 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007191void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007192{
7193 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307194 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007195
7196 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007197 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007198
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307199 trace_android_vh_kswapd_per_node(nid, &skip, true);
7200 if (skip)
7201 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007202 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7203 if (IS_ERR(pgdat->kswapd)) {
7204 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007205 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007206 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007207 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007208 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007209}
7210
David Rientjes8fe23e02009-12-14 17:58:33 -08007211/*
Jiang Liud8adde12012-07-11 14:01:52 -07007212 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007213 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007214 */
7215void kswapd_stop(int nid)
7216{
7217 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307218 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007219
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307220 trace_android_vh_kswapd_per_node(nid, &skip, false);
7221 if (skip)
7222 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007223 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007224 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007225 NODE_DATA(nid)->kswapd = NULL;
7226 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007227}
7228
Linus Torvalds1da177e2005-04-16 15:20:36 -07007229static int __init kswapd_init(void)
7230{
Wei Yang6b700b52020-04-01 21:10:09 -07007231 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007232
Linus Torvalds1da177e2005-04-16 15:20:36 -07007233 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007234 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007235 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007236 return 0;
7237}
7238
7239module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007240
7241#ifdef CONFIG_NUMA
7242/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007243 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007244 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007245 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007246 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007247 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007248int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007249
Dave Hansen51998362021-02-24 12:09:15 -08007250/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007251 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007252 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7253 * a zone.
7254 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007255#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007256
Christoph Lameter9eeff232006-01-18 17:42:31 -08007257/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007258 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007259 * occur.
7260 */
7261int sysctl_min_unmapped_ratio = 1;
7262
7263/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007264 * If the number of slab pages in a zone grows beyond this percentage then
7265 * slab reclaim needs to occur.
7266 */
7267int sysctl_min_slab_ratio = 5;
7268
Mel Gorman11fb9982016-07-28 15:46:20 -07007269static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007270{
Mel Gorman11fb9982016-07-28 15:46:20 -07007271 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7272 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7273 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007274
7275 /*
7276 * It's possible for there to be more file mapped pages than
7277 * accounted for by the pages on the file LRU lists because
7278 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7279 */
7280 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7281}
7282
7283/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007284static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007285{
Alexandru Moised031a152015-11-05 18:48:08 -08007286 unsigned long nr_pagecache_reclaimable;
7287 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007288
7289 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007290 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007291 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007292 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007293 * a better estimate
7294 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007295 if (node_reclaim_mode & RECLAIM_UNMAP)
7296 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007297 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007298 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007299
7300 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007301 if (!(node_reclaim_mode & RECLAIM_WRITE))
7302 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007303
7304 /* Watch for any possible underflows due to delta */
7305 if (unlikely(delta > nr_pagecache_reclaimable))
7306 delta = nr_pagecache_reclaimable;
7307
7308 return nr_pagecache_reclaimable - delta;
7309}
7310
Christoph Lameter0ff38492006-09-25 23:31:52 -07007311/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007312 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007313 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007314static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007315{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007316 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007317 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007318 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007319 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007320 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007321 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007322 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007323 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007324 .priority = NODE_RECLAIM_PRIORITY,
7325 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7326 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007327 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007328 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007329 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007330 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007331
Yafang Shao132bb8c2019-05-13 17:17:53 -07007332 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7333 sc.gfp_mask);
7334
Christoph Lameter9eeff232006-01-18 17:42:31 -08007335 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007336 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007337 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007338 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007339 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007340 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007341 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007342 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007343 noreclaim_flag = memalloc_noreclaim_save();
7344 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007345 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007346
Mel Gormana5f5f912016-07-28 15:46:32 -07007347 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007348 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007349 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007350 * priorities until we have enough memory freed.
7351 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007352 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007353 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007354 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007355 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007356
Andrew Morton1732d2b012019-07-16 16:26:15 -07007357 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007358 current->flags &= ~PF_SWAPWRITE;
7359 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007360 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007361 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007362
7363 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7364
Rik van Riela79311c2009-01-06 14:40:01 -08007365 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007366}
Andrew Morton179e9632006-03-22 00:08:18 -08007367
Mel Gormana5f5f912016-07-28 15:46:32 -07007368int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007369{
David Rientjesd773ed62007-10-16 23:26:01 -07007370 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007371
7372 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007373 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007374 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007375 *
Christoph Lameter96146342006-07-03 00:24:13 -07007376 * A small portion of unmapped file backed pages is needed for
7377 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007378 * thrown out if the node is overallocated. So we do not reclaim
7379 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007380 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007381 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007382 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007383 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7384 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007385 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007386
7387 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007388 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007389 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007390 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007391 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007392
7393 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007394 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007395 * have associated processors. This will favor the local processor
7396 * over remote processors and spread off node memory allocations
7397 * as wide as possible.
7398 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007399 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7400 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007401
Mel Gormana5f5f912016-07-28 15:46:32 -07007402 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7403 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007404
Mel Gormana5f5f912016-07-28 15:46:32 -07007405 ret = __node_reclaim(pgdat, gfp_mask, order);
7406 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007407
Mel Gorman24cf725182009-06-16 15:33:23 -07007408 if (!ret)
7409 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7410
David Rientjesd773ed62007-10-16 23:26:01 -07007411 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007412}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007413#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007414
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007415/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007416 * check_move_unevictable_pages - check pages for evictability and move to
7417 * appropriate zone lru list
7418 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007419 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007420 * Checks pages for evictability, if an evictable page is in the unevictable
7421 * lru list, moves it to the appropriate evictable lru list. This function
7422 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007423 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007424void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007425{
Alex Shi6168d0d2020-12-15 12:34:29 -08007426 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007427 int pgscanned = 0;
7428 int pgrescued = 0;
7429 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007430
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007431 for (i = 0; i < pvec->nr; i++) {
7432 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007433 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007434
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007435 if (PageTransTail(page))
7436 continue;
7437
7438 nr_pages = thp_nr_pages(page);
7439 pgscanned += nr_pages;
7440
Alex Shid25b5bd2020-12-15 12:34:16 -08007441 /* block memcg migration during page moving between lru */
7442 if (!TestClearPageLRU(page))
7443 continue;
7444
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007445 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007446 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007447 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007448 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007449 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007450 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007451 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007452 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007453 }
Hugh Dickins24513262012-01-20 14:34:21 -08007454
Alex Shi6168d0d2020-12-15 12:34:29 -08007455 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007456 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7457 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007458 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007459 } else if (pgscanned) {
7460 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007461 }
Hugh Dickins850465792012-01-20 14:34:19 -08007462}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007463EXPORT_SYMBOL_GPL(check_move_unevictable_pages);