blob: 635bd6abb6256b5e53cddc6961a3ab17db49f04b [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>
Yu Zhaoa3eb6512022-12-21 21:19:04 -070057#include <linux/rculist_nulls.h>
58#include <linux/random.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070059
60#include <asm/tlbflush.h>
61#include <asm/div64.h>
62
63#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070064#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070065
Nick Piggin0f8053a2006-03-22 00:08:33 -080066#include "internal.h"
67
Mel Gorman33906bc2010-08-09 17:19:16 -070068#define CREATE_TRACE_POINTS
69#include <trace/events/vmscan.h>
70
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070071#undef CREATE_TRACE_POINTS
72#include <trace/hooks/vmscan.h>
73
Minchan Kim7df45e52022-10-27 08:29:17 -070074#undef CREATE_TRACE_POINTS
75#include <trace/hooks/mm.h>
76
Tao Zeng54f845e2022-01-26 16:04:08 +080077#ifdef CONFIG_AMLOGIC_CMA
78#include <linux/amlogic/aml_cma.h>
79#endif
80
Martin Liud705ab992021-06-23 12:20:18 +080081EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
82EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
83
Linus Torvalds1da177e2005-04-16 15:20:36 -070084struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080085 /* How many pages shrink_list() should reclaim */
86 unsigned long nr_to_reclaim;
87
Johannes Weineree814fe2014-08-06 16:06:19 -070088 /*
89 * Nodemask of nodes allowed by the caller. If NULL, all nodes
90 * are scanned.
91 */
92 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070093
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070094 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080095 * The memory cgroup that hit its limit and as a result is the
96 * primary target of this reclaim invocation.
97 */
98 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080099
Johannes Weiner7cf111b2020-06-03 16:03:06 -0700100 /*
101 * Scan pressure balancing between anon and file LRUs
102 */
103 unsigned long anon_cost;
104 unsigned long file_cost;
105
Johannes Weinerb91ac372019-11-30 17:56:02 -0800106 /* Can active pages be deactivated as part of reclaim? */
107#define DEACTIVATE_ANON 1
108#define DEACTIVATE_FILE 2
109 unsigned int may_deactivate:2;
110 unsigned int force_deactivate:1;
111 unsigned int skipped_deactivate:1;
112
Johannes Weiner1276ad62017-02-24 14:56:11 -0800113 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700114 unsigned int may_writepage:1;
115
116 /* Can mapped pages be reclaimed? */
117 unsigned int may_unmap:1;
118
119 /* Can pages be swapped as part of reclaim? */
120 unsigned int may_swap:1;
121
Yosry Ahmed17bdc392022-07-14 06:49:18 +0000122 /* Proactive reclaim invoked by userspace through memory.reclaim */
123 unsigned int proactive:1;
124
Yisheng Xied6622f62017-05-03 14:53:57 -0700125 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700126 * Cgroup memory below memory.low is protected as long as we
127 * don't threaten to OOM. If any cgroup is reclaimed at
128 * reduced force or passed over entirely due to its memory.low
129 * setting (memcg_low_skipped), and nothing is reclaimed as a
130 * result, then go back for one more cycle that reclaims the protected
131 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700132 */
133 unsigned int memcg_low_reclaim:1;
134 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800135
Johannes Weineree814fe2014-08-06 16:06:19 -0700136 unsigned int hibernation_mode:1;
137
138 /* One of the zones is ready for compaction */
139 unsigned int compaction_ready:1;
140
Johannes Weinerb91ac372019-11-30 17:56:02 -0800141 /* There is easily reclaimable cold cache in the current node */
142 unsigned int cache_trim_mode:1;
143
Johannes Weiner53138ce2019-11-30 17:55:56 -0800144 /* The file pages on the current node are dangerously low */
145 unsigned int file_is_tiny:1;
146
Dave Hansen26aa2d12021-09-02 14:59:16 -0700147 /* Always discard instead of demoting to lower tier memory */
148 unsigned int no_demotion:1;
149
Greg Thelenbb451fd2018-08-17 15:45:19 -0700150 /* Allocation order */
151 s8 order;
152
153 /* Scan (total_size >> priority) pages at once */
154 s8 priority;
155
156 /* The highest zone to isolate pages for reclaim from */
157 s8 reclaim_idx;
158
159 /* This context's GFP mask */
160 gfp_t gfp_mask;
161
Johannes Weineree814fe2014-08-06 16:06:19 -0700162 /* Incremented by the number of inactive pages that were scanned */
163 unsigned long nr_scanned;
164
165 /* Number of pages freed so far during a call to shrink_zones() */
166 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700167
168 struct {
169 unsigned int dirty;
170 unsigned int unqueued_dirty;
171 unsigned int congested;
172 unsigned int writeback;
173 unsigned int immediate;
174 unsigned int file_taken;
175 unsigned int taken;
176 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700177
178 /* for recording the reclaimed slab by now */
179 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700180};
181
Linus Torvalds1da177e2005-04-16 15:20:36 -0700182#ifdef ARCH_HAS_PREFETCHW
183#define prefetchw_prev_lru_page(_page, _base, _field) \
184 do { \
185 if ((_page)->lru.prev != _base) { \
186 struct page *prev; \
187 \
188 prev = lru_to_page(&(_page->lru)); \
189 prefetchw(&prev->_field); \
190 } \
191 } while (0)
192#else
193#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
194#endif
195
196/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700197 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700198 */
199int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700200
Yang Shi0a432dc2019-09-23 15:38:12 -0700201static void set_task_reclaim_state(struct task_struct *task,
202 struct reclaim_state *rs)
203{
204 /* Check for an overwrite */
205 WARN_ON_ONCE(rs && task->reclaim_state);
206
207 /* Check for the nulling of an already-nulled member */
208 WARN_ON_ONCE(!rs && !task->reclaim_state);
209
210 task->reclaim_state = rs;
211}
212
Linus Torvalds1da177e2005-04-16 15:20:36 -0700213static LIST_HEAD(shrinker_list);
214static DECLARE_RWSEM(shrinker_rwsem);
215
Yang Shi0a432dc2019-09-23 15:38:12 -0700216#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700217static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700218
Yang Shi3c6f17e2021-05-04 18:36:33 -0700219/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700220static inline int shrinker_map_size(int nr_items)
221{
222 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
223}
Yang Shi2bfd3632021-05-04 18:36:11 -0700224
Yang Shi3c6f17e2021-05-04 18:36:33 -0700225static inline int shrinker_defer_size(int nr_items)
226{
227 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
228}
229
Yang Shi468ab842021-05-04 18:36:26 -0700230static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
231 int nid)
232{
233 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
234 lockdep_is_held(&shrinker_rwsem));
235}
236
Yang Shie4262c42021-05-04 18:36:23 -0700237static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700238 int map_size, int defer_size,
239 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700240{
Yang Shie4262c42021-05-04 18:36:23 -0700241 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700242 struct mem_cgroup_per_node *pn;
243 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700244 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700245
Yang Shi2bfd3632021-05-04 18:36:11 -0700246 for_each_node(nid) {
247 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700248 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700249 /* Not yet online memcg */
250 if (!old)
251 return 0;
252
253 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
254 if (!new)
255 return -ENOMEM;
256
Yang Shi3c6f17e2021-05-04 18:36:33 -0700257 new->nr_deferred = (atomic_long_t *)(new + 1);
258 new->map = (void *)new->nr_deferred + defer_size;
259
260 /* map: set all old bits, clear all new bits */
261 memset(new->map, (int)0xff, old_map_size);
262 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
263 /* nr_deferred: copy old values, clear all new values */
264 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
265 memset((void *)new->nr_deferred + old_defer_size, 0,
266 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700267
Yang Shie4262c42021-05-04 18:36:23 -0700268 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700269 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700270 }
271
272 return 0;
273}
274
Yang Shie4262c42021-05-04 18:36:23 -0700275void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700276{
277 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700278 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700279 int nid;
280
Yang Shi2bfd3632021-05-04 18:36:11 -0700281 for_each_node(nid) {
282 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700283 info = rcu_dereference_protected(pn->shrinker_info, true);
284 kvfree(info);
285 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700286 }
287}
288
Yang Shie4262c42021-05-04 18:36:23 -0700289int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700290{
Yang Shie4262c42021-05-04 18:36:23 -0700291 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700292 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700293 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700294
Yang Shid27cf2a2021-05-04 18:36:14 -0700295 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296 map_size = shrinker_map_size(shrinker_nr_max);
297 defer_size = shrinker_defer_size(shrinker_nr_max);
298 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700299 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700300 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
301 if (!info) {
302 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700303 ret = -ENOMEM;
304 break;
305 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306 info->nr_deferred = (atomic_long_t *)(info + 1);
307 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700308 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700309 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700310 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700311
312 return ret;
313}
314
Yang Shi3c6f17e2021-05-04 18:36:33 -0700315static inline bool need_expand(int nr_max)
316{
317 return round_up(nr_max, BITS_PER_LONG) >
318 round_up(shrinker_nr_max, BITS_PER_LONG);
319}
320
Yang Shie4262c42021-05-04 18:36:23 -0700321static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700322{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700323 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700324 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700325 int map_size, defer_size = 0;
326 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700327 struct mem_cgroup *memcg;
328
Yang Shi3c6f17e2021-05-04 18:36:33 -0700329 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700330 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700331
Yang Shi2bfd3632021-05-04 18:36:11 -0700332 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700333 goto out;
334
335 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700336
Yang Shi3c6f17e2021-05-04 18:36:33 -0700337 map_size = shrinker_map_size(new_nr_max);
338 defer_size = shrinker_defer_size(new_nr_max);
339 old_map_size = shrinker_map_size(shrinker_nr_max);
340 old_defer_size = shrinker_defer_size(shrinker_nr_max);
341
Yang Shi2bfd3632021-05-04 18:36:11 -0700342 memcg = mem_cgroup_iter(NULL, NULL, NULL);
343 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700344 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
345 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 if (ret) {
347 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700348 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 }
350 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700351out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700352 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700353 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700354
Yang Shi2bfd3632021-05-04 18:36:11 -0700355 return ret;
356}
357
358void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
359{
360 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700361 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700362
363 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700364 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700365 /* Pairs with smp mb in shrink_slab() */
366 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700367 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700368 rcu_read_unlock();
369 }
370}
371
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700372static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700373
374static int prealloc_memcg_shrinker(struct shrinker *shrinker)
375{
376 int id, ret = -ENOMEM;
377
Yang Shi476b30a2021-05-04 18:36:39 -0700378 if (mem_cgroup_disabled())
379 return -ENOSYS;
380
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700381 down_write(&shrinker_rwsem);
382 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700383 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700384 if (id < 0)
385 goto unlock;
386
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700387 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700388 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700389 idr_remove(&shrinker_idr, id);
390 goto unlock;
391 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700392 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700393 shrinker->id = id;
394 ret = 0;
395unlock:
396 up_write(&shrinker_rwsem);
397 return ret;
398}
399
400static void unregister_memcg_shrinker(struct shrinker *shrinker)
401{
402 int id = shrinker->id;
403
404 BUG_ON(id < 0);
405
Yang Shi41ca6682021-05-04 18:36:29 -0700406 lockdep_assert_held(&shrinker_rwsem);
407
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700408 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700409}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700410
Yang Shi86750832021-05-04 18:36:36 -0700411static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
412 struct mem_cgroup *memcg)
413{
414 struct shrinker_info *info;
415
416 info = shrinker_info_protected(memcg, nid);
417 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
418}
419
420static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
421 struct mem_cgroup *memcg)
422{
423 struct shrinker_info *info;
424
425 info = shrinker_info_protected(memcg, nid);
426 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
427}
428
Yang Shia1780152021-05-04 18:36:42 -0700429void reparent_shrinker_deferred(struct mem_cgroup *memcg)
430{
431 int i, nid;
432 long nr;
433 struct mem_cgroup *parent;
434 struct shrinker_info *child_info, *parent_info;
435
436 parent = parent_mem_cgroup(memcg);
437 if (!parent)
438 parent = root_mem_cgroup;
439
440 /* Prevent from concurrent shrinker_info expand */
441 down_read(&shrinker_rwsem);
442 for_each_node(nid) {
443 child_info = shrinker_info_protected(memcg, nid);
444 parent_info = shrinker_info_protected(parent, nid);
445 for (i = 0; i < shrinker_nr_max; i++) {
446 nr = atomic_long_read(&child_info->nr_deferred[i]);
447 atomic_long_add(nr, &parent_info->nr_deferred[i]);
448 }
449 }
450 up_read(&shrinker_rwsem);
451}
452
Johannes Weinerb5ead352019-11-30 17:55:40 -0800453static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800454{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800455 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800456}
Tejun Heo97c93412015-05-22 18:23:36 -0400457
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700458static bool global_reclaim(struct scan_control *sc)
459{
460 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
461}
462
Tejun Heo97c93412015-05-22 18:23:36 -0400463/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800464 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400465 * @sc: scan_control in question
466 *
467 * The normal page dirty throttling mechanism in balance_dirty_pages() is
468 * completely broken with the legacy memcg and direct stalling in
469 * shrink_page_list() is used for throttling instead, which lacks all the
470 * niceties such as fairness, adaptive pausing, bandwidth proportional
471 * allocation and configurability.
472 *
473 * This function tests whether the vmscan currently in progress can assume
474 * that the normal dirty throttling mechanism is operational.
475 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800476static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400477{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800478 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400479 return true;
480#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800481 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400482 return true;
483#endif
484 return false;
485}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800486#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700487static int prealloc_memcg_shrinker(struct shrinker *shrinker)
488{
Yang Shi476b30a2021-05-04 18:36:39 -0700489 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700490}
491
492static void unregister_memcg_shrinker(struct shrinker *shrinker)
493{
494}
495
Yang Shi86750832021-05-04 18:36:36 -0700496static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
497 struct mem_cgroup *memcg)
498{
499 return 0;
500}
501
502static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
503 struct mem_cgroup *memcg)
504{
505 return 0;
506}
507
Johannes Weinerb5ead352019-11-30 17:55:40 -0800508static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800509{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800510 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800511}
Tejun Heo97c93412015-05-22 18:23:36 -0400512
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700513static bool global_reclaim(struct scan_control *sc)
514{
515 return true;
516}
517
Johannes Weinerb5ead352019-11-30 17:55:40 -0800518static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400519{
520 return true;
521}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800522#endif
523
Yang Shi86750832021-05-04 18:36:36 -0700524static long xchg_nr_deferred(struct shrinker *shrinker,
525 struct shrink_control *sc)
526{
527 int nid = sc->nid;
528
529 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
530 nid = 0;
531
532 if (sc->memcg &&
533 (shrinker->flags & SHRINKER_MEMCG_AWARE))
534 return xchg_nr_deferred_memcg(nid, shrinker,
535 sc->memcg);
536
537 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
538}
539
540
541static long add_nr_deferred(long nr, struct shrinker *shrinker,
542 struct shrink_control *sc)
543{
544 int nid = sc->nid;
545
546 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
547 nid = 0;
548
549 if (sc->memcg &&
550 (shrinker->flags & SHRINKER_MEMCG_AWARE))
551 return add_nr_deferred_memcg(nr, nid, shrinker,
552 sc->memcg);
553
554 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
555}
556
Dave Hansen26aa2d12021-09-02 14:59:16 -0700557static bool can_demote(int nid, struct scan_control *sc)
558{
Huang Ying20b51af12021-09-02 14:59:33 -0700559 if (!numa_demotion_enabled)
560 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700561 if (sc) {
562 if (sc->no_demotion)
563 return false;
564 /* It is pointless to do demotion in memcg reclaim */
565 if (cgroup_reclaim(sc))
566 return false;
567 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700568 if (next_demotion_node(nid) == NUMA_NO_NODE)
569 return false;
570
Huang Ying20b51af12021-09-02 14:59:33 -0700571 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700572}
573
Keith Buscha2a36482021-09-02 14:59:26 -0700574static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
575 int nid,
576 struct scan_control *sc)
577{
578 if (memcg == NULL) {
579 /*
580 * For non-memcg reclaim, is there
581 * space in any swap device?
582 */
583 if (get_nr_swap_pages() > 0)
584 return true;
585 } else {
586 /* Is the memcg below its swap limit? */
587 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
588 return true;
589 }
590
591 /*
592 * The page can not be swapped.
593 *
594 * Can it be reclaimed from this node via demotion?
595 */
596 return can_demote(nid, sc);
597}
598
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700599/*
600 * This misses isolated pages which are not accounted for to save counters.
601 * As the data only determines if reclaim or compaction continues, it is
602 * not expected that isolated pages will be a dominating factor.
603 */
604unsigned long zone_reclaimable_pages(struct zone *zone)
605{
606 unsigned long nr;
607
608 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
609 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700610 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700611 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
612 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
613
614 return nr;
615}
616
Michal Hockofd538802017-02-22 15:45:58 -0800617/**
618 * lruvec_lru_size - Returns the number of pages on the given LRU list.
619 * @lruvec: lru vector
620 * @lru: lru to use
621 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
622 */
Yu Zhao20913392021-02-24 12:08:44 -0800623static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
624 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800625{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800626 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800627 int zid;
628
Johannes Weinerde3b0152019-11-30 17:55:31 -0800629 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800630 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800631
Michal Hockofd538802017-02-22 15:45:58 -0800632 if (!managed_zone(zone))
633 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800634
Michal Hockofd538802017-02-22 15:45:58 -0800635 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800636 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800637 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800638 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800639 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800640 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800641}
642
Linus Torvalds1da177e2005-04-16 15:20:36 -0700643/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000644 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700645 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900646int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700647{
Yang Shi476b30a2021-05-04 18:36:39 -0700648 unsigned int size;
649 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000650
Yang Shi476b30a2021-05-04 18:36:39 -0700651 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
652 err = prealloc_memcg_shrinker(shrinker);
653 if (err != -ENOSYS)
654 return err;
655
656 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
657 }
658
659 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000660 if (shrinker->flags & SHRINKER_NUMA_AWARE)
661 size *= nr_node_ids;
662
663 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
664 if (!shrinker->nr_deferred)
665 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700666
Tetsuo Handa8e049442018-04-04 19:53:07 +0900667 return 0;
668}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000669
Tetsuo Handa8e049442018-04-04 19:53:07 +0900670void free_prealloced_shrinker(struct shrinker *shrinker)
671{
Yang Shi41ca6682021-05-04 18:36:29 -0700672 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
673 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700674 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700675 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700676 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700677 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700678
Tetsuo Handa8e049442018-04-04 19:53:07 +0900679 kfree(shrinker->nr_deferred);
680 shrinker->nr_deferred = NULL;
681}
682
683void register_shrinker_prepared(struct shrinker *shrinker)
684{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700685 down_write(&shrinker_rwsem);
686 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700687 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700688 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900689}
690
691int register_shrinker(struct shrinker *shrinker)
692{
693 int err = prealloc_shrinker(shrinker);
694
695 if (err)
696 return err;
697 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000698 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700700EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701
702/*
703 * Remove one
704 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700705void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706{
Yang Shi41ca6682021-05-04 18:36:29 -0700707 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900708 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700709
Linus Torvalds1da177e2005-04-16 15:20:36 -0700710 down_write(&shrinker_rwsem);
711 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700712 shrinker->flags &= ~SHRINKER_REGISTERED;
713 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
714 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700715 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700716
Andrew Vaginae393322013-10-16 13:46:46 -0700717 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900718 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700719}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700720EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700721
722#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000723
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800724static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800725 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700726{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000727 unsigned long freed = 0;
728 unsigned long long delta;
729 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700730 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000731 long nr;
732 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000733 long batch_size = shrinker->batch ? shrinker->batch
734 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800735 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000736
rongqianfeng8da6ee32021-05-21 10:30:14 +0800737 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
738
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700739 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700740 if (freeable == 0 || freeable == SHRINK_EMPTY)
741 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000742
743 /*
744 * copy the current shrinker scan count into a local variable
745 * and zero it so that other concurrent shrinker invocations
746 * don't also do this scanning work.
747 */
Yang Shi86750832021-05-04 18:36:36 -0700748 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000749
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700750 if (shrinker->seeks) {
751 delta = freeable >> priority;
752 delta *= 4;
753 do_div(delta, shrinker->seeks);
754 } else {
755 /*
756 * These objects don't require any IO to create. Trim
757 * them aggressively under memory pressure to keep
758 * them from causing refetches in the IO caches.
759 */
760 delta = freeable / 2;
761 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700762
Yang Shi18bb4732021-05-04 18:36:45 -0700763 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000764 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700765 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000766
767 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800768 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800770 /*
771 * Normally, we should not scan less than batch_size objects in one
772 * pass to avoid too frequent shrinker calls, but if the slab has less
773 * than batch_size objects in total and we are really tight on memory,
774 * we will try to reclaim all available objects, otherwise we can end
775 * up failing allocations although there are plenty of reclaimable
776 * objects spread over several slabs with usage less than the
777 * batch_size.
778 *
779 * We detect the "tight on memory" situations by looking at the total
780 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700781 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800782 * scanning at high prio and therefore should try to reclaim as much as
783 * possible.
784 */
785 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700786 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000787 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800788 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800790 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700791 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000792 ret = shrinker->scan_objects(shrinker, shrinkctl);
793 if (ret == SHRINK_STOP)
794 break;
795 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000796
Chris Wilsond460acb2017-09-06 16:19:26 -0700797 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
798 total_scan -= shrinkctl->nr_scanned;
799 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000800
801 cond_resched();
802 }
803
Yang Shi18bb4732021-05-04 18:36:45 -0700804 /*
805 * The deferred work is increased by any new work (delta) that wasn't
806 * done, decreased by old deferred work that was done now.
807 *
808 * And it is capped to two times of the freeable items.
809 */
810 next_deferred = max_t(long, (nr + delta - scanned), 0);
811 next_deferred = min(next_deferred, (2 * freeable));
812
Glauber Costa1d3d4432013-08-28 10:18:04 +1000813 /*
814 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700815 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000816 */
Yang Shi86750832021-05-04 18:36:36 -0700817 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000818
Yang Shi8efb4b52021-05-04 18:36:08 -0700819 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000820 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700821}
822
Yang Shi0a432dc2019-09-23 15:38:12 -0700823#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700824static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
825 struct mem_cgroup *memcg, int priority)
826{
Yang Shie4262c42021-05-04 18:36:23 -0700827 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700828 unsigned long ret, freed = 0;
829 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700830
Yang Shi0a432dc2019-09-23 15:38:12 -0700831 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 return 0;
833
834 if (!down_read_trylock(&shrinker_rwsem))
835 return 0;
836
Yang Shi468ab842021-05-04 18:36:26 -0700837 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700838 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700839 goto unlock;
840
Yang Shie4262c42021-05-04 18:36:23 -0700841 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700842 struct shrink_control sc = {
843 .gfp_mask = gfp_mask,
844 .nid = nid,
845 .memcg = memcg,
846 };
847 struct shrinker *shrinker;
848
849 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700850 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700851 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700852 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700853 continue;
854 }
855
Yang Shi0a432dc2019-09-23 15:38:12 -0700856 /* Call non-slab shrinkers even though kmem is disabled */
857 if (!memcg_kmem_enabled() &&
858 !(shrinker->flags & SHRINKER_NONSLAB))
859 continue;
860
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700861 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700862 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700863 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700864 /*
865 * After the shrinker reported that it had no objects to
866 * free, but before we cleared the corresponding bit in
867 * the memcg shrinker map, a new object might have been
868 * added. To make sure, we have the bit set in this
869 * case, we invoke the shrinker one more time and reset
870 * the bit if it reports that it is not empty anymore.
871 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700872 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700873 *
874 * list_lru_add() shrink_slab_memcg()
875 * list_add_tail() clear_bit()
876 * <MB> <MB>
877 * set_bit() do_shrink_slab()
878 */
879 smp_mb__after_atomic();
880 ret = do_shrink_slab(&sc, shrinker, priority);
881 if (ret == SHRINK_EMPTY)
882 ret = 0;
883 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700884 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700885 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700886 freed += ret;
887
888 if (rwsem_is_contended(&shrinker_rwsem)) {
889 freed = freed ? : 1;
890 break;
891 }
892 }
893unlock:
894 up_read(&shrinker_rwsem);
895 return freed;
896}
Yang Shi0a432dc2019-09-23 15:38:12 -0700897#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700898static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
899 struct mem_cgroup *memcg, int priority)
900{
901 return 0;
902}
Yang Shi0a432dc2019-09-23 15:38:12 -0700903#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700904
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800905/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800906 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800907 * @gfp_mask: allocation context
908 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800909 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800910 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700911 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800912 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700913 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800914 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
915 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700916 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700917 * @memcg specifies the memory cgroup to target. Unaware shrinkers
918 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800919 *
Josef Bacik9092c712018-01-31 16:16:26 -0800920 * @priority is sc->priority, we take the number of objects and >> by priority
921 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700922 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800923 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700924 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800925unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800926 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800927 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700928{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700929 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800931 bool bypass = false;
932
933 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
934 if (bypass)
935 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936
Yang Shifa1e5122019-08-02 21:48:44 -0700937 /*
938 * The root memcg might be allocated even though memcg is disabled
939 * via "cgroup_disable=memory" boot parameter. This could make
940 * mem_cgroup_is_root() return false, then just run memcg slab
941 * shrink, but skip global shrink. This may result in premature
942 * oom.
943 */
944 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700945 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800946
Tetsuo Handae830c632018-04-05 16:23:35 -0700947 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700948 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949
950 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800951 struct shrink_control sc = {
952 .gfp_mask = gfp_mask,
953 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800954 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800955 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800956
Kirill Tkhai9b996462018-08-17 15:48:21 -0700957 ret = do_shrink_slab(&sc, shrinker, priority);
958 if (ret == SHRINK_EMPTY)
959 ret = 0;
960 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800961 /*
962 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700963 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800964 * by parallel ongoing shrinking.
965 */
966 if (rwsem_is_contended(&shrinker_rwsem)) {
967 freed = freed ? : 1;
968 break;
969 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700970 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800971
Linus Torvalds1da177e2005-04-16 15:20:36 -0700972 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700973out:
974 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000975 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700976}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800977EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700978
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800979void drop_slab_node(int nid)
980{
981 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700982 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800983
984 do {
985 struct mem_cgroup *memcg = NULL;
986
Chunxin Zang069c4112020-10-13 16:56:46 -0700987 if (fatal_signal_pending(current))
988 return;
989
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800990 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700991 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800992 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800993 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800994 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700995 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800996}
997
998void drop_slab(void)
999{
1000 int nid;
1001
1002 for_each_online_node(nid)
1003 drop_slab_node(nid);
1004}
1005
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006static inline int is_page_cache_freeable(struct page *page)
1007{
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001008 /*
1009 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001010 * that isolated the page, the page cache and optional buffer
1011 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001012 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001013 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001014 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001015}
1016
Yang Shicb165562019-11-30 17:55:28 -08001017static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001018{
Christoph Lameter930d9152006-01-08 01:00:47 -08001019 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001020 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001021 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001022 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001023 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001024 return 1;
1025 return 0;
1026}
1027
1028/*
1029 * We detected a synchronous write error writing a page out. Probably
1030 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1031 * fsync(), msync() or close().
1032 *
1033 * The tricky part is that after writepage we cannot touch the mapping: nothing
1034 * prevents it from being freed up. But we have a ref on the page and once
1035 * that page is locked, the mapping is pinned.
1036 *
1037 * We're allowed to run sleeping lock_page() here because we know the caller has
1038 * __GFP_FS.
1039 */
1040static void handle_write_error(struct address_space *mapping,
1041 struct page *page, int error)
1042{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001043 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001044 if (page_mapping(page) == mapping)
1045 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046 unlock_page(page);
1047}
1048
Christoph Lameter04e62a22006-06-23 02:03:38 -07001049/* possible outcome of pageout() */
1050typedef enum {
1051 /* failed to write page out, page is locked */
1052 PAGE_KEEP,
1053 /* move page to the active list, page is locked */
1054 PAGE_ACTIVATE,
1055 /* page has been sent to the disk successfully, page is unlocked */
1056 PAGE_SUCCESS,
1057 /* page is clean and locked */
1058 PAGE_CLEAN,
1059} pageout_t;
1060
Linus Torvalds1da177e2005-04-16 15:20:36 -07001061/*
Andrew Morton1742f192006-03-22 00:08:21 -08001062 * pageout is called by shrink_page_list() for each dirty page.
1063 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064 */
Yang Shicb165562019-11-30 17:55:28 -08001065static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001066{
1067 /*
1068 * If the page is dirty, only perform writeback if that write
1069 * will be non-blocking. To prevent this allocation from being
1070 * stalled by pagecache activity. But note that there may be
1071 * stalls if we need to run get_block(). We could test
1072 * PagePrivate for that.
1073 *
Al Viro81742022014-04-03 03:17:43 -04001074 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 * this page's queue, we can perform writeback even if that
1076 * will block.
1077 *
1078 * If the page is swapcache, write it back even if that would
1079 * block, for some throttling. This happens by accident, because
1080 * swap_backing_dev_info is bust: it doesn't reflect the
1081 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001082 */
1083 if (!is_page_cache_freeable(page))
1084 return PAGE_KEEP;
1085 if (!mapping) {
1086 /*
1087 * Some data journaling orphaned pages can have
1088 * page->mapping == NULL while being dirty with clean buffers.
1089 */
David Howells266cf652009-04-03 16:42:36 +01001090 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001091 if (try_to_free_buffers(page)) {
1092 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001093 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001094 return PAGE_CLEAN;
1095 }
1096 }
1097 return PAGE_KEEP;
1098 }
1099 if (mapping->a_ops->writepage == NULL)
1100 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001101 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001102 return PAGE_KEEP;
1103
1104 if (clear_page_dirty_for_io(page)) {
1105 int res;
1106 struct writeback_control wbc = {
1107 .sync_mode = WB_SYNC_NONE,
1108 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001109 .range_start = 0,
1110 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001111 .for_reclaim = 1,
1112 };
1113
1114 SetPageReclaim(page);
1115 res = mapping->a_ops->writepage(page, &wbc);
1116 if (res < 0)
1117 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001118 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001119 ClearPageReclaim(page);
1120 return PAGE_ACTIVATE;
1121 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001122
Linus Torvalds1da177e2005-04-16 15:20:36 -07001123 if (!PageWriteback(page)) {
1124 /* synchronous write or broken a_ops? */
1125 ClearPageReclaim(page);
1126 }
yalin wang3aa23852016-01-14 15:18:30 -08001127 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001128 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001129 return PAGE_SUCCESS;
1130 }
1131
1132 return PAGE_CLEAN;
1133}
1134
Andrew Mortona649fd92006-10-17 00:09:36 -07001135/*
Nick Piggine2867812008-07-25 19:45:30 -07001136 * Same as remove_mapping, but if the page is removed from the mapping, it
1137 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001138 */
Johannes Weinera5289102014-04-03 14:47:51 -07001139static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001140 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001141{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001142 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001143 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001144
Nick Piggin28e4d962006-09-25 23:31:23 -07001145 BUG_ON(!PageLocked(page));
1146 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001147
Johannes Weiner30472502021-09-02 14:53:18 -07001148 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001149 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001150 * The non racy check for a busy page.
1151 *
1152 * Must be careful with the order of the tests. When someone has
1153 * a ref to the page, it may be possible that they dirty it then
1154 * drop the reference. So if PageDirty is tested before page_count
1155 * here, then the following race may occur:
1156 *
1157 * get_user_pages(&page);
1158 * [user mapping goes away]
1159 * write_to(page);
1160 * !PageDirty(page) [good]
1161 * SetPageDirty(page);
1162 * put_page(page);
1163 * !page_count(page) [good, discard it]
1164 *
1165 * [oops, our write_to data is lost]
1166 *
1167 * Reversing the order of the tests ensures such a situation cannot
1168 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001169 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001170 *
1171 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001172 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001173 */
William Kucharski906d2782019-10-18 20:20:33 -07001174 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001175 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001176 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001177 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001178 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001179 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001180 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001181 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001182
1183 if (PageSwapCache(page)) {
1184 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001185
1186 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001187 if (reclaimed && !mapping_exiting(mapping))
1188 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001189 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001190 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001191 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001192 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001193 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001194 void (*freepage)(struct page *);
1195
1196 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001197 /*
1198 * Remember a shadow entry for reclaimed file cache in
1199 * order to detect refaults, thus thrashing, later on.
1200 *
1201 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001202 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001203 * inode reclaim needs to empty out the radix tree or
1204 * the nodes are lost. Don't plant shadows behind its
1205 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001206 *
1207 * We also don't store shadows for DAX mappings because the
1208 * only page cache pages found in these are zero pages
1209 * covering holes, and because we don't want to mix DAX
1210 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001211 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001212 */
Huang Ying9de4f222020-04-06 20:04:41 -07001213 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001214 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001215 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001216 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001217 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001218
1219 if (freepage != NULL)
1220 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001221 }
1222
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001223 return 1;
1224
1225cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001226 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001227 return 0;
1228}
1229
Linus Torvalds1da177e2005-04-16 15:20:36 -07001230/*
Nick Piggine2867812008-07-25 19:45:30 -07001231 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1232 * someone else has a ref on the page, abort and return 0. If it was
1233 * successfully detached, return 1. Assumes the caller has a single ref on
1234 * this page.
1235 */
1236int remove_mapping(struct address_space *mapping, struct page *page)
1237{
Johannes Weinerb9107182019-11-30 17:55:59 -08001238 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001239 /*
1240 * Unfreezing the refcount with 1 rather than 2 effectively
1241 * drops the pagecache ref for us without requiring another
1242 * atomic operation.
1243 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001244 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001245 return 1;
1246 }
1247 return 0;
1248}
1249
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001250/**
1251 * putback_lru_page - put previously isolated page onto appropriate LRU list
1252 * @page: page to be put back to appropriate lru list
1253 *
1254 * Add previously isolated @page to appropriate LRU list.
1255 * Page may still be unevictable for other reasons.
1256 *
1257 * lru_lock must not be held, interrupts must be enabled.
1258 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001259void putback_lru_page(struct page *page)
1260{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001261 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001262 put_page(page); /* drop ref from isolate */
1263}
1264
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001265enum page_references {
1266 PAGEREF_RECLAIM,
1267 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001268 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001269 PAGEREF_ACTIVATE,
1270};
1271
1272static enum page_references page_check_references(struct page *page,
1273 struct scan_control *sc)
1274{
Johannes Weiner645747462010-03-05 13:42:22 -08001275 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001276 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001277
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001278 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1279 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001280 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001281
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001282 /*
1283 * Mlock lost the isolation race with us. Let try_to_unmap()
1284 * move the page to the unevictable list.
1285 */
1286 if (vm_flags & VM_LOCKED)
1287 return PAGEREF_RECLAIM;
1288
Minchan Kimf74aca72022-05-19 14:08:54 -07001289 /* rmap lock contention: rotate */
1290 if (referenced_ptes == -1)
1291 return PAGEREF_KEEP;
1292
Johannes Weiner645747462010-03-05 13:42:22 -08001293 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001294 /*
1295 * All mapped pages start out with page table
1296 * references from the instantiating fault, so we need
1297 * to look twice if a mapped file page is used more
1298 * than once.
1299 *
1300 * Mark it and spare it for another trip around the
1301 * inactive list. Another page table reference will
1302 * lead to its activation.
1303 *
1304 * Note: the mark is set for activated pages as well
1305 * so that recently deactivated but used pages are
1306 * quickly recovered.
1307 */
1308 SetPageReferenced(page);
1309
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001310 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001311 return PAGEREF_ACTIVATE;
1312
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001313 /*
1314 * Activate file-backed executable pages after first usage.
1315 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001316 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001317 return PAGEREF_ACTIVATE;
1318
Johannes Weiner645747462010-03-05 13:42:22 -08001319 return PAGEREF_KEEP;
1320 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001321
1322 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001323 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001324 return PAGEREF_RECLAIM_CLEAN;
1325
1326 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001327}
1328
Mel Gormane2be15f2013-07-03 15:01:57 -07001329/* Check if a page is dirty or under writeback */
1330static void page_check_dirty_writeback(struct page *page,
1331 bool *dirty, bool *writeback)
1332{
Mel Gormanb4597222013-07-03 15:02:05 -07001333 struct address_space *mapping;
1334
Mel Gormane2be15f2013-07-03 15:01:57 -07001335 /*
1336 * Anonymous pages are not handled by flushers and must be written
1337 * from reclaim context. Do not stall reclaim based on them
1338 */
Huang Ying9de4f222020-04-06 20:04:41 -07001339 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001340 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001341 *dirty = false;
1342 *writeback = false;
1343 return;
1344 }
1345
1346 /* By default assume that the page flags are accurate */
1347 *dirty = PageDirty(page);
1348 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001349
1350 /* Verify dirty/writeback state if the filesystem supports it */
1351 if (!page_has_private(page))
1352 return;
1353
1354 mapping = page_mapping(page);
1355 if (mapping && mapping->a_ops->is_dirty_writeback)
1356 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001357}
1358
Dave Hansen26aa2d12021-09-02 14:59:16 -07001359static struct page *alloc_demote_page(struct page *page, unsigned long node)
1360{
1361 struct migration_target_control mtc = {
1362 /*
1363 * Allocate from 'node', or fail quickly and quietly.
1364 * When this happens, 'page' will likely just be discarded
1365 * instead of migrated.
1366 */
1367 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1368 __GFP_THISNODE | __GFP_NOWARN |
1369 __GFP_NOMEMALLOC | GFP_NOWAIT,
1370 .nid = node
1371 };
1372
1373 return alloc_migration_target(page, (unsigned long)&mtc);
1374}
1375
1376/*
1377 * Take pages on @demote_list and attempt to demote them to
1378 * another node. Pages which are not demoted are left on
1379 * @demote_pages.
1380 */
1381static unsigned int demote_page_list(struct list_head *demote_pages,
1382 struct pglist_data *pgdat)
1383{
1384 int target_nid = next_demotion_node(pgdat->node_id);
1385 unsigned int nr_succeeded;
1386 int err;
1387
1388 if (list_empty(demote_pages))
1389 return 0;
1390
1391 if (target_nid == NUMA_NO_NODE)
1392 return 0;
1393
1394 /* Demotion ignores all cpuset and mempolicy settings */
1395 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1396 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1397 &nr_succeeded);
1398
Yang Shi668e4142021-09-02 14:59:19 -07001399 if (current_is_kswapd())
1400 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1401 else
1402 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1403
Dave Hansen26aa2d12021-09-02 14:59:16 -07001404 return nr_succeeded;
1405}
1406
Jianxiong Pan710268f2022-02-24 19:30:46 +08001407#ifdef CONFIG_AMLOGIC_SWAPD_OPT
1408static int can_unmap_files(struct scan_control *sc, struct page *page)
1409{
1410 if (!current_is_kswapd())
1411 return 1;
1412 if (page_mapcount(page) > 1)
1413 return 0;
1414 return 1;
1415}
1416#endif
1417
Nick Piggine2867812008-07-25 19:45:30 -07001418/*
Andrew Morton1742f192006-03-22 00:08:21 -08001419 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001420 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001421static unsigned int shrink_page_list(struct list_head *page_list,
1422 struct pglist_data *pgdat,
1423 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001424 struct reclaim_stat *stat,
1425 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001426{
1427 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001428 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001429 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001430 unsigned int nr_reclaimed = 0;
1431 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001432 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001433
Kirill Tkhai060f0052019-03-05 15:48:15 -08001434 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001435 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001436 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001437
Dave Hansen26aa2d12021-09-02 14:59:16 -07001438retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001439 while (!list_empty(page_list)) {
1440 struct address_space *mapping;
1441 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001442 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001443 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001444 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001445
1446 cond_resched();
1447
1448 page = lru_to_page(page_list);
1449 list_del(&page->lru);
1450
Nick Piggin529ae9a2008-08-02 12:01:03 +02001451 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001452 goto keep;
1453
Sasha Levin309381fea2014-01-23 15:52:54 -08001454 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001456 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001457
1458 /* Account the number of base pages even though THP */
1459 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001460
Hugh Dickins39b5f292012-10-08 16:33:18 -07001461 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001462 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001463
Jianxiong Pan710268f2022-02-24 19:30:46 +08001464 #ifdef CONFIG_AMLOGIC_SWAPD_OPT
1465 if (!can_unmap_files(sc, page))
1466 #else
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001467 if (!sc->may_unmap && page_mapped(page))
Jianxiong Pan710268f2022-02-24 19:30:46 +08001468 #endif
Christoph Lameter80e43422006-02-11 17:55:53 -08001469 goto keep_locked;
1470
Yu Zhao0182f922022-09-18 02:00:04 -06001471 /* page_update_gen() tried to promote this page? */
1472 if (lru_gen_enabled() && !ignore_references &&
1473 page_mapped(page) && PageReferenced(page))
1474 goto keep_locked;
1475
Andy Whitcroftc661b072007-08-22 14:01:26 -07001476 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1477 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1478
Mel Gorman283aba92013-07-03 15:01:51 -07001479 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001480 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001481 * reclaim_congested which affects wait_iff_congested. kswapd
1482 * will stall and start writing pages if the tail of the LRU
1483 * is all dirty unqueued pages.
1484 */
1485 page_check_dirty_writeback(page, &dirty, &writeback);
1486 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001487 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001488
1489 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001490 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001491
Mel Gormand04e8ac2013-07-03 15:02:03 -07001492 /*
1493 * Treat this page as congested if the underlying BDI is or if
1494 * pages are cycling through the LRU so quickly that the
1495 * pages marked for immediate reclaim are making it to the
1496 * end of the LRU a second time.
1497 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001498 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001499 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001500 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001501 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001502 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001503
1504 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001505 * If a page at the tail of the LRU is under writeback, there
1506 * are three cases to consider.
1507 *
1508 * 1) If reclaim is encountering an excessive number of pages
1509 * under writeback and this page is both under writeback and
1510 * PageReclaim then it indicates that pages are being queued
1511 * for IO but are being recycled through the LRU before the
1512 * IO can complete. Waiting on the page itself risks an
1513 * indefinite stall if it is impossible to writeback the
1514 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001515 * note that the LRU is being scanned too quickly and the
1516 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001517 *
Tejun Heo97c93412015-05-22 18:23:36 -04001518 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001519 * not marked for immediate reclaim, or the caller does not
1520 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1521 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001522 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001523 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001524 * Require may_enter_fs because we would wait on fs, which
1525 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001526 * enter reclaim, and deadlock if it waits on a page for
1527 * which it is needed to do the write (loop masks off
1528 * __GFP_IO|__GFP_FS for this reason); but more thought
1529 * would probably show more reasons.
1530 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001531 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001532 * PageReclaim. memcg does not have any dirty pages
1533 * throttling so we could easily OOM just because too many
1534 * pages are in writeback and there is nothing else to
1535 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001536 *
1537 * In cases 1) and 2) we activate the pages to get them out of
1538 * the way while we continue scanning for clean pages on the
1539 * inactive list and refilling from the active list. The
1540 * observation here is that waiting for disk writes is more
1541 * expensive than potentially causing reloads down the line.
1542 * Since they're marked for immediate reclaim, they won't put
1543 * memory pressure on the cache working set any longer than it
1544 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001545 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001546 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001547 /* Case 1 above */
1548 if (current_is_kswapd() &&
1549 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001550 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001551 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001552 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001553
1554 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001555 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001556 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001557 /*
1558 * This is slightly racy - end_page_writeback()
1559 * might have just cleared PageReclaim, then
1560 * setting PageReclaim here end up interpreted
1561 * as PageReadahead - but that does not matter
1562 * enough to care. What we do want is for this
1563 * page to have PageReclaim set next time memcg
1564 * reclaim reaches the tests above, so it will
1565 * then wait_on_page_writeback() to avoid OOM;
1566 * and it's also appropriate in global reclaim.
1567 */
1568 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001569 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001570 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001571
1572 /* Case 3 above */
1573 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001574 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001575 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001576 /* then go back and try same page again */
1577 list_add_tail(&page->lru, page_list);
1578 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001579 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001580 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001581
Minchan Kim8940b342019-09-25 16:49:11 -07001582 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001583 references = page_check_references(page, sc);
1584
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001585 switch (references) {
1586 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001587 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001588 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001589 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001590 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001591 case PAGEREF_RECLAIM:
1592 case PAGEREF_RECLAIM_CLEAN:
1593 ; /* try to reclaim the page below */
1594 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001595
Linus Torvalds1da177e2005-04-16 15:20:36 -07001596 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001597 * Before reclaiming the page, try to relocate
1598 * its contents to another node.
1599 */
1600 if (do_demote_pass &&
1601 (thp_migration_supported() || !PageTransHuge(page))) {
1602 list_add(&page->lru, &demote_pages);
1603 unlock_page(page);
1604 continue;
1605 }
1606
1607 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001608 * Anonymous process memory has backing store?
1609 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001610 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001611 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001612 if (PageAnon(page) && PageSwapBacked(page)) {
1613 if (!PageSwapCache(page)) {
1614 if (!(sc->gfp_mask & __GFP_IO))
1615 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001616 if (page_maybe_dma_pinned(page))
1617 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001618 if (PageTransHuge(page)) {
1619 /* cannot split THP, skip it */
1620 if (!can_split_huge_page(page, NULL))
1621 goto activate_locked;
1622 /*
1623 * Split pages without a PMD map right
1624 * away. Chances are some or all of the
1625 * tail pages can be freed without IO.
1626 */
1627 if (!compound_mapcount(page) &&
1628 split_huge_page_to_list(page,
1629 page_list))
1630 goto activate_locked;
1631 }
1632 if (!add_to_swap(page)) {
1633 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001634 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001635 /* Fallback to swap normal pages */
1636 if (split_huge_page_to_list(page,
1637 page_list))
1638 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001639#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1640 count_vm_event(THP_SWPOUT_FALLBACK);
1641#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001642 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001643 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001644 }
Minchan Kim0f074652017-07-06 15:37:24 -07001645
Kirill Tkhai4b793062020-04-01 21:10:18 -07001646 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001647
1648 /* Adding to swap updated mapping */
1649 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001650 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001651 } else if (unlikely(PageTransHuge(page))) {
1652 /* Split file THP */
1653 if (split_huge_page_to_list(page, page_list))
1654 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001655 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001656
1657 /*
Yang Shi98879b32019-07-11 20:59:30 -07001658 * THP may get split above, need minus tail pages and update
1659 * nr_pages to avoid accounting tail pages twice.
1660 *
1661 * The tail pages that are added into swap cache successfully
1662 * reach here.
1663 */
1664 if ((nr_pages > 1) && !PageTransHuge(page)) {
1665 sc->nr_scanned -= (nr_pages - 1);
1666 nr_pages = 1;
1667 }
1668
1669 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 * The page is mapped into the page tables of one or more
1671 * processes. Try to unmap it here.
1672 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001673 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001674 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001675 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001676
1677 if (unlikely(PageTransHuge(page)))
1678 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001679
Yang Shi1fb08ac2021-06-30 18:52:01 -07001680 try_to_unmap(page, flags);
1681 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001682 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001683 if (!was_swapbacked && PageSwapBacked(page))
1684 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001686 }
1687 }
1688
1689 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001690 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001691 * Only kswapd can writeback filesystem pages
1692 * to avoid risk of stack overflow. But avoid
1693 * injecting inefficient single-page IO into
1694 * flusher writeback as much as possible: only
1695 * write pages when we've encountered many
1696 * dirty pages, and when we've already scanned
1697 * the rest of the LRU for clean pages and see
1698 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001699 */
Huang Ying9de4f222020-04-06 20:04:41 -07001700 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001701 (!current_is_kswapd() || !PageReclaim(page) ||
1702 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001703 /*
1704 * Immediately reclaim when written back.
1705 * Similar in principal to deactivate_page()
1706 * except we already have the page isolated
1707 * and know it's dirty
1708 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001709 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001710 SetPageReclaim(page);
1711
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001712 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001713 }
1714
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001715 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001716 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001717 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001718 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001719 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001720 goto keep_locked;
1721
Mel Gormand950c942015-09-04 15:47:35 -07001722 /*
1723 * Page is dirty. Flush the TLB if a writable entry
1724 * potentially exists to avoid CPU writes after IO
1725 * starts and then write it out here.
1726 */
1727 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001728 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001729 case PAGE_KEEP:
1730 goto keep_locked;
1731 case PAGE_ACTIVATE:
1732 goto activate_locked;
1733 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001734 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001735
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001736 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001737 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001738 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001740
Linus Torvalds1da177e2005-04-16 15:20:36 -07001741 /*
1742 * A synchronous write - probably a ramdisk. Go
1743 * ahead and try to reclaim the page.
1744 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001745 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001746 goto keep;
1747 if (PageDirty(page) || PageWriteback(page))
1748 goto keep_locked;
1749 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001750 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001751 case PAGE_CLEAN:
1752 ; /* try to free the page below */
1753 }
1754 }
1755
1756 /*
1757 * If the page has buffers, try to free the buffer mappings
1758 * associated with this page. If we succeed we try to free
1759 * the page as well.
1760 *
1761 * We do this even if the page is PageDirty().
1762 * try_to_release_page() does not perform I/O, but it is
1763 * possible for a page to have PageDirty set, but it is actually
1764 * clean (all its buffers are clean). This happens if the
1765 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001766 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001767 * try_to_release_page() will discover that cleanness and will
1768 * drop the buffers and mark the page clean - it can be freed.
1769 *
1770 * Rarely, pages can have buffers and no ->mapping. These are
1771 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001772 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001773 * and if that worked, and the page is no longer mapped into
1774 * process address space (page_count == 1) it can be freed.
1775 * Otherwise, leave the page on the LRU so it is swappable.
1776 */
David Howells266cf652009-04-03 16:42:36 +01001777 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001778 if (!try_to_release_page(page, sc->gfp_mask))
1779 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001780 if (!mapping && page_count(page) == 1) {
1781 unlock_page(page);
1782 if (put_page_testzero(page))
1783 goto free_it;
1784 else {
1785 /*
1786 * rare race with speculative reference.
1787 * the speculative reference will free
1788 * this page shortly, so we may
1789 * increment nr_reclaimed here (and
1790 * leave it off the LRU).
1791 */
1792 nr_reclaimed++;
1793 continue;
1794 }
1795 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796 }
1797
Shaohua Li802a3a92017-05-03 14:52:32 -07001798 if (PageAnon(page) && !PageSwapBacked(page)) {
1799 /* follow __remove_mapping for reference */
1800 if (!page_ref_freeze(page, 1))
1801 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001802 /*
1803 * The page has only one reference left, which is
1804 * from the isolation. After the caller puts the
1805 * page back on lru and drops the reference, the
1806 * page will be freed anyway. It doesn't matter
1807 * which lru it goes. So we don't bother checking
1808 * PageDirty here.
1809 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001810 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001811 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001812 } else if (!mapping || !__remove_mapping(mapping, page, true,
1813 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001814 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001815
1816 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001817free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001818 /*
1819 * THP may get swapped out in a whole, need account
1820 * all base pages.
1821 */
1822 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001823
1824 /*
1825 * Is there need to periodically free_page_list? It would
1826 * appear not as the counts should be low
1827 */
Yang Shi7ae88532019-09-23 15:38:09 -07001828 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001829 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001830 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001831 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001832 continue;
1833
Yang Shi98879b32019-07-11 20:59:30 -07001834activate_locked_split:
1835 /*
1836 * The tail pages that are failed to add into swap cache
1837 * reach here. Fixup nr_scanned and nr_pages.
1838 */
1839 if (nr_pages > 1) {
1840 sc->nr_scanned -= (nr_pages - 1);
1841 nr_pages = 1;
1842 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001843activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001844 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001845 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1846 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001847 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001848 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001849 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001850 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001851 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001852 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001853 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001854 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001855keep_locked:
1856 unlock_page(page);
1857keep:
1858 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001859 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001860 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001861 /* 'page_list' is always empty here */
1862
1863 /* Migrate pages selected for demotion */
1864 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1865 /* Pages that could not be demoted are still in @demote_pages */
1866 if (!list_empty(&demote_pages)) {
1867 /* Pages which failed to demoted go back on @page_list for retry: */
1868 list_splice_init(&demote_pages, page_list);
1869 do_demote_pass = false;
1870 goto retry;
1871 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001872
Yang Shi98879b32019-07-11 20:59:30 -07001873 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1874
Johannes Weiner747db952014-08-08 14:19:24 -07001875 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001876 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001877 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001878
Linus Torvalds1da177e2005-04-16 15:20:36 -07001879 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001880 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001881
Andrew Morton05ff5132006-03-22 00:08:20 -08001882 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001883}
1884
Maninder Singh730ec8c2020-06-03 16:01:18 -07001885unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001886 struct list_head *page_list)
1887{
1888 struct scan_control sc = {
1889 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001890 .may_unmap = 1,
1891 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001892 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001893 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001894 struct page *page, *next;
1895 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001896 unsigned int noreclaim_flag;
Tao Zeng54f845e2022-01-26 16:04:08 +08001897#ifdef CONFIG_AMLOGIC_CMA
1898 LIST_HEAD(high_active_pages);
1899#endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001900
1901 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001902 if (!PageHuge(page) && page_is_file_lru(page) &&
1903 !PageDirty(page) && !__PageMovable(page) &&
1904 !PageUnevictable(page)) {
Tao Zeng54f845e2022-01-26 16:04:08 +08001905 #ifdef CONFIG_AMLOGIC_CMA
1906 cma_keep_high_active(page, &high_active_pages,
1907 &clean_pages);
1908 #else
Minchan Kim02c6de82012-10-08 16:31:55 -07001909 ClearPageActive(page);
1910 list_move(&page->lru, &clean_pages);
Tao Zeng54f845e2022-01-26 16:04:08 +08001911 #endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001912 }
1913 }
1914
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001915 /*
1916 * We should be safe here since we are only dealing with file pages and
1917 * we are not kswapd and therefore cannot write dirty file pages. But
1918 * call memalloc_noreclaim_save() anyway, just in case these conditions
1919 * change in the future.
1920 */
1921 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001922 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001923 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001924 memalloc_noreclaim_restore(noreclaim_flag);
1925
Minchan Kim02c6de82012-10-08 16:31:55 -07001926 list_splice(&clean_pages, page_list);
Tao Zeng54f845e2022-01-26 16:04:08 +08001927#ifdef CONFIG_AMLOGIC_CMA
1928 list_splice(&high_active_pages, page_list);
1929#endif
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001930 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1931 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001932 /*
1933 * Since lazyfree pages are isolated from file LRU from the beginning,
1934 * they will rotate back to anonymous LRU in the end if it failed to
1935 * discard so isolated count will be mismatched.
1936 * Compensate the isolated count for both LRU lists.
1937 */
1938 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1939 stat.nr_lazyfree_fail);
1940 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001941 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001942 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001943}
1944
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001945/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001946 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001947 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001948 */
1949static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001950 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001951{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001952 int zid;
1953
Mel Gorman7ee36a12016-07-28 15:47:17 -07001954 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1955 if (!nr_zone_taken[zid])
1956 continue;
1957
Wei Yanga892cb62020-06-03 16:01:12 -07001958 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001960
Mel Gorman7ee36a12016-07-28 15:47:17 -07001961}
1962
Zhaoyang Huang45022652023-05-31 10:51:01 +08001963#ifdef CONFIG_CMA
1964/*
1965 * It is waste of effort to scan and reclaim CMA pages if it is not available
1966 * for current allocation context. Kswapd can not be enrolled as it can not
1967 * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1968 */
1969static bool skip_cma(struct page *page, struct scan_control *sc)
1970{
1971 return !current_is_kswapd() &&
1972 gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1973 get_pageblock_migratetype(page) == MIGRATE_CMA;
1974}
1975#else
1976static bool skip_cma(struct page *page, struct scan_control *sc)
1977{
1978 return false;
1979}
1980#endif
1981
Mel Gormanf611fab2021-06-30 18:53:19 -07001982/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001983 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1984 *
1985 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001986 * shrink the lists perform better by taking out a batch of pages
1987 * and working on them outside the LRU lock.
1988 *
1989 * For pagecache intensive workloads, this function is the hottest
1990 * spot in the kernel (apart from copy_*_user functions).
1991 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001992 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001993 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001994 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001995 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001996 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001997 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001998 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001999 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000 *
2001 * returns how many pages were moved onto *@dst.
2002 */
Andrew Morton69e05942006-03-22 00:08:19 -08002003static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002004 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002005 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002006 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002007{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002008 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002009 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002010 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002011 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002012 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002013 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002014 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002015
Yang Shi98879b32019-07-11 20:59:30 -07002016 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002017 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002018 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002019 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002020 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002021
Linus Torvalds1da177e2005-04-16 15:20:36 -07002022 page = lru_to_page(src);
2023 prefetchw_prev_lru_page(page, src, flags);
2024
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002025 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002026 total_scan += nr_pages;
2027
Zhaoyang Huang45022652023-05-31 10:51:01 +08002028 if (page_zonenum(page) > sc->reclaim_idx ||
2029 skip_cma(page, sc)) {
Yang Shi98879b32019-07-11 20:59:30 -07002030 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002031 move_to = &pages_skipped;
2032 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07002033 }
2034
Minchan Kim791b48b2017-05-12 15:47:06 -07002035 /*
2036 * Do not count skipped pages because that makes the function
2037 * return with no isolated pages if the LRU mostly contains
2038 * ineligible pages. This causes the VM to not reclaim any
2039 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002040 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07002041 */
Yang Shi98879b32019-07-11 20:59:30 -07002042 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002043
2044 if (!PageLRU(page))
2045 goto move;
2046 if (!sc->may_unmap && page_mapped(page))
2047 goto move;
2048
Alex Shic2135f72021-02-24 12:08:01 -08002049 /*
2050 * Be careful not to clear PageLRU until after we're
2051 * sure the page is not being freed elsewhere -- the
2052 * page release code relies on it.
2053 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002054 if (unlikely(!get_page_unless_zero(page)))
2055 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002056
2057 if (!TestClearPageLRU(page)) {
2058 /* Another thread is already isolating this page */
2059 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002060 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002061 }
2062
2063 nr_taken += nr_pages;
2064 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002065 move_to = dst;
2066move:
2067 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002068 }
2069
Mel Gormanb2e18752016-07-28 15:45:37 -07002070 /*
2071 * Splice any skipped pages to the start of the LRU list. Note that
2072 * this disrupts the LRU order when reclaiming for lower zones but
2073 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2074 * scanning would soon rescan the same pages to skip and put the
2075 * system at risk of premature OOM.
2076 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002077 if (!list_empty(&pages_skipped)) {
2078 int zid;
2079
Johannes Weiner3db65812017-05-03 14:52:13 -07002080 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002081 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2082 if (!nr_skipped[zid])
2083 continue;
2084
2085 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002086 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002087 }
2088 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002089 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002090 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002091 total_scan, skipped, nr_taken,
2092 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002093 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002094 return nr_taken;
2095}
2096
Nick Piggin62695a82008-10-18 20:26:09 -07002097/**
2098 * isolate_lru_page - tries to isolate a page from its LRU list
2099 * @page: page to isolate from its LRU list
2100 *
2101 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2102 * vmstat statistic corresponding to whatever LRU list the page was on.
2103 *
2104 * Returns 0 if the page was removed from an LRU list.
2105 * Returns -EBUSY if the page was not on an LRU list.
2106 *
2107 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002108 * the active list, it will have PageActive set. If it was found on
2109 * the unevictable list, it will have the PageUnevictable bit set. That flag
2110 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002111 *
2112 * The vmstat statistic corresponding to the list on which the page was
2113 * found will be decremented.
2114 *
2115 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002116 *
Nick Piggin62695a82008-10-18 20:26:09 -07002117 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002118 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002119 * without a stable reference).
2120 * (2) the lru_lock must not be held.
2121 * (3) interrupts must be enabled.
2122 */
2123int isolate_lru_page(struct page *page)
2124{
2125 int ret = -EBUSY;
2126
Sasha Levin309381fea2014-01-23 15:52:54 -08002127 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002128 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002129
Alex Shid25b5bd2020-12-15 12:34:16 -08002130 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002131 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002132
Alex Shid25b5bd2020-12-15 12:34:16 -08002133 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002134 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002135 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002136 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002137 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002138 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002139
Nick Piggin62695a82008-10-18 20:26:09 -07002140 return ret;
2141}
2142
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002143/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002144 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002145 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002146 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2147 * the LRU list will go small and be scanned faster than necessary, leading to
2148 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002149 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002150static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002151 struct scan_control *sc)
2152{
2153 unsigned long inactive, isolated;
2154
2155 if (current_is_kswapd())
2156 return 0;
2157
Johannes Weinerb5ead352019-11-30 17:55:40 -08002158 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002159 return 0;
2160
2161 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002162 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2163 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002164 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002165 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2166 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002167 }
2168
Fengguang Wu3cf23842012-12-18 14:23:31 -08002169 /*
2170 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2171 * won't get blocked by normal direct-reclaimers, forming a circular
2172 * deadlock.
2173 */
Jianxiong Pan710268f2022-02-24 19:30:46 +08002174#ifndef CONFIG_AMLOGIC_MEMORY_EXTEND
Mel Gormand0164ad2015-11-06 16:28:21 -08002175 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002176 inactive >>= 3;
Jianxiong Pan710268f2022-02-24 19:30:46 +08002177#endif
Fengguang Wu3cf23842012-12-18 14:23:31 -08002178
Tao Zeng54f845e2022-01-26 16:04:08 +08002179#ifdef CONFIG_AMLOGIC_CMA
2180 check_cma_isolated(&isolated, inactive, inactive);
2181#endif
Rik van Riel35cd7812009-09-21 17:01:38 -07002182 return isolated > inactive;
2183}
2184
Kirill Tkhaia222f342019-05-13 17:17:00 -07002185/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002186 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2187 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002188 *
2189 * Returns the number of pages moved to the given lruvec.
2190 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002191static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2192 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002193{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002194 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002195 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002196 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002197
Kirill Tkhaia222f342019-05-13 17:17:00 -07002198 while (!list_empty(list)) {
2199 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002200 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002201 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002202 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002203 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002204 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002205 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002206 continue;
2207 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002208
Alex Shi3d06afa2020-12-15 12:33:37 -08002209 /*
2210 * The SetPageLRU needs to be kept here for list integrity.
2211 * Otherwise:
2212 * #0 move_pages_to_lru #1 release_pages
2213 * if !put_page_testzero
2214 * if (put_page_testzero())
2215 * !PageLRU //skip lru_lock
2216 * SetPageLRU()
2217 * list_add(&page->lru,)
2218 * list_add(&page->lru,)
2219 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002220 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002221
Alex Shi3d06afa2020-12-15 12:33:37 -08002222 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002223 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002224
2225 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002226 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002227 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002228 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002229 } else
2230 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002231
2232 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002233 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002234
Alex Shiafca9152020-12-15 12:34:02 -08002235 /*
2236 * All pages were isolated from the same lruvec (and isolation
2237 * inhibits memcg migration).
2238 */
Muchun Song7467c392021-06-28 19:37:59 -07002239 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002240 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002241 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002242 nr_moved += nr_pages;
2243 if (PageActive(page))
2244 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002245 }
Mel Gorman66635622010-08-09 17:19:30 -07002246
Hugh Dickins3f797682012-01-12 17:20:07 -08002247 /*
2248 * To save our caller's stack, now use input list for pages to free.
2249 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002250 list_splice(&pages_to_free, list);
2251
2252 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002253}
2254
2255/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002256 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002257 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002258 * In that case we should only throttle if the backing device it is
2259 * writing to is congested. In other cases it is safe to throttle.
2260 */
2261static int current_may_throttle(void)
2262{
NeilBrowna37b0712020-06-01 21:48:18 -07002263 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002264 current->backing_dev_info == NULL ||
2265 bdi_write_congested(current->backing_dev_info);
2266}
2267
2268/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002269 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002270 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002271 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002272static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002273shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002274 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002275{
2276 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002277 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002278 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002279 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002280 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002281 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002282 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002283 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002284 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002285 struct blk_plug plug;
2286 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002287
Mel Gorman599d0c92016-07-28 15:45:31 -07002288 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002289 if (stalled)
2290 return 0;
2291
2292 /* wait a bit for the reclaimer. */
2293 msleep(100);
2294 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002295
2296 /* We are about to die and free our memory. Return now. */
2297 if (fatal_signal_pending(current))
2298 return SWAP_CLUSTER_MAX;
2299 }
2300
Linus Torvalds1da177e2005-04-16 15:20:36 -07002301 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002302
Alex Shi6168d0d2020-12-15 12:34:29 -08002303 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002304
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002305 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002306 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002307
Mel Gorman599d0c92016-07-28 15:45:31 -07002308 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002309 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002310 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002311 __count_vm_events(item, nr_scanned);
2312 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002313 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2314
Alex Shi6168d0d2020-12-15 12:34:29 -08002315 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002316
Hillf Dantond563c052012-03-21 16:34:02 -07002317 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002318 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002319
Minchan Kim7df45e52022-10-27 08:29:17 -07002320 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2321 if (do_plug)
2322 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002323 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002324
Alex Shi6168d0d2020-12-15 12:34:29 -08002325 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002326 move_pages_to_lru(lruvec, &page_list);
2327
2328 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002329 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002330 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002331 __count_vm_events(item, nr_reclaimed);
2332 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002333 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002334 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002335
Minchan Kim7df45e52022-10-27 08:29:17 -07002336 if (do_plug)
2337 blk_finish_plug(&plug);
2338
Alex Shi75cc3c92020-12-15 14:20:50 -08002339 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002340 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002341 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002342
Mel Gorman92df3a72011-10-31 17:07:56 -07002343 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002344 * If dirty pages are scanned that are not queued for IO, it
2345 * implies that flushers are not doing their job. This can
2346 * happen when memory pressure pushes dirty pages to the end of
2347 * the LRU before the dirty limits are breached and the dirty
2348 * data has expired. It can also happen when the proportion of
2349 * dirty pages grows not through writes but through memory
2350 * pressure reclaiming all the clean cache. And in some cases,
2351 * the flushers simply cannot keep up with the allocation
2352 * rate. Nudge the flusher threads in case they are asleep.
2353 */
2354 if (stat.nr_unqueued_dirty == nr_taken)
2355 wakeup_flusher_threads(WB_REASON_VMSCAN);
2356
Andrey Ryabinind108c772018-04-10 16:27:59 -07002357 sc->nr.dirty += stat.nr_dirty;
2358 sc->nr.congested += stat.nr_congested;
2359 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2360 sc->nr.writeback += stat.nr_writeback;
2361 sc->nr.immediate += stat.nr_immediate;
2362 sc->nr.taken += nr_taken;
2363 if (file)
2364 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002365
Mel Gorman599d0c92016-07-28 15:45:31 -07002366 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002367 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002368 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002369}
2370
Hugh Dickins15b44732020-12-15 14:21:31 -08002371/*
2372 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2373 *
2374 * We move them the other way if the page is referenced by one or more
2375 * processes.
2376 *
2377 * If the pages are mostly unmapped, the processing is fast and it is
2378 * appropriate to hold lru_lock across the whole operation. But if
2379 * the pages are mapped, the processing is slow (page_referenced()), so
2380 * we should drop lru_lock around each page. It's impossible to balance
2381 * this, so instead we remove the pages from the LRU while processing them.
2382 * It is safe to rely on PG_active against the non-LRU pages in here because
2383 * nobody will play with that bit on a non-LRU page.
2384 *
2385 * The downside is that we have to touch page->_refcount against each page.
2386 * But we had to alter page->flags anyway.
2387 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002388static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002389 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002390 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002391 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002392{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002393 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002394 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002395 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002396 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002397 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002398 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002399 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002400 unsigned nr_deactivate, nr_activate;
2401 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002402 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002403 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002404 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002405
2406 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002407
Alex Shi6168d0d2020-12-15 12:34:29 -08002408 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002409
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002410 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002411 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002412
Mel Gorman599d0c92016-07-28 15:45:31 -07002413 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002414
Shakeel Butt912c0572020-08-06 23:26:32 -07002415 if (!cgroup_reclaim(sc))
2416 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002417 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002418
Alex Shi6168d0d2020-12-15 12:34:29 -08002419 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002420
Linus Torvalds1da177e2005-04-16 15:20:36 -07002421 while (!list_empty(&l_hold)) {
2422 cond_resched();
2423 page = lru_to_page(&l_hold);
2424 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002425
Hugh Dickins39b5f292012-10-08 16:33:18 -07002426 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002427 putback_lru_page(page);
2428 continue;
2429 }
2430
Mel Gormancc715d92012-03-21 16:34:00 -07002431 if (unlikely(buffer_heads_over_limit)) {
2432 if (page_has_private(page) && trylock_page(page)) {
2433 if (page_has_private(page))
2434 try_to_release_page(page, 0);
2435 unlock_page(page);
2436 }
2437 }
2438
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002439 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2440 if (bypass)
2441 goto skip_page_referenced;
2442
Minchan Kimf74aca72022-05-19 14:08:54 -07002443 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002444 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002445 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002446 /*
2447 * Identify referenced, file-backed active pages and
2448 * give them one more trip around the active list. So
2449 * that executable code get better chances to stay in
2450 * memory under moderate memory pressure. Anon pages
2451 * are not likely to be evicted by use-once streaming
2452 * IO, plus JVM can create lots of anon VM_EXEC pages,
2453 * so we ignore them here.
2454 */
Huang Ying9de4f222020-04-06 20:04:41 -07002455 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002456 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002457 list_add(&page->lru, &l_active);
2458 continue;
2459 }
2460 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002461skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002462 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002463 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002464 list_add(&page->lru, &l_inactive);
2465 }
2466
Andrew Mortonb5557492009-01-06 14:40:13 -08002467 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002468 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002469 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002470 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002471
Kirill Tkhaia222f342019-05-13 17:17:00 -07002472 nr_activate = move_pages_to_lru(lruvec, &l_active);
2473 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002474 /* Keep all free pages in l_active list */
2475 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002476
2477 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2478 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2479
Mel Gorman599d0c92016-07-28 15:45:31 -07002480 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002481 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002482
Kirill Tkhaif372d892019-05-13 17:16:57 -07002483 mem_cgroup_uncharge_list(&l_active);
2484 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002485 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2486 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002487}
2488
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002489unsigned long reclaim_pages(struct list_head *page_list)
2490{
Yang Shif661d002020-04-01 21:10:05 -07002491 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002492 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002493 LIST_HEAD(node_page_list);
2494 struct reclaim_stat dummy_stat;
2495 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002496 struct blk_plug plug;
2497 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002498 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002499 struct scan_control sc = {
2500 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002501 .may_writepage = 1,
2502 .may_unmap = 1,
2503 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002504 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002505 };
2506
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002507 noreclaim_flag = memalloc_noreclaim_save();
2508
Minchan Kim7df45e52022-10-27 08:29:17 -07002509 trace_android_vh_reclaim_pages_plug(&do_plug);
2510 if (do_plug)
2511 blk_start_plug(&plug);
2512
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002513 while (!list_empty(page_list)) {
2514 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002515 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002516 nid = page_to_nid(page);
2517 INIT_LIST_HEAD(&node_page_list);
2518 }
2519
2520 if (nid == page_to_nid(page)) {
2521 ClearPageActive(page);
2522 list_move(&page->lru, &node_page_list);
2523 continue;
2524 }
2525
2526 nr_reclaimed += shrink_page_list(&node_page_list,
2527 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002528 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002529 while (!list_empty(&node_page_list)) {
2530 page = lru_to_page(&node_page_list);
2531 list_del(&page->lru);
2532 putback_lru_page(page);
2533 }
2534
Yang Shif661d002020-04-01 21:10:05 -07002535 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002536 }
2537
2538 if (!list_empty(&node_page_list)) {
2539 nr_reclaimed += shrink_page_list(&node_page_list,
2540 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002541 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002542 while (!list_empty(&node_page_list)) {
2543 page = lru_to_page(&node_page_list);
2544 list_del(&page->lru);
2545 putback_lru_page(page);
2546 }
2547 }
2548
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002549 memalloc_noreclaim_restore(noreclaim_flag);
2550
Minchan Kim7df45e52022-10-27 08:29:17 -07002551 if (do_plug)
2552 blk_finish_plug(&plug);
2553
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002554 return nr_reclaimed;
2555}
2556
Johannes Weinerb91ac372019-11-30 17:56:02 -08002557static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2558 struct lruvec *lruvec, struct scan_control *sc)
2559{
2560 if (is_active_lru(lru)) {
2561 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2562 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2563 else
2564 sc->skipped_deactivate = 1;
2565 return 0;
2566 }
2567
2568 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2569}
2570
Rik van Riel59dc76b2016-05-20 16:56:31 -07002571/*
2572 * The inactive anon list should be small enough that the VM never has
2573 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002574 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002575 * The inactive file list should be small enough to leave most memory
2576 * to the established workingset on the scan-resistant active list,
2577 * but large enough to avoid thrashing the aggregate readahead window.
2578 *
2579 * Both inactive lists should also be large enough that each inactive
2580 * page has a chance to be referenced again before it is reclaimed.
2581 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002582 * If that fails and refaulting is observed, the inactive list grows.
2583 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002584 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002585 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002586 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2587 *
2588 * total target max
2589 * memory ratio inactive
2590 * -------------------------------------
2591 * 10MB 1 5MB
2592 * 100MB 1 50MB
2593 * 1GB 3 250MB
2594 * 10GB 10 0.9GB
2595 * 100GB 31 3GB
2596 * 1TB 101 10GB
2597 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002598 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002599static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002600{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002601 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002602 unsigned long inactive, active;
2603 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002604 unsigned long gb;
2605
Johannes Weinerb91ac372019-11-30 17:56:02 -08002606 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2607 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002608
Johannes Weinerb91ac372019-11-30 17:56:02 -08002609 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002610 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002611 inactive_ratio = int_sqrt(10 * gb);
2612 else
2613 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002614
Rik van Riel59dc76b2016-05-20 16:56:31 -07002615 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002616}
2617
Johannes Weiner9a265112013-02-22 16:32:17 -08002618enum scan_balance {
2619 SCAN_EQUAL,
2620 SCAN_FRACT,
2621 SCAN_ANON,
2622 SCAN_FILE,
2623};
2624
Yu Zhao6d313442022-09-18 02:00:00 -06002625static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2626{
2627 unsigned long file;
2628 struct lruvec *target_lruvec;
2629
Yu Zhao37397872022-09-18 02:00:03 -06002630 if (lru_gen_enabled())
2631 return;
2632
Yu Zhao6d313442022-09-18 02:00:00 -06002633 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2634
2635 /*
2636 * Flush the memory cgroup stats, so that we read accurate per-memcg
2637 * lruvec stats for heuristics.
2638 */
2639 mem_cgroup_flush_stats();
2640
2641 /*
2642 * Determine the scan balance between anon and file LRUs.
2643 */
2644 spin_lock_irq(&target_lruvec->lru_lock);
2645 sc->anon_cost = target_lruvec->anon_cost;
2646 sc->file_cost = target_lruvec->file_cost;
2647 spin_unlock_irq(&target_lruvec->lru_lock);
2648
2649 /*
2650 * Target desirable inactive:active list ratios for the anon
2651 * and file LRU lists.
2652 */
2653 if (!sc->force_deactivate) {
2654 unsigned long refaults;
2655
2656 refaults = lruvec_page_state(target_lruvec,
2657 WORKINGSET_ACTIVATE_ANON);
2658 if (refaults != target_lruvec->refaults[0] ||
2659 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2660 sc->may_deactivate |= DEACTIVATE_ANON;
2661 else
2662 sc->may_deactivate &= ~DEACTIVATE_ANON;
2663
2664 /*
2665 * When refaults are being observed, it means a new
2666 * workingset is being established. Deactivate to get
2667 * rid of any stale active pages quickly.
2668 */
2669 refaults = lruvec_page_state(target_lruvec,
2670 WORKINGSET_ACTIVATE_FILE);
2671 if (refaults != target_lruvec->refaults[1] ||
2672 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2673 sc->may_deactivate |= DEACTIVATE_FILE;
2674 else
2675 sc->may_deactivate &= ~DEACTIVATE_FILE;
2676 } else
2677 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2678
2679 /*
2680 * If we have plenty of inactive file pages that aren't
2681 * thrashing, try to reclaim those first before touching
2682 * anonymous pages.
2683 */
2684 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2685 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2686 sc->cache_trim_mode = 1;
2687 else
2688 sc->cache_trim_mode = 0;
2689
2690 /*
2691 * Prevent the reclaimer from falling into the cache trap: as
2692 * cache pages start out inactive, every cache fault will tip
2693 * the scan balance towards the file LRU. And as the file LRU
2694 * shrinks, so does the window for rotation from references.
2695 * This means we have a runaway feedback loop where a tiny
2696 * thrashing file LRU becomes infinitely more attractive than
2697 * anon pages. Try to detect this based on file LRU size.
2698 */
2699 if (!cgroup_reclaim(sc)) {
2700 unsigned long total_high_wmark = 0;
2701 unsigned long free, anon;
2702 int z;
2703
2704 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2705 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2706 node_page_state(pgdat, NR_INACTIVE_FILE);
2707
2708 for (z = 0; z < MAX_NR_ZONES; z++) {
2709 struct zone *zone = &pgdat->node_zones[z];
2710
2711 if (!managed_zone(zone))
2712 continue;
2713
2714 total_high_wmark += high_wmark_pages(zone);
2715 }
2716
2717 /*
2718 * Consider anon: if that's low too, this isn't a
2719 * runaway file reclaim problem, but rather just
2720 * extreme pressure. Reclaim as per usual then.
2721 */
2722 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2723
2724 sc->file_is_tiny =
2725 file + free <= total_high_wmark &&
2726 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2727 anon >> sc->priority;
2728 }
2729}
2730
Linus Torvalds1da177e2005-04-16 15:20:36 -07002731/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002732 * Determine how aggressively the anon and file LRU lists should be
2733 * scanned. The relative value of each set of LRU lists is determined
2734 * by looking at the fraction of the pages scanned we did rotate back
2735 * onto the active list instead of evict.
2736 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002737 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2738 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002739 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002740static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2741 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002742{
Keith Buscha2a36482021-09-02 14:59:26 -07002743 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002744 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002745 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002746 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002747 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002748 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002749 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002750 unsigned long ap, fp;
2751 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002752 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002753
2754 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002755 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002756 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002757 goto out;
2758 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002759
Johannes Weiner10316b32013-02-22 16:32:14 -08002760 /*
2761 * Global reclaim will swap to prevent OOM even with no
2762 * swappiness, but memcg users want to use this knob to
2763 * disable swapping for individual groups completely when
2764 * using the memory controller's swap limit feature would be
2765 * too expensive.
2766 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002767 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002768 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002769 goto out;
2770 }
2771
2772 /*
2773 * Do not apply any pressure balancing cleverness when the
2774 * system is close to OOM, scan both anon and file equally
2775 * (unless the swappiness setting disagrees with swapping).
2776 */
Johannes Weiner02695172014-08-06 16:06:17 -07002777 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002778 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002779 goto out;
2780 }
2781
Johannes Weiner11d16c22013-02-22 16:32:15 -08002782 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002783 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002784 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002785 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002786 scan_balance = SCAN_ANON;
2787 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002788 }
2789
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002790 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2791
Johannes Weiner62376252014-05-06 12:50:07 -07002792 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002793 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002794 * anything from the anonymous working right now. But when balancing
2795 * anon and page cache files for reclaim, allow swapping of anon pages
2796 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002797 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002798 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002799 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002800 goto out;
2801 }
2802
Johannes Weiner9a265112013-02-22 16:32:17 -08002803 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002804 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002805 * Calculate the pressure balance between anon and file pages.
2806 *
2807 * The amount of pressure we put on each LRU is inversely
2808 * proportional to the cost of reclaiming each list, as
2809 * determined by the share of pages that are refaulting, times
2810 * the relative IO cost of bringing back a swapped out
2811 * anonymous page vs reloading a filesystem page (swappiness).
2812 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002813 * Although we limit that influence to ensure no list gets
2814 * left behind completely: at least a third of the pressure is
2815 * applied, before swappiness.
2816 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002817 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002818 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002819 total_cost = sc->anon_cost + sc->file_cost;
2820 anon_cost = total_cost + sc->anon_cost;
2821 file_cost = total_cost + sc->file_cost;
2822 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002823
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002824 ap = swappiness * (total_cost + 1);
2825 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002826
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002827 fp = (200 - swappiness) * (total_cost + 1);
2828 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002829
Shaohua Li76a33fc2010-05-24 14:32:36 -07002830 fraction[0] = ap;
2831 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002832 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002833out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002834 for_each_evictable_lru(lru) {
2835 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002836 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002837 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002838 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002839
Chris Down9783aa92019-10-06 17:58:32 -07002840 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002841 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2842 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002843
Johannes Weinerf56ce412021-08-19 19:04:21 -07002844 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002845 /*
2846 * Scale a cgroup's reclaim pressure by proportioning
2847 * its current usage to its memory.low or memory.min
2848 * setting.
2849 *
2850 * This is important, as otherwise scanning aggression
2851 * becomes extremely binary -- from nothing as we
2852 * approach the memory protection threshold, to totally
2853 * nominal as we exceed it. This results in requiring
2854 * setting extremely liberal protection thresholds. It
2855 * also means we simply get no protection at all if we
2856 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002857 *
2858 * If there is any protection in place, we reduce scan
2859 * pressure by how much of the total memory used is
2860 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002861 *
Chris Down9de7ca42019-10-06 17:58:35 -07002862 * There is one special case: in the first reclaim pass,
2863 * we skip over all groups that are within their low
2864 * protection. If that fails to reclaim enough pages to
2865 * satisfy the reclaim goal, we come back and override
2866 * the best-effort low protection. However, we still
2867 * ideally want to honor how well-behaved groups are in
2868 * that case instead of simply punishing them all
2869 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002870 * memory they are using, reducing the scan pressure
2871 * again by how much of the total memory used is under
2872 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002873 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002874 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002875 unsigned long protection;
2876
2877 /* memory.low scaling, make sure we retry before OOM */
2878 if (!sc->memcg_low_reclaim && low > min) {
2879 protection = low;
2880 sc->memcg_low_skipped = 1;
2881 } else {
2882 protection = min;
2883 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002884
2885 /* Avoid TOCTOU with earlier protection check */
2886 cgroup_size = max(cgroup_size, protection);
2887
2888 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002889 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002890
2891 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002892 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002893 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002894 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002895 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002896 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002897 } else {
2898 scan = lruvec_size;
2899 }
2900
2901 scan >>= sc->priority;
2902
Johannes Weiner688035f2017-05-03 14:52:07 -07002903 /*
2904 * If the cgroup's already been deleted, make sure to
2905 * scrape out the remaining cache.
2906 */
2907 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002908 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002909
Johannes Weiner688035f2017-05-03 14:52:07 -07002910 switch (scan_balance) {
2911 case SCAN_EQUAL:
2912 /* Scan lists relative to size */
2913 break;
2914 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002915 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002916 * Scan types proportional to swappiness and
2917 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002918 * Make sure we don't miss the last page on
2919 * the offlined memory cgroups because of a
2920 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002921 */
Gavin Shan76073c62020-02-20 20:04:24 -08002922 scan = mem_cgroup_online(memcg) ?
2923 div64_u64(scan * fraction[file], denominator) :
2924 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002925 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002926 break;
2927 case SCAN_FILE:
2928 case SCAN_ANON:
2929 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002930 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002931 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002932 break;
2933 default:
2934 /* Look ma, no brain */
2935 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002936 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002937
Johannes Weiner688035f2017-05-03 14:52:07 -07002938 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002939 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002940}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002941
Dave Hansen2f368a92021-09-02 14:59:23 -07002942/*
2943 * Anonymous LRU management is a waste if there is
2944 * ultimately no way to reclaim the memory.
2945 */
2946static bool can_age_anon_pages(struct pglist_data *pgdat,
2947 struct scan_control *sc)
2948{
2949 /* Aging the anon LRU is valuable if swap is present: */
2950 if (total_swap_pages > 0)
2951 return true;
2952
2953 /* Also valuable if anon pages can be demoted: */
2954 return can_demote(pgdat->node_id, sc);
2955}
2956
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002957#ifdef CONFIG_LRU_GEN
2958
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002959#ifdef CONFIG_LRU_GEN_ENABLED
2960DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2961#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2962#else
2963DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2964#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2965#endif
2966
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002967/******************************************************************************
2968 * shorthand helpers
2969 ******************************************************************************/
2970
Yu Zhao37397872022-09-18 02:00:03 -06002971#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2972
2973#define DEFINE_MAX_SEQ(lruvec) \
2974 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2975
2976#define DEFINE_MIN_SEQ(lruvec) \
2977 unsigned long min_seq[ANON_AND_FILE] = { \
2978 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2979 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2980 }
2981
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002982#define for_each_gen_type_zone(gen, type, zone) \
2983 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2984 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2985 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2986
Yu Zhaoa3eb6512022-12-21 21:19:04 -07002987#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2988#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2989
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002990static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002991{
2992 struct pglist_data *pgdat = NODE_DATA(nid);
2993
2994#ifdef CONFIG_MEMCG
2995 if (memcg) {
2996 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2997
2998 /* for hotadd_new_pgdat() */
2999 if (!lruvec->pgdat)
3000 lruvec->pgdat = pgdat;
3001
3002 return lruvec;
3003 }
3004#endif
3005 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3006
3007 return pgdat ? &pgdat->__lruvec : NULL;
3008}
3009
Yu Zhao37397872022-09-18 02:00:03 -06003010static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3011{
3012 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3013 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3014
Yu Zhaof8b57162022-12-21 21:19:05 -07003015 if (!sc->may_swap)
3016 return 0;
3017
Kalesh Singhb8d031e2023-04-03 15:28:17 -07003018 if (!can_demote(pgdat->node_id, sc) &&
3019 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06003020 return 0;
3021
3022 return mem_cgroup_swappiness(memcg);
3023}
3024
3025static int get_nr_gens(struct lruvec *lruvec, int type)
3026{
3027 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3028}
3029
3030static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3031{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003032 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06003033 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3034 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3035 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3036}
3037
3038/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003039 * mm_struct list
3040 ******************************************************************************/
3041
3042static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3043{
3044 static struct lru_gen_mm_list mm_list = {
3045 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3046 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3047 };
3048
3049#ifdef CONFIG_MEMCG
3050 if (memcg)
3051 return &memcg->mm_list;
3052#endif
3053 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3054
3055 return &mm_list;
3056}
3057
3058void lru_gen_add_mm(struct mm_struct *mm)
3059{
3060 int nid;
3061 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3062 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3063
3064 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3065#ifdef CONFIG_MEMCG
3066 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3067 mm->lru_gen.memcg = memcg;
3068#endif
3069 spin_lock(&mm_list->lock);
3070
3071 for_each_node_state(nid, N_MEMORY) {
3072 struct lruvec *lruvec = get_lruvec(memcg, nid);
3073
3074 if (!lruvec)
3075 continue;
3076
3077 /* the first addition since the last iteration */
3078 if (lruvec->mm_state.tail == &mm_list->fifo)
3079 lruvec->mm_state.tail = &mm->lru_gen.list;
3080 }
3081
3082 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3083
3084 spin_unlock(&mm_list->lock);
3085}
3086
3087void lru_gen_del_mm(struct mm_struct *mm)
3088{
3089 int nid;
3090 struct lru_gen_mm_list *mm_list;
3091 struct mem_cgroup *memcg = NULL;
3092
3093 if (list_empty(&mm->lru_gen.list))
3094 return;
3095
3096#ifdef CONFIG_MEMCG
3097 memcg = mm->lru_gen.memcg;
3098#endif
3099 mm_list = get_mm_list(memcg);
3100
3101 spin_lock(&mm_list->lock);
3102
3103 for_each_node(nid) {
3104 struct lruvec *lruvec = get_lruvec(memcg, nid);
3105
3106 if (!lruvec)
3107 continue;
3108
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003109 /* where the current iteration continues after */
3110 if (lruvec->mm_state.head == &mm->lru_gen.list)
3111 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3112
3113 /* where the last iteration ended before */
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003114 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3115 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003116 }
3117
3118 list_del_init(&mm->lru_gen.list);
3119
3120 spin_unlock(&mm_list->lock);
3121
3122#ifdef CONFIG_MEMCG
3123 mem_cgroup_put(mm->lru_gen.memcg);
3124 mm->lru_gen.memcg = NULL;
3125#endif
3126}
3127
3128#ifdef CONFIG_MEMCG
3129void lru_gen_migrate_mm(struct mm_struct *mm)
3130{
3131 struct mem_cgroup *memcg;
3132 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3133
3134 VM_WARN_ON_ONCE(task->mm != mm);
3135 lockdep_assert_held(&task->alloc_lock);
3136
3137 /* for mm_update_next_owner() */
3138 if (mem_cgroup_disabled())
3139 return;
3140
Yu Zhao578a3a32023-01-15 20:44:05 -07003141 /* migration can happen before addition */
3142 if (!mm->lru_gen.memcg)
3143 return;
3144
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003145 rcu_read_lock();
3146 memcg = mem_cgroup_from_task(task);
3147 rcu_read_unlock();
3148 if (memcg == mm->lru_gen.memcg)
3149 return;
3150
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003151 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3152
3153 lru_gen_del_mm(mm);
3154 lru_gen_add_mm(mm);
3155}
3156#endif
3157
3158/*
3159 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3160 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3161 * bits in a bitmap, k is the number of hash functions and n is the number of
3162 * inserted items.
3163 *
3164 * Page table walkers use one of the two filters to reduce their search space.
3165 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3166 * aging uses the double-buffering technique to flip to the other filter each
3167 * time it produces a new generation. For non-leaf entries that have enough
3168 * leaf entries, the aging carries them over to the next generation in
3169 * walk_pmd_range(); the eviction also report them when walking the rmap
3170 * in lru_gen_look_around().
3171 *
3172 * For future optimizations:
3173 * 1. It's not necessary to keep both filters all the time. The spare one can be
3174 * freed after the RCU grace period and reallocated if needed again.
3175 * 2. And when reallocating, it's worth scaling its size according to the number
3176 * of inserted entries in the other filter, to reduce the memory overhead on
3177 * small systems and false positives on large systems.
3178 * 3. Jenkins' hash function is an alternative to Knuth's.
3179 */
3180#define BLOOM_FILTER_SHIFT 15
3181
3182static inline int filter_gen_from_seq(unsigned long seq)
3183{
3184 return seq % NR_BLOOM_FILTERS;
3185}
3186
3187static void get_item_key(void *item, int *key)
3188{
3189 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3190
3191 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3192
3193 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3194 key[1] = hash >> BLOOM_FILTER_SHIFT;
3195}
3196
3197static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3198{
3199 unsigned long *filter;
3200 int gen = filter_gen_from_seq(seq);
3201
3202 filter = lruvec->mm_state.filters[gen];
3203 if (filter) {
3204 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3205 return;
3206 }
3207
3208 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3209 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3210 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3211}
3212
3213static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3214{
3215 int key[2];
3216 unsigned long *filter;
3217 int gen = filter_gen_from_seq(seq);
3218
3219 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3220 if (!filter)
3221 return;
3222
3223 get_item_key(item, key);
3224
3225 if (!test_bit(key[0], filter))
3226 set_bit(key[0], filter);
3227 if (!test_bit(key[1], filter))
3228 set_bit(key[1], filter);
3229}
3230
3231static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3232{
3233 int key[2];
3234 unsigned long *filter;
3235 int gen = filter_gen_from_seq(seq);
3236
3237 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3238 if (!filter)
3239 return true;
3240
3241 get_item_key(item, key);
3242
3243 return test_bit(key[0], filter) && test_bit(key[1], filter);
3244}
3245
3246static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3247{
3248 int i;
3249 int hist;
3250
3251 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3252
3253 if (walk) {
3254 hist = lru_hist_from_seq(walk->max_seq);
3255
3256 for (i = 0; i < NR_MM_STATS; i++) {
3257 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3258 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3259 walk->mm_stats[i] = 0;
3260 }
3261 }
3262
3263 if (NR_HIST_GENS > 1 && last) {
3264 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3265
3266 for (i = 0; i < NR_MM_STATS; i++)
3267 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3268 }
3269}
3270
3271static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3272{
3273 int type;
3274 unsigned long size = 0;
3275 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3276 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3277
3278 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3279 return true;
3280
3281 clear_bit(key, &mm->lru_gen.bitmap);
3282
3283 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3284 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3285 get_mm_counter(mm, MM_ANONPAGES) +
3286 get_mm_counter(mm, MM_SHMEMPAGES);
3287 }
3288
3289 if (size < MIN_LRU_BATCH)
3290 return true;
3291
3292 return !mmget_not_zero(mm);
3293}
3294
3295static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3296 struct mm_struct **iter)
3297{
3298 bool first = false;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003299 bool last = false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003300 struct mm_struct *mm = NULL;
3301 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3302 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3303 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3304
3305 /*
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003306 * mm_state->seq is incremented after each iteration of mm_list. There
3307 * are three interesting cases for this page table walker:
3308 * 1. It tries to start a new iteration with a stale max_seq: there is
3309 * nothing left to do.
3310 * 2. It started the next iteration: it needs to reset the Bloom filter
3311 * so that a fresh set of PTE tables can be recorded.
3312 * 3. It ended the current iteration: it needs to reset the mm stats
3313 * counters and tell its caller to increment max_seq.
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003314 */
3315 spin_lock(&mm_list->lock);
3316
3317 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003318
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003319 if (walk->max_seq <= mm_state->seq)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003320 goto done;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003321
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003322 if (!mm_state->head)
3323 mm_state->head = &mm_list->fifo;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003324
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003325 if (mm_state->head == &mm_list->fifo)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003326 first = true;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003327
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003328 do {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003329 mm_state->head = mm_state->head->next;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003330 if (mm_state->head == &mm_list->fifo) {
3331 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3332 last = true;
3333 break;
3334 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003335
3336 /* force scan for those added after the last iteration */
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003337 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3338 mm_state->tail = mm_state->head->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003339 walk->force_scan = true;
3340 }
3341
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003342 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003343 if (should_skip_mm(mm, walk))
3344 mm = NULL;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003345 } while (!mm);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003346done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003347 if (*iter || last)
3348 reset_mm_stats(lruvec, walk, last);
3349
3350 spin_unlock(&mm_list->lock);
3351
3352 if (mm && first)
3353 reset_bloom_filter(lruvec, walk->max_seq + 1);
3354
3355 if (*iter)
3356 mmput_async(*iter);
3357
3358 *iter = mm;
3359
3360 return last;
3361}
3362
3363static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3364{
3365 bool success = false;
3366 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3367 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3368 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3369
3370 spin_lock(&mm_list->lock);
3371
3372 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3373
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003374 if (max_seq > mm_state->seq) {
3375 mm_state->head = NULL;
3376 mm_state->tail = NULL;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003377 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3378 reset_mm_stats(lruvec, NULL, true);
3379 success = true;
3380 }
3381
3382 spin_unlock(&mm_list->lock);
3383
3384 return success;
3385}
3386
3387/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003388 * refault feedback loop
3389 ******************************************************************************/
3390
3391/*
3392 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3393 *
3394 * The P term is refaulted/(evicted+protected) from a tier in the generation
3395 * currently being evicted; the I term is the exponential moving average of the
3396 * P term over the generations previously evicted, using the smoothing factor
3397 * 1/2; the D term isn't supported.
3398 *
3399 * The setpoint (SP) is always the first tier of one type; the process variable
3400 * (PV) is either any tier of the other type or any other tier of the same
3401 * type.
3402 *
3403 * The error is the difference between the SP and the PV; the correction is to
3404 * turn off protection when SP>PV or turn on protection when SP<PV.
3405 *
3406 * For future optimizations:
3407 * 1. The D term may discount the other two terms over time so that long-lived
3408 * generations can resist stale information.
3409 */
3410struct ctrl_pos {
3411 unsigned long refaulted;
3412 unsigned long total;
3413 int gain;
3414};
3415
3416static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3417 struct ctrl_pos *pos)
3418{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003419 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003420 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3421
3422 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3423 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3424 pos->total = lrugen->avg_total[type][tier] +
3425 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3426 if (tier)
3427 pos->total += lrugen->protected[hist][type][tier - 1];
3428 pos->gain = gain;
3429}
3430
3431static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3432{
3433 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003434 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003435 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3436 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3437
3438 lockdep_assert_held(&lruvec->lru_lock);
3439
3440 if (!carryover && !clear)
3441 return;
3442
3443 hist = lru_hist_from_seq(seq);
3444
3445 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3446 if (carryover) {
3447 unsigned long sum;
3448
3449 sum = lrugen->avg_refaulted[type][tier] +
3450 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3451 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3452
3453 sum = lrugen->avg_total[type][tier] +
3454 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3455 if (tier)
3456 sum += lrugen->protected[hist][type][tier - 1];
3457 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3458 }
3459
3460 if (clear) {
3461 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3462 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3463 if (tier)
3464 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3465 }
3466 }
3467}
3468
3469static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3470{
3471 /*
3472 * Return true if the PV has a limited number of refaults or a lower
3473 * refaulted/total than the SP.
3474 */
3475 return pv->refaulted < MIN_LRU_BATCH ||
3476 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3477 (sp->refaulted + 1) * pv->total * pv->gain;
3478}
3479
3480/******************************************************************************
3481 * the aging
3482 ******************************************************************************/
3483
Yu Zhao0182f922022-09-18 02:00:04 -06003484/* promote pages accessed through page tables */
3485static int page_update_gen(struct page *page, int gen)
3486{
3487 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3488
3489 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3490 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3491
3492 do {
3493 /* lru_gen_del_page() has isolated this page? */
3494 if (!(old_flags & LRU_GEN_MASK)) {
3495 /* for shrink_page_list() */
3496 new_flags = old_flags | BIT(PG_referenced);
3497 continue;
3498 }
3499
3500 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3501 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3502 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3503
3504 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3505}
3506
Yu Zhao37397872022-09-18 02:00:03 -06003507/* protect pages accessed multiple times through file descriptors */
3508static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3509{
3510 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003511 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003512 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3513 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3514
3515 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3516
3517 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003518 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3519 /* page_update_gen() has promoted this page? */
3520 if (new_gen >= 0 && new_gen != old_gen)
3521 return new_gen;
3522
Yu Zhao37397872022-09-18 02:00:03 -06003523 new_gen = (old_gen + 1) % MAX_NR_GENS;
3524
3525 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3526 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3527 /* for end_page_writeback() */
3528 if (reclaiming)
3529 new_flags |= BIT(PG_reclaim);
3530 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3531
3532 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3533
3534 return new_gen;
3535}
3536
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003537static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3538 int old_gen, int new_gen)
3539{
3540 int type = page_is_file_lru(page);
3541 int zone = page_zonenum(page);
3542 int delta = thp_nr_pages(page);
3543
3544 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3545 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3546
3547 walk->batched++;
3548
3549 walk->nr_pages[old_gen][type][zone] -= delta;
3550 walk->nr_pages[new_gen][type][zone] += delta;
3551}
3552
3553static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3554{
3555 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003556 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003557
3558 walk->batched = 0;
3559
3560 for_each_gen_type_zone(gen, type, zone) {
3561 enum lru_list lru = type * LRU_INACTIVE_FILE;
3562 int delta = walk->nr_pages[gen][type][zone];
3563
3564 if (!delta)
3565 continue;
3566
3567 walk->nr_pages[gen][type][zone] = 0;
3568 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3569 lrugen->nr_pages[gen][type][zone] + delta);
3570
3571 if (lru_gen_is_active(lruvec, gen))
3572 lru += LRU_ACTIVE;
3573 __update_lru_size(lruvec, lru, zone, delta);
3574 }
3575}
3576
3577static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3578{
3579 struct address_space *mapping;
3580 struct vm_area_struct *vma = args->vma;
3581 struct lru_gen_mm_walk *walk = args->private;
3582
3583 if (!vma_is_accessible(vma))
3584 return true;
3585
3586 if (is_vm_hugetlb_page(vma))
3587 return true;
3588
Yu Zhao3b9ab092022-12-30 14:52:51 -07003589 if (!vma_has_recency(vma))
3590 return true;
3591
3592 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003593 return true;
3594
3595 if (vma == get_gate_vma(vma->vm_mm))
3596 return true;
3597
3598 if (vma_is_anonymous(vma))
3599 return !walk->can_swap;
3600
3601 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3602 return true;
3603
3604 mapping = vma->vm_file->f_mapping;
3605 if (mapping_unevictable(mapping))
3606 return true;
3607
3608 if (shmem_mapping(mapping))
3609 return !walk->can_swap;
3610
3611 /* to exclude special mappings like dax, etc. */
3612 return !mapping->a_ops->readpage;
3613}
3614
3615/*
3616 * Some userspace memory allocators map many single-page VMAs. Instead of
3617 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3618 * table to reduce zigzags and improve cache performance.
3619 */
3620static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3621 unsigned long *vm_start, unsigned long *vm_end)
3622{
3623 unsigned long start = round_up(*vm_end, size);
3624 unsigned long end = (start | ~mask) + 1;
3625
3626 VM_WARN_ON_ONCE(mask & size);
3627 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3628
3629 while (args->vma) {
3630 if (start >= args->vma->vm_end) {
3631 args->vma = args->vma->vm_next;
3632 continue;
3633 }
3634
3635 if (end && end <= args->vma->vm_start)
3636 return false;
3637
3638 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3639 args->vma = args->vma->vm_next;
3640 continue;
3641 }
3642
3643 *vm_start = max(start, args->vma->vm_start);
3644 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3645
3646 return true;
3647 }
3648
3649 return false;
3650}
3651
Yu Zhao0182f922022-09-18 02:00:04 -06003652static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3653{
3654 unsigned long pfn = pte_pfn(pte);
3655
3656 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3657
3658 if (!pte_present(pte) || is_zero_pfn(pfn))
3659 return -1;
3660
3661 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3662 return -1;
3663
3664 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3665 return -1;
3666
3667 return pfn;
3668}
3669
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003670#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3671static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3672{
3673 unsigned long pfn = pmd_pfn(pmd);
3674
3675 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3676
3677 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3678 return -1;
3679
3680 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3681 return -1;
3682
3683 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3684 return -1;
3685
3686 return pfn;
3687}
3688#endif
3689
Yu Zhao0182f922022-09-18 02:00:04 -06003690static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003691 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003692{
3693 struct page *page;
3694
3695 /* try to avoid unnecessary memory loads */
3696 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3697 return NULL;
3698
3699 page = compound_head(pfn_to_page(pfn));
3700 if (page_to_nid(page) != pgdat->node_id)
3701 return NULL;
3702
3703 if (page_memcg_rcu(page) != memcg)
3704 return NULL;
3705
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003706 /* file VMAs can contain anon pages from COW */
3707 if (!page_is_file_lru(page) && !can_swap)
3708 return NULL;
3709
Yu Zhao0182f922022-09-18 02:00:04 -06003710 return page;
3711}
3712
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003713static bool suitable_to_scan(int total, int young)
3714{
3715 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3716
3717 /* suitable if the average number of young PTEs per cacheline is >=1 */
3718 return young * n >= total;
3719}
3720
3721static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3722 struct mm_walk *args)
3723{
3724 int i;
3725 pte_t *pte;
3726 spinlock_t *ptl;
3727 unsigned long addr;
3728 int total = 0;
3729 int young = 0;
3730 struct lru_gen_mm_walk *walk = args->private;
3731 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3732 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3733 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3734
3735 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3736
3737 ptl = pte_lockptr(args->mm, pmd);
3738 if (!spin_trylock(ptl))
3739 return false;
3740
3741 arch_enter_lazy_mmu_mode();
3742
3743 pte = pte_offset_map(pmd, start & PMD_MASK);
3744restart:
3745 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3746 unsigned long pfn;
3747 struct page *page;
3748
3749 total++;
3750 walk->mm_stats[MM_LEAF_TOTAL]++;
3751
3752 pfn = get_pte_pfn(pte[i], args->vma, addr);
3753 if (pfn == -1)
3754 continue;
3755
3756 if (!pte_young(pte[i])) {
3757 walk->mm_stats[MM_LEAF_OLD]++;
3758 continue;
3759 }
3760
3761 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3762 if (!page)
3763 continue;
3764
3765 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3766 VM_WARN_ON_ONCE(true);
3767
3768 young++;
3769 walk->mm_stats[MM_LEAF_YOUNG]++;
3770
3771 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3772 !(PageAnon(page) && PageSwapBacked(page) &&
3773 !PageSwapCache(page)))
3774 set_page_dirty(page);
3775
3776 old_gen = page_update_gen(page, new_gen);
3777 if (old_gen >= 0 && old_gen != new_gen)
3778 update_batch_size(walk, page, old_gen, new_gen);
3779 }
3780
3781 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3782 goto restart;
3783
3784 pte_unmap(pte);
3785
3786 arch_leave_lazy_mmu_mode();
3787 spin_unlock(ptl);
3788
3789 return suitable_to_scan(total, young);
3790}
3791
3792#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
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 int i;
3797 pmd_t *pmd;
3798 spinlock_t *ptl;
3799 struct lru_gen_mm_walk *walk = args->private;
3800 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3801 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3802 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3803
3804 VM_WARN_ON_ONCE(pud_leaf(*pud));
3805
3806 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3807 if (*start == -1) {
3808 *start = next;
3809 return;
3810 }
3811
3812 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3813 if (i && i <= MIN_LRU_BATCH) {
3814 __set_bit(i - 1, bitmap);
3815 return;
3816 }
3817
3818 pmd = pmd_offset(pud, *start);
3819
3820 ptl = pmd_lockptr(args->mm, pmd);
3821 if (!spin_trylock(ptl))
3822 goto done;
3823
3824 arch_enter_lazy_mmu_mode();
3825
3826 do {
3827 unsigned long pfn;
3828 struct page *page;
3829 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3830
3831 pfn = get_pmd_pfn(pmd[i], vma, addr);
3832 if (pfn == -1)
3833 goto next;
3834
3835 if (!pmd_trans_huge(pmd[i])) {
Juergen Gross23811792022-11-23 07:45:10 +01003836 if (arch_has_hw_nonleaf_pmd_young() &&
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003837 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003838 pmdp_test_and_clear_young(vma, addr, pmd + i);
3839 goto next;
3840 }
3841
3842 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3843 if (!page)
3844 goto next;
3845
3846 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3847 goto next;
3848
3849 walk->mm_stats[MM_LEAF_YOUNG]++;
3850
3851 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3852 !(PageAnon(page) && PageSwapBacked(page) &&
3853 !PageSwapCache(page)))
3854 set_page_dirty(page);
3855
3856 old_gen = page_update_gen(page, new_gen);
3857 if (old_gen >= 0 && old_gen != new_gen)
3858 update_batch_size(walk, page, old_gen, new_gen);
3859next:
3860 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3861 } while (i <= MIN_LRU_BATCH);
3862
3863 arch_leave_lazy_mmu_mode();
3864 spin_unlock(ptl);
3865done:
3866 *start = -1;
3867 bitmap_zero(bitmap, MIN_LRU_BATCH);
3868}
3869#else
3870static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3871 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3872{
3873}
3874#endif
3875
3876static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3877 struct mm_walk *args)
3878{
3879 int i;
3880 pmd_t *pmd;
3881 unsigned long next;
3882 unsigned long addr;
3883 struct vm_area_struct *vma;
3884 unsigned long pos = -1;
3885 struct lru_gen_mm_walk *walk = args->private;
3886 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3887
3888 VM_WARN_ON_ONCE(pud_leaf(*pud));
3889
3890 /*
3891 * Finish an entire PMD in two passes: the first only reaches to PTE
3892 * tables to avoid taking the PMD lock; the second, if necessary, takes
3893 * the PMD lock to clear the accessed bit in PMD entries.
3894 */
3895 pmd = pmd_offset(pud, start & PUD_MASK);
3896restart:
3897 /* walk_pte_range() may call get_next_vma() */
3898 vma = args->vma;
3899 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3900 pmd_t val = pmd_read_atomic(pmd + i);
3901
3902 /* for pmd_read_atomic() */
3903 barrier();
3904
3905 next = pmd_addr_end(addr, end);
3906
3907 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3908 walk->mm_stats[MM_LEAF_TOTAL]++;
3909 continue;
3910 }
3911
3912#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3913 if (pmd_trans_huge(val)) {
3914 unsigned long pfn = pmd_pfn(val);
3915 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3916
3917 walk->mm_stats[MM_LEAF_TOTAL]++;
3918
3919 if (!pmd_young(val)) {
3920 walk->mm_stats[MM_LEAF_OLD]++;
3921 continue;
3922 }
3923
3924 /* try to avoid unnecessary memory loads */
3925 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3926 continue;
3927
3928 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3929 continue;
3930 }
3931#endif
3932 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3933
Juergen Gross23811792022-11-23 07:45:10 +01003934 if (arch_has_hw_nonleaf_pmd_young() &&
3935 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003936 if (!pmd_young(val))
3937 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003938
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003939 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3940 }
Juergen Gross23811792022-11-23 07:45:10 +01003941
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003942 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3943 continue;
3944
3945 walk->mm_stats[MM_NONLEAF_FOUND]++;
3946
3947 if (!walk_pte_range(&val, addr, next, args))
3948 continue;
3949
3950 walk->mm_stats[MM_NONLEAF_ADDED]++;
3951
3952 /* carry over to the next generation */
3953 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3954 }
3955
3956 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3957
3958 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3959 goto restart;
3960}
3961
3962static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3963 struct mm_walk *args)
3964{
3965 int i;
3966 pud_t *pud;
3967 unsigned long addr;
3968 unsigned long next;
3969 struct lru_gen_mm_walk *walk = args->private;
3970
3971 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3972
3973 pud = pud_offset(p4d, start & P4D_MASK);
3974restart:
3975 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3976 pud_t val = READ_ONCE(pud[i]);
3977
3978 next = pud_addr_end(addr, end);
3979
3980 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3981 continue;
3982
3983 walk_pmd_range(&val, addr, next, args);
3984
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003985 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3986 end = (addr | ~PUD_MASK) + 1;
3987 goto done;
3988 }
3989 }
3990
3991 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3992 goto restart;
3993
3994 end = round_up(end, P4D_SIZE);
3995done:
3996 if (!end || !args->vma)
3997 return 1;
3998
3999 walk->next_addr = max(end, args->vma->vm_start);
4000
4001 return -EAGAIN;
4002}
4003
4004static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4005{
4006 static const struct mm_walk_ops mm_walk_ops = {
4007 .test_walk = should_skip_vma,
4008 .p4d_entry = walk_pud_range,
4009 };
4010
4011 int err;
4012 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4013
4014 walk->next_addr = FIRST_USER_ADDRESS;
4015
4016 do {
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004017 DEFINE_MAX_SEQ(lruvec);
4018
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004019 err = -EBUSY;
4020
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004021 /* another thread might have called inc_max_seq() */
4022 if (walk->max_seq != max_seq)
4023 break;
4024
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004025 /* page_update_gen() requires stable page_memcg() */
4026 if (!mem_cgroup_trylock_pages(memcg))
4027 break;
4028
4029 /* the caller might be holding the lock for write */
4030 if (mmap_read_trylock(mm)) {
4031 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4032
4033 mmap_read_unlock(mm);
4034 }
4035
4036 mem_cgroup_unlock_pages();
4037
4038 if (walk->batched) {
4039 spin_lock_irq(&lruvec->lru_lock);
4040 reset_batch_size(lruvec, walk);
4041 spin_unlock_irq(&lruvec->lru_lock);
4042 }
4043
4044 cond_resched();
4045 } while (err == -EAGAIN);
4046}
4047
Yu Zhaof8b57162022-12-21 21:19:05 -07004048static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004049{
4050 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4051
4052 if (pgdat && current_is_kswapd()) {
4053 VM_WARN_ON_ONCE(walk);
4054
4055 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004056 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004057 VM_WARN_ON_ONCE(current_is_kswapd());
4058
4059 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4060 }
4061
4062 current->reclaim_state->mm_walk = walk;
4063
4064 return walk;
4065}
4066
4067static void clear_mm_walk(void)
4068{
4069 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4070
4071 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4072 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4073
4074 current->reclaim_state->mm_walk = NULL;
4075
4076 if (!current_is_kswapd())
4077 kfree(walk);
4078}
4079
Yu Zhao4983c522022-09-18 02:00:09 -06004080static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004081{
Yu Zhao4983c522022-09-18 02:00:09 -06004082 int zone;
4083 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004084 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004085 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004086
Yu Zhao4983c522022-09-18 02:00:09 -06004087 if (type == LRU_GEN_ANON && !can_swap)
4088 goto done;
4089
4090 /* prevent cold/hot inversion if force_scan is true */
4091 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004092 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004093
4094 while (!list_empty(head)) {
4095 struct page *page = lru_to_page(head);
4096
4097 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4098 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4099 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4100 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4101
4102 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004103 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004104
4105 if (!--remaining)
4106 return false;
4107 }
4108 }
4109done:
Yu Zhao37397872022-09-18 02:00:03 -06004110 reset_ctrl_pos(lruvec, type, true);
4111 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004112
4113 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004114}
4115
4116static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4117{
4118 int gen, type, zone;
4119 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004120 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004121 DEFINE_MIN_SEQ(lruvec);
4122
4123 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4124
4125 /* find the oldest populated generation */
4126 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4127 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4128 gen = lru_gen_from_seq(min_seq[type]);
4129
4130 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004131 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004132 goto next;
4133 }
4134
4135 min_seq[type]++;
4136 }
4137next:
4138 ;
4139 }
4140
Yu Zhao3c6c3592022-12-21 21:18:59 -07004141 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004142 if (can_swap) {
4143 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4144 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4145 }
4146
4147 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4148 if (min_seq[type] == lrugen->min_seq[type])
4149 continue;
4150
4151 reset_ctrl_pos(lruvec, type, true);
4152 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4153 success = true;
4154 }
4155
4156 return success;
4157}
4158
Yu Zhao4983c522022-09-18 02:00:09 -06004159static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004160{
4161 int prev, next;
4162 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004163 struct lru_gen_page *lrugen = &lruvec->lrugen;
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004164restart:
Yu Zhao37397872022-09-18 02:00:03 -06004165 spin_lock_irq(&lruvec->lru_lock);
4166
4167 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4168
Yu Zhao37397872022-09-18 02:00:03 -06004169 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4170 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4171 continue;
4172
Yu Zhao4983c522022-09-18 02:00:09 -06004173 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004174
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004175 if (inc_min_seq(lruvec, type, can_swap))
4176 continue;
4177
4178 spin_unlock_irq(&lruvec->lru_lock);
4179 cond_resched();
4180 goto restart;
Yu Zhao37397872022-09-18 02:00:03 -06004181 }
4182
4183 /*
4184 * Update the active/inactive LRU sizes for compatibility. Both sides of
4185 * the current max_seq need to be covered, since max_seq+1 can overlap
4186 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4187 * overlap, cold/hot inversion happens.
4188 */
4189 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4190 next = lru_gen_from_seq(lrugen->max_seq + 1);
4191
4192 for (type = 0; type < ANON_AND_FILE; type++) {
4193 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4194 enum lru_list lru = type * LRU_INACTIVE_FILE;
4195 long delta = lrugen->nr_pages[prev][type][zone] -
4196 lrugen->nr_pages[next][type][zone];
4197
4198 if (!delta)
4199 continue;
4200
4201 __update_lru_size(lruvec, lru, zone, delta);
4202 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4203 }
4204 }
4205
4206 for (type = 0; type < ANON_AND_FILE; type++)
4207 reset_ctrl_pos(lruvec, type, false);
4208
Yu Zhao430499c2022-09-18 02:00:08 -06004209 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004210 /* make sure preceding modifications appear */
4211 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004212
Yu Zhao37397872022-09-18 02:00:03 -06004213 spin_unlock_irq(&lruvec->lru_lock);
4214}
4215
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004216static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004217 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004218{
4219 bool success;
4220 struct lru_gen_mm_walk *walk;
4221 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004222 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004223
4224 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4225
4226 /* see the comment in iterate_mm_list() */
4227 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4228 success = false;
4229 goto done;
4230 }
4231
4232 /*
4233 * If the hardware doesn't automatically set the accessed bit, fallback
4234 * to lru_gen_look_around(), which only clears the accessed bit in a
4235 * handful of PTEs. Spreading the work out over a period of time usually
4236 * is less efficient, but it avoids bursty page faults.
4237 */
Yu Zhao18580ef2022-12-21 21:19:06 -07004238 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004239 success = iterate_mm_list_nowalk(lruvec, max_seq);
4240 goto done;
4241 }
4242
Yu Zhaof8b57162022-12-21 21:19:05 -07004243 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004244 if (!walk) {
4245 success = iterate_mm_list_nowalk(lruvec, max_seq);
4246 goto done;
4247 }
4248
4249 walk->lruvec = lruvec;
4250 walk->max_seq = max_seq;
4251 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004252 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004253
4254 do {
4255 success = iterate_mm_list(lruvec, walk, &mm);
4256 if (mm)
4257 walk_mm(lruvec, mm, walk);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004258 } while (mm);
4259done:
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004260 if (success)
4261 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004262
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004263 return success;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004264}
4265
Yu Zhaoa5998f92022-12-21 21:19:02 -07004266static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004267{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004268 int gen, type, zone;
4269 unsigned long total = 0;
4270 bool can_swap = get_swappiness(lruvec, sc);
4271 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004272 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4273 DEFINE_MAX_SEQ(lruvec);
4274 DEFINE_MIN_SEQ(lruvec);
4275
Yu Zhaoa5998f92022-12-21 21:19:02 -07004276 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4277 unsigned long seq;
4278
4279 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4280 gen = lru_gen_from_seq(seq);
4281
4282 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4283 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4284 }
4285 }
4286
4287 /* whether the size is big enough to be helpful */
4288 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4289}
4290
4291static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4292 unsigned long min_ttl)
4293{
4294 int gen;
4295 unsigned long birth;
4296 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4297 DEFINE_MIN_SEQ(lruvec);
4298
Yu Zhaoa5998f92022-12-21 21:19:02 -07004299 /* see the comment on lru_gen_page */
4300 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4301 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4302
4303 if (time_is_after_jiffies(birth + min_ttl))
4304 return false;
4305
4306 if (!lruvec_is_sizable(lruvec, sc))
4307 return false;
4308
Yu Zhao37397872022-09-18 02:00:03 -06004309 mem_cgroup_calculate_protection(NULL, memcg);
4310
Yu Zhaoa5998f92022-12-21 21:19:02 -07004311 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004312}
4313
Yu Zhao430499c2022-09-18 02:00:08 -06004314/* to protect the working set of the last N jiffies */
4315static unsigned long lru_gen_min_ttl __read_mostly;
4316
Yu Zhao37397872022-09-18 02:00:03 -06004317static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4318{
4319 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004320 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004321
4322 VM_WARN_ON_ONCE(!current_is_kswapd());
4323
Yu Zhaoa5998f92022-12-21 21:19:02 -07004324 /* check the order to exclude compaction-induced reclaim */
4325 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004326 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004327
Yu Zhao37397872022-09-18 02:00:03 -06004328 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4329 do {
4330 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4331
Yu Zhaoa5998f92022-12-21 21:19:02 -07004332 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4333 mem_cgroup_iter_break(NULL, memcg);
4334 return;
4335 }
Yu Zhao37397872022-09-18 02:00:03 -06004336
4337 cond_resched();
4338 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004339
Yu Zhao430499c2022-09-18 02:00:08 -06004340 /*
4341 * The main goal is to OOM kill if every generation from all memcgs is
4342 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004343 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004344 */
4345 if (mutex_trylock(&oom_lock)) {
4346 struct oom_control oc = {
4347 .gfp_mask = sc->gfp_mask,
4348 };
4349
4350 out_of_memory(&oc);
4351
4352 mutex_unlock(&oom_lock);
4353 }
Yu Zhao37397872022-09-18 02:00:03 -06004354}
4355
Yu Zhao0182f922022-09-18 02:00:04 -06004356/*
4357 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004358 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4359 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4360 * the PTE table to the Bloom filter. This forms a feedback loop between the
4361 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004362 */
4363void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4364{
4365 int i;
4366 pte_t *pte;
4367 unsigned long start;
4368 unsigned long end;
4369 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004370 struct lru_gen_mm_walk *walk;
4371 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004372 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4373 struct page *page = pvmw->page;
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004374 bool can_swap = !page_is_file_lru(page);
Yu Zhao0182f922022-09-18 02:00:04 -06004375 struct mem_cgroup *memcg = page_memcg(page);
4376 struct pglist_data *pgdat = page_pgdat(page);
4377 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4378 DEFINE_MAX_SEQ(lruvec);
4379 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4380
4381 lockdep_assert_held(pvmw->ptl);
4382 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4383
4384 if (spin_is_contended(pvmw->ptl))
4385 return;
4386
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004387 /* avoid taking the LRU lock under the PTL when possible */
4388 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4389
Yu Zhao0182f922022-09-18 02:00:04 -06004390 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4391 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4392
4393 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4394 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4395 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4396 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4397 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4398 else {
4399 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4400 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4401 }
4402 }
4403
4404 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4405
4406 rcu_read_lock();
4407 arch_enter_lazy_mmu_mode();
4408
4409 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4410 unsigned long pfn;
4411
4412 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4413 if (pfn == -1)
4414 continue;
4415
4416 if (!pte_young(pte[i]))
4417 continue;
4418
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004419 page = get_pfn_page(pfn, memcg, pgdat, can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004420 if (!page)
4421 continue;
4422
4423 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4424 VM_WARN_ON_ONCE(true);
4425
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004426 young++;
4427
Yu Zhao0182f922022-09-18 02:00:04 -06004428 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4429 !(PageAnon(page) && PageSwapBacked(page) &&
4430 !PageSwapCache(page)))
4431 set_page_dirty(page);
4432
4433 old_gen = page_lru_gen(page);
4434 if (old_gen < 0)
4435 SetPageReferenced(page);
4436 else if (old_gen != new_gen)
4437 __set_bit(i, bitmap);
4438 }
4439
4440 arch_leave_lazy_mmu_mode();
4441 rcu_read_unlock();
4442
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004443 /* feedback from rmap walkers to page table walkers */
4444 if (suitable_to_scan(i, young))
4445 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4446
4447 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004448 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4449 page = pte_page(pte[i]);
4450 activate_page(page);
4451 }
4452 return;
4453 }
4454
4455 /* page_update_gen() requires stable page_memcg() */
4456 if (!mem_cgroup_trylock_pages(memcg))
4457 return;
4458
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004459 if (!walk) {
4460 spin_lock_irq(&lruvec->lru_lock);
4461 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4462 }
Yu Zhao0182f922022-09-18 02:00:04 -06004463
4464 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4465 page = compound_head(pte_page(pte[i]));
4466 if (page_memcg_rcu(page) != memcg)
4467 continue;
4468
4469 old_gen = page_update_gen(page, new_gen);
4470 if (old_gen < 0 || old_gen == new_gen)
4471 continue;
4472
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004473 if (walk)
4474 update_batch_size(walk, page, old_gen, new_gen);
4475 else
4476 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004477 }
4478
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004479 if (!walk)
4480 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004481
4482 mem_cgroup_unlock_pages();
4483}
4484
Yu Zhao37397872022-09-18 02:00:03 -06004485/******************************************************************************
4486 * the eviction
4487 ******************************************************************************/
4488
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004489static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4490 int tier_idx)
Yu Zhao37397872022-09-18 02:00:03 -06004491{
4492 bool success;
4493 int gen = page_lru_gen(page);
4494 int type = page_is_file_lru(page);
4495 int zone = page_zonenum(page);
4496 int delta = thp_nr_pages(page);
4497 int refs = page_lru_refs(page);
4498 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004499 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004500
4501 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4502
4503 /* unevictable */
4504 if (!page_evictable(page)) {
4505 success = lru_gen_del_page(lruvec, page, true);
4506 VM_WARN_ON_ONCE_PAGE(!success, page);
4507 SetPageUnevictable(page);
4508 add_page_to_lru_list(page, lruvec);
4509 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4510 return true;
4511 }
4512
4513 /* dirty lazyfree */
4514 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4515 success = lru_gen_del_page(lruvec, page, true);
4516 VM_WARN_ON_ONCE_PAGE(!success, page);
4517 SetPageSwapBacked(page);
4518 add_page_to_lru_list_tail(page, lruvec);
4519 return true;
4520 }
4521
Yu Zhao0182f922022-09-18 02:00:04 -06004522 /* promoted */
4523 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004524 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004525 return true;
4526 }
4527
Yu Zhao37397872022-09-18 02:00:03 -06004528 /* protected */
4529 if (tier > tier_idx) {
4530 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4531
4532 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004533 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004534
4535 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4536 lrugen->protected[hist][type][tier - 1] + delta);
Yu Zhao37397872022-09-18 02:00:03 -06004537 return true;
4538 }
4539
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004540 /* ineligible */
Charan Teja Kallaa8455252023-08-09 13:35:44 +05304541 if (zone > sc->reclaim_idx || skip_cma(page, sc)) {
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004542 gen = page_inc_gen(lruvec, page, false);
4543 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4544 return true;
4545 }
4546
Yu Zhao37397872022-09-18 02:00:03 -06004547 /* waiting for writeback */
4548 if (PageLocked(page) || PageWriteback(page) ||
4549 (type == LRU_GEN_FILE && PageDirty(page))) {
4550 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004551 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004552 return true;
4553 }
4554
4555 return false;
4556}
4557
4558static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4559{
4560 bool success;
4561
Yu Zhao37397872022-09-18 02:00:03 -06004562 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004563 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004564 (PageDirty(page) ||
4565 (PageAnon(page) && !PageSwapCache(page))))
4566 return false;
4567
4568 /* raced with release_pages() */
4569 if (!get_page_unless_zero(page))
4570 return false;
4571
4572 /* raced with another isolation */
4573 if (!TestClearPageLRU(page)) {
4574 put_page(page);
4575 return false;
4576 }
4577
4578 /* see the comment on MAX_NR_TIERS */
4579 if (!PageReferenced(page))
4580 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4581
4582 /* for shrink_page_list() */
4583 ClearPageReclaim(page);
4584 ClearPageReferenced(page);
4585
4586 success = lru_gen_del_page(lruvec, page, true);
4587 VM_WARN_ON_ONCE_PAGE(!success, page);
4588
4589 return true;
4590}
4591
4592static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4593 int type, int tier, struct list_head *list)
4594{
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004595 int i;
4596 int gen;
Yu Zhao37397872022-09-18 02:00:03 -06004597 enum vm_event_item item;
4598 int sorted = 0;
4599 int scanned = 0;
4600 int isolated = 0;
4601 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004602 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004603 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4604
4605 VM_WARN_ON_ONCE(!list_empty(list));
4606
4607 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4608 return 0;
4609
4610 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4611
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004612 for (i = MAX_NR_ZONES; i > 0; i--) {
Yu Zhao37397872022-09-18 02:00:03 -06004613 LIST_HEAD(moved);
4614 int skipped = 0;
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004615 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004616 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004617
4618 while (!list_empty(head)) {
4619 struct page *page = lru_to_page(head);
4620 int delta = thp_nr_pages(page);
4621
4622 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4623 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4624 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4625 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4626
4627 scanned += delta;
4628
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004629 if (sort_page(lruvec, page, sc, tier))
Yu Zhao37397872022-09-18 02:00:03 -06004630 sorted += delta;
4631 else if (isolate_page(lruvec, page, sc)) {
4632 list_add(&page->lru, list);
4633 isolated += delta;
4634 } else {
4635 list_move(&page->lru, &moved);
4636 skipped += delta;
4637 }
4638
4639 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4640 break;
4641 }
4642
4643 if (skipped) {
4644 list_splice(&moved, head);
4645 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4646 }
4647
4648 if (!remaining || isolated >= MIN_LRU_BATCH)
4649 break;
4650 }
4651
4652 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4653 if (!cgroup_reclaim(sc)) {
4654 __count_vm_events(item, isolated);
4655 __count_vm_events(PGREFILL, sorted);
4656 }
4657 __count_memcg_events(memcg, item, isolated);
4658 __count_memcg_events(memcg, PGREFILL, sorted);
4659 __count_vm_events(PGSCAN_ANON + type, isolated);
4660
4661 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004662 * There might not be eligible pages due to reclaim_idx. Check the
4663 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004664 */
4665 return isolated || !remaining ? scanned : 0;
4666}
4667
4668static int get_tier_idx(struct lruvec *lruvec, int type)
4669{
4670 int tier;
4671 struct ctrl_pos sp, pv;
4672
4673 /*
4674 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4675 * This value is chosen because any other tier would have at least twice
4676 * as many refaults as the first tier.
4677 */
4678 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4679 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4680 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4681 if (!positive_ctrl_err(&sp, &pv))
4682 break;
4683 }
4684
4685 return tier - 1;
4686}
4687
4688static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4689{
4690 int type, tier;
4691 struct ctrl_pos sp, pv;
4692 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4693
4694 /*
4695 * Compare the first tier of anon with that of file to determine which
4696 * type to scan. Also need to compare other tiers of the selected type
4697 * with the first tier of the other type to determine the last tier (of
4698 * the selected type) to evict.
4699 */
4700 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4701 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4702 type = positive_ctrl_err(&sp, &pv);
4703
4704 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4705 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4706 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4707 if (!positive_ctrl_err(&sp, &pv))
4708 break;
4709 }
4710
4711 *tier_idx = tier - 1;
4712
4713 return type;
4714}
4715
4716static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4717 int *type_scanned, struct list_head *list)
4718{
4719 int i;
4720 int type;
4721 int scanned;
4722 int tier = -1;
4723 DEFINE_MIN_SEQ(lruvec);
4724
4725 /*
4726 * Try to make the obvious choice first. When anon and file are both
4727 * available from the same generation, interpret swappiness 1 as file
4728 * first and 200 as anon first.
4729 */
4730 if (!swappiness)
4731 type = LRU_GEN_FILE;
4732 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4733 type = LRU_GEN_ANON;
4734 else if (swappiness == 1)
4735 type = LRU_GEN_FILE;
4736 else if (swappiness == 200)
4737 type = LRU_GEN_ANON;
4738 else
4739 type = get_type_to_scan(lruvec, swappiness, &tier);
4740
4741 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4742 if (tier < 0)
4743 tier = get_tier_idx(lruvec, type);
4744
4745 scanned = scan_pages(lruvec, sc, type, tier, list);
4746 if (scanned)
4747 break;
4748
4749 type = !type;
4750 tier = -1;
4751 }
4752
4753 *type_scanned = type;
4754
4755 return scanned;
4756}
4757
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004758static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004759{
4760 int type;
4761 int scanned;
4762 int reclaimed;
4763 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004764 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004765 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004766 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004767 enum vm_event_item item;
4768 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004769 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004770 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004771 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4772 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4773
4774 spin_lock_irq(&lruvec->lru_lock);
4775
4776 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4777
4778 scanned += try_to_inc_min_seq(lruvec, swappiness);
4779
4780 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4781 scanned = 0;
4782
4783 spin_unlock_irq(&lruvec->lru_lock);
4784
4785 if (list_empty(&list))
4786 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004787retry:
Yu Zhao37397872022-09-18 02:00:03 -06004788 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004789 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004790
Yu Zhao79e66ea2022-11-15 18:38:07 -07004791 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4792 if (!page_evictable(page)) {
4793 list_del(&page->lru);
4794 putback_lru_page(page);
4795 continue;
4796 }
Yu Zhao37397872022-09-18 02:00:03 -06004797
Yu Zhao37397872022-09-18 02:00:03 -06004798 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004799 (PageDirty(page) || PageWriteback(page))) {
4800 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4801 if (PageWorkingset(page))
4802 SetPageReferenced(page);
4803 continue;
4804 }
4805
4806 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4807 page_mapped(page) || PageLocked(page) ||
4808 PageDirty(page) || PageWriteback(page)) {
4809 /* don't add rejected pages to the oldest generation */
4810 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4811 BIT(PG_active));
4812 continue;
4813 }
4814
4815 /* retry pages that may have missed rotate_reclaimable_page() */
4816 list_move(&page->lru, &clean);
4817 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004818 }
4819
4820 spin_lock_irq(&lruvec->lru_lock);
4821
4822 move_pages_to_lru(lruvec, &list);
4823
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004824 walk = current->reclaim_state->mm_walk;
4825 if (walk && walk->batched)
4826 reset_batch_size(lruvec, walk);
4827
Yu Zhao37397872022-09-18 02:00:03 -06004828 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4829 if (!cgroup_reclaim(sc))
4830 __count_vm_events(item, reclaimed);
4831 __count_memcg_events(memcg, item, reclaimed);
4832 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4833
4834 spin_unlock_irq(&lruvec->lru_lock);
4835
4836 mem_cgroup_uncharge_list(&list);
4837 free_unref_page_list(&list);
4838
Yu Zhao79e66ea2022-11-15 18:38:07 -07004839 INIT_LIST_HEAD(&list);
4840 list_splice_init(&clean, &list);
4841
4842 if (!list_empty(&list)) {
4843 skip_retry = true;
4844 goto retry;
4845 }
Yu Zhao37397872022-09-18 02:00:03 -06004846
4847 return scanned;
4848}
4849
Yu Zhaocb3958d2022-12-21 21:19:03 -07004850static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4851 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4852{
4853 int gen, type, zone;
4854 unsigned long old = 0;
4855 unsigned long young = 0;
4856 unsigned long total = 0;
4857 struct lru_gen_page *lrugen = &lruvec->lrugen;
4858 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4859 DEFINE_MIN_SEQ(lruvec);
4860
4861 /* whether this lruvec is completely out of cold pages */
4862 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4863 *nr_to_scan = 0;
4864 return true;
4865 }
4866
4867 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4868 unsigned long seq;
4869
4870 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4871 unsigned long size = 0;
4872
4873 gen = lru_gen_from_seq(seq);
4874
4875 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4876 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4877
4878 total += size;
4879 if (seq == max_seq)
4880 young += size;
4881 else if (seq + MIN_NR_GENS == max_seq)
4882 old += size;
4883 }
4884 }
4885
4886 /* try to scrape all its memory if this memcg was deleted */
4887 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4888
4889 /*
4890 * The aging tries to be lazy to reduce the overhead, while the eviction
4891 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4892 * ideal number of generations is MIN_NR_GENS+1.
4893 */
4894 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4895 return false;
4896
4897 /*
4898 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4899 * of the total number of pages for each generation. A reasonable range
4900 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4901 * aging cares about the upper bound of hot pages, while the eviction
4902 * cares about the lower bound of cold pages.
4903 */
4904 if (young * MIN_NR_GENS > total)
4905 return true;
4906 if (old * (MIN_NR_GENS + 2) < total)
4907 return true;
4908
4909 return false;
4910}
4911
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004912/*
4913 * For future optimizations:
4914 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4915 * reclaim.
4916 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004917static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004918{
Yu Zhao37397872022-09-18 02:00:03 -06004919 unsigned long nr_to_scan;
4920 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4921 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004922
Yu Zhaof8b57162022-12-21 21:19:05 -07004923 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004924 return 0;
4925
Yu Zhaoa5998f92022-12-21 21:19:02 -07004926 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004927 return nr_to_scan;
4928
4929 /* skip the aging path at the default priority */
4930 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004931 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004932
Yu Zhaoa5998f92022-12-21 21:19:02 -07004933 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004934 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004935}
4936
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004937static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004938{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004939 /* don't abort memcg reclaim to ensure fairness */
4940 if (!global_reclaim(sc))
4941 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004942
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004943 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004944}
4945
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004946static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004947{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004948 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004949 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004950 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004951 int swappiness = get_swappiness(lruvec, sc);
4952
4953 /* clean file pages are more likely to exist */
4954 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4955 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004956
Yu Zhao37397872022-09-18 02:00:03 -06004957 while (true) {
4958 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004959
Yu Zhaoa5998f92022-12-21 21:19:02 -07004960 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004961 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004962 break;
Yu Zhao37397872022-09-18 02:00:03 -06004963
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004964 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004965 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004966 break;
Yu Zhao37397872022-09-18 02:00:03 -06004967
4968 scanned += delta;
4969 if (scanned >= nr_to_scan)
4970 break;
4971
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004972 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004973 break;
4974
Yu Zhao37397872022-09-18 02:00:03 -06004975 cond_resched();
4976 }
4977
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004978 /* whether try_to_inc_max_seq() was successful */
4979 return nr_to_scan < 0;
4980}
4981
4982static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4983{
4984 bool success;
4985 unsigned long scanned = sc->nr_scanned;
4986 unsigned long reclaimed = sc->nr_reclaimed;
4987 int seg = lru_gen_memcg_seg(lruvec);
4988 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4989 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4990
4991 /* see the comment on MEMCG_NR_GENS */
4992 if (!lruvec_is_sizable(lruvec, sc))
4993 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4994
4995 mem_cgroup_calculate_protection(NULL, memcg);
4996
4997 if (mem_cgroup_below_min(memcg))
4998 return MEMCG_LRU_YOUNG;
4999
5000 if (mem_cgroup_below_low(memcg)) {
5001 /* see the comment on MEMCG_NR_GENS */
5002 if (seg != MEMCG_LRU_TAIL)
5003 return MEMCG_LRU_TAIL;
5004
5005 memcg_memory_event(memcg, MEMCG_LOW);
5006 }
5007
5008 success = try_to_shrink_lruvec(lruvec, sc);
5009
5010 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5011
5012 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5013 sc->nr_reclaimed - reclaimed);
5014
5015 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
5016 current->reclaim_state->reclaimed_slab = 0;
5017
5018 return success ? MEMCG_LRU_YOUNG : 0;
5019}
5020
5021#ifdef CONFIG_MEMCG
5022
5023static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5024{
Yu Zhaof7909cb2023-02-13 00:53:22 -07005025 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005026 int gen;
5027 int bin;
5028 int first_bin;
5029 struct lruvec *lruvec;
5030 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07005031 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005032 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005033 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5034
5035 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5036restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07005037 op = 0;
5038 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005039 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5040
5041 rcu_read_lock();
5042
5043 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5044 if (op)
5045 lru_gen_rotate_memcg(lruvec, op);
5046
5047 mem_cgroup_put(memcg);
5048
5049 lruvec = container_of(lrugen, struct lruvec, lrugen);
5050 memcg = lruvec_memcg(lruvec);
5051
5052 if (!mem_cgroup_tryget(memcg)) {
5053 op = 0;
5054 memcg = NULL;
5055 continue;
5056 }
5057
5058 rcu_read_unlock();
5059
5060 op = shrink_one(lruvec, sc);
5061
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005062 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005063
5064 if (sc->nr_reclaimed >= nr_to_reclaim)
5065 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005066 }
5067
5068 rcu_read_unlock();
5069
Yu Zhaof7909cb2023-02-13 00:53:22 -07005070 if (op)
5071 lru_gen_rotate_memcg(lruvec, op);
5072
5073 mem_cgroup_put(memcg);
5074
5075 if (sc->nr_reclaimed >= nr_to_reclaim)
5076 return;
5077
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005078 /* restart if raced with lru_gen_rotate_memcg() */
5079 if (gen != get_nulls_value(pos))
5080 goto restart;
5081
5082 /* try the rest of the bins of the current generation */
5083 bin = get_memcg_bin(bin + 1);
5084 if (bin != first_bin)
5085 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005086}
5087
5088static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5089{
5090 struct blk_plug plug;
5091
5092 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005093 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005094
5095 lru_add_drain();
5096
5097 blk_start_plug(&plug);
5098
Yu Zhaof8b57162022-12-21 21:19:05 -07005099 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005100
5101 if (try_to_shrink_lruvec(lruvec, sc))
5102 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5103
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005104 clear_mm_walk();
5105
Yu Zhao37397872022-09-18 02:00:03 -06005106 blk_finish_plug(&plug);
5107}
5108
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005109#else /* !CONFIG_MEMCG */
5110
5111static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5112{
5113 BUILD_BUG();
5114}
5115
5116static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5117{
5118 BUILD_BUG();
5119}
5120
5121#endif
5122
5123static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5124{
5125 int priority;
5126 unsigned long reclaimable;
5127 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5128
5129 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5130 return;
5131 /*
5132 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5133 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5134 * estimated reclaimed_to_scanned_ratio = inactive / total.
5135 */
5136 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5137 if (get_swappiness(lruvec, sc))
5138 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5139
5140 reclaimable /= MEMCG_NR_GENS;
5141
5142 /* round down reclaimable and round up sc->nr_to_reclaim */
5143 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5144
5145 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5146}
5147
5148static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5149{
5150 struct blk_plug plug;
5151 unsigned long reclaimed = sc->nr_reclaimed;
5152
5153 VM_WARN_ON_ONCE(!global_reclaim(sc));
5154
Yu Zhaof8b57162022-12-21 21:19:05 -07005155 /*
5156 * Unmapped clean pages are already prioritized. Scanning for more of
5157 * them is likely futile and can cause high reclaim latency when there
5158 * is a large number of memcgs.
5159 */
5160 if (!sc->may_writepage || !sc->may_unmap)
5161 goto done;
5162
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005163 lru_add_drain();
5164
5165 blk_start_plug(&plug);
5166
Yu Zhaof8b57162022-12-21 21:19:05 -07005167 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005168
5169 set_initial_priority(pgdat, sc);
5170
5171 if (current_is_kswapd())
5172 sc->nr_reclaimed = 0;
5173
5174 if (mem_cgroup_disabled())
5175 shrink_one(&pgdat->__lruvec, sc);
5176 else
5177 shrink_many(pgdat, sc);
5178
5179 if (current_is_kswapd())
5180 sc->nr_reclaimed += reclaimed;
5181
5182 clear_mm_walk();
5183
5184 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005185done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005186 /* kswapd should never fail */
5187 pgdat->kswapd_failures = 0;
5188}
5189
5190#ifdef CONFIG_MEMCG
5191void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5192{
5193 int seg;
5194 int old, new;
5195 int bin = prandom_u32_max(MEMCG_NR_BINS);
5196 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5197
5198 spin_lock(&pgdat->memcg_lru.lock);
5199
5200 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5201
5202 seg = 0;
5203 new = old = lruvec->lrugen.gen;
5204
5205 /* see the comment on MEMCG_NR_GENS */
5206 if (op == MEMCG_LRU_HEAD)
5207 seg = MEMCG_LRU_HEAD;
5208 else if (op == MEMCG_LRU_TAIL)
5209 seg = MEMCG_LRU_TAIL;
5210 else if (op == MEMCG_LRU_OLD)
5211 new = get_memcg_gen(pgdat->memcg_lru.seq);
5212 else if (op == MEMCG_LRU_YOUNG)
5213 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5214 else
5215 VM_WARN_ON_ONCE(true);
5216
5217 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5218
5219 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5220 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5221 else
5222 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5223
5224 pgdat->memcg_lru.nr_memcgs[old]--;
5225 pgdat->memcg_lru.nr_memcgs[new]++;
5226
5227 lruvec->lrugen.gen = new;
5228 WRITE_ONCE(lruvec->lrugen.seg, seg);
5229
5230 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5231 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5232
5233 spin_unlock(&pgdat->memcg_lru.lock);
5234}
5235#endif
5236
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005237/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005238 * state change
5239 ******************************************************************************/
5240
5241static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5242{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005243 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005244
5245 if (lrugen->enabled) {
5246 enum lru_list lru;
5247
5248 for_each_evictable_lru(lru) {
5249 if (!list_empty(&lruvec->lists[lru]))
5250 return false;
5251 }
5252 } else {
5253 int gen, type, zone;
5254
5255 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005256 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005257 return false;
5258 }
5259 }
5260
5261 return true;
5262}
5263
5264static bool fill_evictable(struct lruvec *lruvec)
5265{
5266 enum lru_list lru;
5267 int remaining = MAX_LRU_BATCH;
5268
5269 for_each_evictable_lru(lru) {
5270 int type = is_file_lru(lru);
5271 bool active = is_active_lru(lru);
5272 struct list_head *head = &lruvec->lists[lru];
5273
5274 while (!list_empty(head)) {
5275 bool success;
5276 struct page *page = lru_to_page(head);
5277
5278 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5279 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5280 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5281 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5282
5283 del_page_from_lru_list(page, lruvec);
5284 success = lru_gen_add_page(lruvec, page, false);
5285 VM_WARN_ON_ONCE(!success);
5286
5287 if (!--remaining)
5288 return false;
5289 }
5290 }
5291
5292 return true;
5293}
5294
5295static bool drain_evictable(struct lruvec *lruvec)
5296{
5297 int gen, type, zone;
5298 int remaining = MAX_LRU_BATCH;
5299
5300 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005301 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005302
5303 while (!list_empty(head)) {
5304 bool success;
5305 struct page *page = lru_to_page(head);
5306
5307 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5308 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5309 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5310 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5311
5312 success = lru_gen_del_page(lruvec, page, false);
5313 VM_WARN_ON_ONCE(!success);
5314 add_page_to_lru_list(page, lruvec);
5315
5316 if (!--remaining)
5317 return false;
5318 }
5319 }
5320
5321 return true;
5322}
5323
5324static void lru_gen_change_state(bool enabled)
5325{
5326 static DEFINE_MUTEX(state_mutex);
5327
5328 struct mem_cgroup *memcg;
5329
5330 cgroup_lock();
5331 cpus_read_lock();
5332 get_online_mems();
5333 mutex_lock(&state_mutex);
5334
5335 if (enabled == lru_gen_enabled())
5336 goto unlock;
5337
5338 if (enabled)
5339 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5340 else
5341 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5342
5343 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5344 do {
5345 int nid;
5346
5347 for_each_node(nid) {
5348 struct lruvec *lruvec = get_lruvec(memcg, nid);
5349
5350 if (!lruvec)
5351 continue;
5352
5353 spin_lock_irq(&lruvec->lru_lock);
5354
5355 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5356 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5357
5358 lruvec->lrugen.enabled = enabled;
5359
5360 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5361 spin_unlock_irq(&lruvec->lru_lock);
5362 cond_resched();
5363 spin_lock_irq(&lruvec->lru_lock);
5364 }
5365
5366 spin_unlock_irq(&lruvec->lru_lock);
5367 }
5368
5369 cond_resched();
5370 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5371unlock:
5372 mutex_unlock(&state_mutex);
5373 put_online_mems();
5374 cpus_read_unlock();
5375 cgroup_unlock();
5376}
5377
5378/******************************************************************************
5379 * sysfs interface
5380 ******************************************************************************/
5381
Yu Zhao430499c2022-09-18 02:00:08 -06005382static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5383{
5384 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5385}
5386
Yu Zhao642d9862022-09-18 02:00:10 -06005387/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005388static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5389 const char *buf, size_t len)
5390{
5391 unsigned int msecs;
5392
5393 if (kstrtouint(buf, 0, &msecs))
5394 return -EINVAL;
5395
5396 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5397
5398 return len;
5399}
5400
5401static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5402 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5403);
5404
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005405static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5406{
5407 unsigned int caps = 0;
5408
5409 if (get_cap(LRU_GEN_CORE))
5410 caps |= BIT(LRU_GEN_CORE);
5411
5412 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5413 caps |= BIT(LRU_GEN_MM_WALK);
5414
Juergen Gross23811792022-11-23 07:45:10 +01005415 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005416 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5417
5418 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5419}
5420
Yu Zhao642d9862022-09-18 02:00:10 -06005421/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005422static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5423 const char *buf, size_t len)
5424{
5425 int i;
5426 unsigned int caps;
5427
5428 if (tolower(*buf) == 'n')
5429 caps = 0;
5430 else if (tolower(*buf) == 'y')
5431 caps = -1;
5432 else if (kstrtouint(buf, 0, &caps))
5433 return -EINVAL;
5434
5435 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5436 bool enabled = caps & BIT(i);
5437
5438 if (i == LRU_GEN_CORE)
5439 lru_gen_change_state(enabled);
5440 else if (enabled)
5441 static_branch_enable(&lru_gen_caps[i]);
5442 else
5443 static_branch_disable(&lru_gen_caps[i]);
5444 }
5445
5446 return len;
5447}
5448
5449static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5450 enabled, 0644, show_enabled, store_enabled
5451);
5452
5453static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005454 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005455 &lru_gen_enabled_attr.attr,
5456 NULL
5457};
5458
5459static struct attribute_group lru_gen_attr_group = {
5460 .name = "lru_gen",
5461 .attrs = lru_gen_attrs,
5462};
5463
5464/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005465 * debugfs interface
5466 ******************************************************************************/
5467
5468static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5469{
5470 struct mem_cgroup *memcg;
5471 loff_t nr_to_skip = *pos;
5472
5473 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5474 if (!m->private)
5475 return ERR_PTR(-ENOMEM);
5476
5477 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5478 do {
5479 int nid;
5480
5481 for_each_node_state(nid, N_MEMORY) {
5482 if (!nr_to_skip--)
5483 return get_lruvec(memcg, nid);
5484 }
5485 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5486
5487 return NULL;
5488}
5489
5490static void lru_gen_seq_stop(struct seq_file *m, void *v)
5491{
5492 if (!IS_ERR_OR_NULL(v))
5493 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5494
5495 kvfree(m->private);
5496 m->private = NULL;
5497}
5498
5499static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5500{
5501 int nid = lruvec_pgdat(v)->node_id;
5502 struct mem_cgroup *memcg = lruvec_memcg(v);
5503
5504 ++*pos;
5505
5506 nid = next_memory_node(nid);
5507 if (nid == MAX_NUMNODES) {
5508 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5509 if (!memcg)
5510 return NULL;
5511
5512 nid = first_memory_node;
5513 }
5514
5515 return get_lruvec(memcg, nid);
5516}
5517
5518static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5519 unsigned long max_seq, unsigned long *min_seq,
5520 unsigned long seq)
5521{
5522 int i;
5523 int type, tier;
5524 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005525 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005526
5527 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5528 seq_printf(m, " %10d", tier);
5529 for (type = 0; type < ANON_AND_FILE; type++) {
5530 const char *s = " ";
5531 unsigned long n[3] = {};
5532
5533 if (seq == max_seq) {
5534 s = "RT ";
5535 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5536 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5537 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5538 s = "rep";
5539 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5540 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5541 if (tier)
5542 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5543 }
5544
5545 for (i = 0; i < 3; i++)
5546 seq_printf(m, " %10lu%c", n[i], s[i]);
5547 }
5548 seq_putc(m, '\n');
5549 }
5550
5551 seq_puts(m, " ");
5552 for (i = 0; i < NR_MM_STATS; i++) {
5553 const char *s = " ";
5554 unsigned long n = 0;
5555
5556 if (seq == max_seq && NR_HIST_GENS == 1) {
5557 s = "LOYNFA";
5558 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5559 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5560 s = "loynfa";
5561 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5562 }
5563
5564 seq_printf(m, " %10lu%c", n, s[i]);
5565 }
5566 seq_putc(m, '\n');
5567}
5568
Yu Zhao642d9862022-09-18 02:00:10 -06005569/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005570static int lru_gen_seq_show(struct seq_file *m, void *v)
5571{
5572 unsigned long seq;
5573 bool full = !debugfs_real_fops(m->file)->write;
5574 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005575 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005576 int nid = lruvec_pgdat(lruvec)->node_id;
5577 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5578 DEFINE_MAX_SEQ(lruvec);
5579 DEFINE_MIN_SEQ(lruvec);
5580
5581 if (nid == first_memory_node) {
5582 const char *path = memcg ? m->private : "";
5583
5584#ifdef CONFIG_MEMCG
5585 if (memcg)
5586 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5587#endif
5588 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5589 }
5590
5591 seq_printf(m, " node %5d\n", nid);
5592
5593 if (!full)
5594 seq = min_seq[LRU_GEN_ANON];
5595 else if (max_seq >= MAX_NR_GENS)
5596 seq = max_seq - MAX_NR_GENS + 1;
5597 else
5598 seq = 0;
5599
5600 for (; seq <= max_seq; seq++) {
5601 int type, zone;
5602 int gen = lru_gen_from_seq(seq);
5603 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5604
5605 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5606
5607 for (type = 0; type < ANON_AND_FILE; type++) {
5608 unsigned long size = 0;
5609 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5610
5611 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5612 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5613
5614 seq_printf(m, " %10lu%c", size, mark);
5615 }
5616
5617 seq_putc(m, '\n');
5618
5619 if (full)
5620 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5621 }
5622
5623 return 0;
5624}
5625
5626static const struct seq_operations lru_gen_seq_ops = {
5627 .start = lru_gen_seq_start,
5628 .stop = lru_gen_seq_stop,
5629 .next = lru_gen_seq_next,
5630 .show = lru_gen_seq_show,
5631};
5632
5633static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5634 bool can_swap, bool force_scan)
5635{
5636 DEFINE_MAX_SEQ(lruvec);
5637 DEFINE_MIN_SEQ(lruvec);
5638
5639 if (seq < max_seq)
5640 return 0;
5641
5642 if (seq > max_seq)
5643 return -EINVAL;
5644
5645 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5646 return -ERANGE;
5647
5648 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5649
5650 return 0;
5651}
5652
5653static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5654 int swappiness, unsigned long nr_to_reclaim)
5655{
5656 DEFINE_MAX_SEQ(lruvec);
5657
5658 if (seq + MIN_NR_GENS > max_seq)
5659 return -EINVAL;
5660
5661 sc->nr_reclaimed = 0;
5662
5663 while (!signal_pending(current)) {
5664 DEFINE_MIN_SEQ(lruvec);
5665
5666 if (seq < min_seq[!swappiness])
5667 return 0;
5668
5669 if (sc->nr_reclaimed >= nr_to_reclaim)
5670 return 0;
5671
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005672 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005673 return 0;
5674
5675 cond_resched();
5676 }
5677
5678 return -EINTR;
5679}
5680
5681static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5682 struct scan_control *sc, int swappiness, unsigned long opt)
5683{
5684 struct lruvec *lruvec;
5685 int err = -EINVAL;
5686 struct mem_cgroup *memcg = NULL;
5687
5688 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5689 return -EINVAL;
5690
5691 if (!mem_cgroup_disabled()) {
5692 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005693
Yu Zhao4983c522022-09-18 02:00:09 -06005694 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005695 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005696 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005697
Yu Zhao4983c522022-09-18 02:00:09 -06005698 rcu_read_unlock();
5699
5700 if (!memcg)
5701 return -EINVAL;
5702 }
5703
5704 if (memcg_id != mem_cgroup_id(memcg))
5705 goto done;
5706
5707 lruvec = get_lruvec(memcg, nid);
5708
5709 if (swappiness < 0)
5710 swappiness = get_swappiness(lruvec, sc);
5711 else if (swappiness > 200)
5712 goto done;
5713
5714 switch (cmd) {
5715 case '+':
5716 err = run_aging(lruvec, seq, sc, swappiness, opt);
5717 break;
5718 case '-':
5719 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5720 break;
5721 }
5722done:
5723 mem_cgroup_put(memcg);
5724
5725 return err;
5726}
5727
Yu Zhao642d9862022-09-18 02:00:10 -06005728/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005729static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5730 size_t len, loff_t *pos)
5731{
5732 void *buf;
5733 char *cur, *next;
5734 unsigned int flags;
5735 struct blk_plug plug;
5736 int err = -EINVAL;
5737 struct scan_control sc = {
5738 .may_writepage = true,
5739 .may_unmap = true,
5740 .may_swap = true,
5741 .reclaim_idx = MAX_NR_ZONES - 1,
5742 .gfp_mask = GFP_KERNEL,
5743 };
5744
5745 buf = kvmalloc(len + 1, GFP_KERNEL);
5746 if (!buf)
5747 return -ENOMEM;
5748
5749 if (copy_from_user(buf, src, len)) {
5750 kvfree(buf);
5751 return -EFAULT;
5752 }
5753
5754 set_task_reclaim_state(current, &sc.reclaim_state);
5755 flags = memalloc_noreclaim_save();
5756 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005757 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005758 err = -ENOMEM;
5759 goto done;
5760 }
5761
5762 next = buf;
5763 next[len] = '\0';
5764
5765 while ((cur = strsep(&next, ",;\n"))) {
5766 int n;
5767 int end;
5768 char cmd;
5769 unsigned int memcg_id;
5770 unsigned int nid;
5771 unsigned long seq;
5772 unsigned int swappiness = -1;
5773 unsigned long opt = -1;
5774
5775 cur = skip_spaces(cur);
5776 if (!*cur)
5777 continue;
5778
5779 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5780 &seq, &end, &swappiness, &end, &opt, &end);
5781 if (n < 4 || cur[end]) {
5782 err = -EINVAL;
5783 break;
5784 }
5785
5786 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5787 if (err)
5788 break;
5789 }
5790done:
5791 clear_mm_walk();
5792 blk_finish_plug(&plug);
5793 memalloc_noreclaim_restore(flags);
5794 set_task_reclaim_state(current, NULL);
5795
5796 kvfree(buf);
5797
5798 return err ? : len;
5799}
5800
5801static int lru_gen_seq_open(struct inode *inode, struct file *file)
5802{
5803 return seq_open(file, &lru_gen_seq_ops);
5804}
5805
5806static const struct file_operations lru_gen_rw_fops = {
5807 .open = lru_gen_seq_open,
5808 .read = seq_read,
5809 .write = lru_gen_seq_write,
5810 .llseek = seq_lseek,
5811 .release = seq_release,
5812};
5813
5814static const struct file_operations lru_gen_ro_fops = {
5815 .open = lru_gen_seq_open,
5816 .read = seq_read,
5817 .llseek = seq_lseek,
5818 .release = seq_release,
5819};
5820
5821/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005822 * initialization
5823 ******************************************************************************/
5824
5825void lru_gen_init_lruvec(struct lruvec *lruvec)
5826{
Yu Zhao430499c2022-09-18 02:00:08 -06005827 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005828 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005829 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005830
5831 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005832 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005833
Yu Zhao430499c2022-09-18 02:00:08 -06005834 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5835 lrugen->timestamps[i] = jiffies;
5836
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005837 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005838 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005839
5840 lruvec->mm_state.seq = MIN_NR_GENS;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005841}
5842
5843#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005844
5845void lru_gen_init_pgdat(struct pglist_data *pgdat)
5846{
5847 int i, j;
5848
5849 spin_lock_init(&pgdat->memcg_lru.lock);
5850
5851 for (i = 0; i < MEMCG_NR_GENS; i++) {
5852 for (j = 0; j < MEMCG_NR_BINS; j++)
5853 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5854 }
5855}
5856
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005857void lru_gen_init_memcg(struct mem_cgroup *memcg)
5858{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005859 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5860 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005861}
5862
5863void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5864{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005865 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005866 int nid;
5867
5868 for_each_node(nid) {
5869 struct lruvec *lruvec = get_lruvec(memcg, nid);
5870
5871 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5872 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005873
5874 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5875 bitmap_free(lruvec->mm_state.filters[i]);
5876 lruvec->mm_state.filters[i] = NULL;
5877 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005878 }
5879}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005880
5881void lru_gen_online_memcg(struct mem_cgroup *memcg)
5882{
5883 int gen;
5884 int nid;
5885 int bin = prandom_u32_max(MEMCG_NR_BINS);
5886
5887 for_each_node(nid) {
5888 struct pglist_data *pgdat = NODE_DATA(nid);
5889 struct lruvec *lruvec = get_lruvec(memcg, nid);
5890
5891 spin_lock(&pgdat->memcg_lru.lock);
5892
5893 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5894
5895 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5896
5897 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5898 pgdat->memcg_lru.nr_memcgs[gen]++;
5899
5900 lruvec->lrugen.gen = gen;
5901
5902 spin_unlock(&pgdat->memcg_lru.lock);
5903 }
5904}
5905
5906void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5907{
5908 int nid;
5909
5910 for_each_node(nid) {
5911 struct lruvec *lruvec = get_lruvec(memcg, nid);
5912
5913 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5914 }
5915}
5916
5917void lru_gen_release_memcg(struct mem_cgroup *memcg)
5918{
5919 int gen;
5920 int nid;
5921
5922 for_each_node(nid) {
5923 struct pglist_data *pgdat = NODE_DATA(nid);
5924 struct lruvec *lruvec = get_lruvec(memcg, nid);
5925
5926 spin_lock(&pgdat->memcg_lru.lock);
5927
5928 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5929
5930 gen = lruvec->lrugen.gen;
5931
5932 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5933 pgdat->memcg_lru.nr_memcgs[gen]--;
5934
5935 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5936 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5937
5938 spin_unlock(&pgdat->memcg_lru.lock);
5939 }
5940}
5941
5942#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005943
5944static int __init init_lru_gen(void)
5945{
5946 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5947 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5948
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005949 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5950 pr_err("lru_gen: failed to create sysfs group\n");
5951
Yu Zhao4983c522022-09-18 02:00:09 -06005952 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5953 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5954
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005955 return 0;
5956};
5957late_initcall(init_lru_gen);
5958
Yu Zhao37397872022-09-18 02:00:03 -06005959#else /* !CONFIG_LRU_GEN */
5960
5961static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5962{
5963}
5964
5965static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5966{
5967}
5968
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005969static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5970{
5971}
5972
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005973#endif /* CONFIG_LRU_GEN */
5974
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005975static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005976{
5977 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005978 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005979 unsigned long nr_to_scan;
5980 enum lru_list lru;
5981 unsigned long nr_reclaimed = 0;
5982 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005983 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005984 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005985 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005986
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005987 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06005988 lru_gen_shrink_lruvec(lruvec, sc);
5989 return;
5990 }
5991
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005992 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005993
Mel Gormane82e0562013-07-03 15:01:44 -07005994 /* Record the original scan target for proportional adjustments later */
5995 memcpy(targets, nr, sizeof(nr));
5996
Mel Gorman1a501902014-06-04 16:10:49 -07005997 /*
5998 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5999 * event that can occur when there is little memory pressure e.g.
6000 * multiple streaming readers/writers. Hence, we do not abort scanning
6001 * when the requested number of pages are reclaimed when scanning at
6002 * DEF_PRIORITY on the assumption that the fact we are direct
6003 * reclaiming implies that kswapd is not keeping up and it is best to
6004 * do a batch of work at once. For memcg reclaim one check is made to
6005 * abort proportional reclaim if either the file or anon lru has already
6006 * dropped to zero at the first pass.
6007 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006008 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6009 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07006010
Minchan Kima8962f62022-11-02 09:04:41 -07006011 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
6012 if (do_plug)
6013 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006014 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6015 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07006016 unsigned long nr_anon, nr_file, percentage;
6017 unsigned long nr_scanned;
6018
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006019 for_each_evictable_lru(lru) {
6020 if (nr[lru]) {
6021 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6022 nr[lru] -= nr_to_scan;
6023
6024 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07006025 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006026 }
6027 }
Mel Gormane82e0562013-07-03 15:01:44 -07006028
Michal Hockobd041732016-12-02 17:26:48 -08006029 cond_resched();
6030
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006031 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07006032 continue;
6033
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006034 /*
Mel Gormane82e0562013-07-03 15:01:44 -07006035 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07006036 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07006037 * proportionally what was requested by get_scan_count(). We
6038 * stop reclaiming one LRU and reduce the amount scanning
6039 * proportional to the original scan target.
6040 */
6041 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6042 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6043
Mel Gorman1a501902014-06-04 16:10:49 -07006044 /*
6045 * It's just vindictive to attack the larger once the smaller
6046 * has gone to zero. And given the way we stop scanning the
6047 * smaller below, this makes sure that we only make one nudge
6048 * towards proportionality once we've got nr_to_reclaim.
6049 */
6050 if (!nr_file || !nr_anon)
6051 break;
6052
Mel Gormane82e0562013-07-03 15:01:44 -07006053 if (nr_file > nr_anon) {
6054 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6055 targets[LRU_ACTIVE_ANON] + 1;
6056 lru = LRU_BASE;
6057 percentage = nr_anon * 100 / scan_target;
6058 } else {
6059 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6060 targets[LRU_ACTIVE_FILE] + 1;
6061 lru = LRU_FILE;
6062 percentage = nr_file * 100 / scan_target;
6063 }
6064
6065 /* Stop scanning the smaller of the LRU */
6066 nr[lru] = 0;
6067 nr[lru + LRU_ACTIVE] = 0;
6068
6069 /*
6070 * Recalculate the other LRU scan count based on its original
6071 * scan target and the percentage scanning already complete
6072 */
6073 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6074 nr_scanned = targets[lru] - nr[lru];
6075 nr[lru] = targets[lru] * (100 - percentage) / 100;
6076 nr[lru] -= min(nr[lru], nr_scanned);
6077
6078 lru += LRU_ACTIVE;
6079 nr_scanned = targets[lru] - nr[lru];
6080 nr[lru] = targets[lru] * (100 - percentage) / 100;
6081 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006082 }
Minchan Kima8962f62022-11-02 09:04:41 -07006083 if (do_plug)
6084 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006085 sc->nr_reclaimed += nr_reclaimed;
6086
6087 /*
6088 * Even if we did not try to evict anon pages at all, we want to
6089 * rebalance the anon lru active/inactive ratio.
6090 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006091 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6092 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006093 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6094 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006095}
6096
Mel Gorman23b9da52012-05-29 15:06:20 -07006097/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006098static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006099{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006100 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006101 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006102 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006103 return true;
6104
6105 return false;
6106}
6107
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006108/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006109 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6110 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6111 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006112 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006113 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006114 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006115static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006116 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006117 struct scan_control *sc)
6118{
6119 unsigned long pages_for_compaction;
6120 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006121 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006122
6123 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006124 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006125 return false;
6126
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006127 /*
6128 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6129 * number of pages that were scanned. This will return to the caller
6130 * with the risk reclaim/compaction and the resulting allocation attempt
6131 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6132 * allocations through requiring that the full LRU list has been scanned
6133 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6134 * scan, but that approximation was wrong, and there were corner cases
6135 * where always a non-zero amount of pages were scanned.
6136 */
6137 if (!nr_reclaimed)
6138 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006139
Mel Gorman3e7d3442011-01-13 15:45:56 -08006140 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006141 for (z = 0; z <= sc->reclaim_idx; z++) {
6142 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006143 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006144 continue;
6145
6146 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006147 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006148 case COMPACT_CONTINUE:
6149 return false;
6150 default:
6151 /* check next zone */
6152 ;
6153 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006154 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006155
6156 /*
6157 * If we have not reclaimed enough pages for compaction and the
6158 * inactive lists are large enough, continue reclaiming
6159 */
6160 pages_for_compaction = compact_gap(sc->order);
6161 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006162 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006163 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6164
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006165 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006166}
6167
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006168static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006169{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006170 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006171 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006172
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006173 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006174 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006175 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006176 unsigned long reclaimed;
6177 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006178 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006179
Xunlei Pange3336ca2020-09-04 16:35:27 -07006180 /*
6181 * This loop can become CPU-bound when target memcgs
6182 * aren't eligible for reclaim - either because they
6183 * don't have any reclaimable pages, or because their
6184 * memory is explicitly protected. Avoid soft lockups.
6185 */
6186 cond_resched();
6187
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006188 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6189 if (skip)
6190 continue;
6191
Chris Down45c7f7e2020-08-06 23:22:05 -07006192 mem_cgroup_calculate_protection(target_memcg, memcg);
6193
6194 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006195 /*
6196 * Hard protection.
6197 * If there is no reclaimable memory, OOM.
6198 */
6199 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006200 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006201 /*
6202 * Soft protection.
6203 * Respect the protection only as long as
6204 * there is an unprotected supply
6205 * of reclaimable memory from other cgroups.
6206 */
6207 if (!sc->memcg_low_reclaim) {
6208 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006209 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006210 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006211 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006212 }
6213
Johannes Weinerd2af3392019-11-30 17:55:43 -08006214 reclaimed = sc->nr_reclaimed;
6215 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006216
6217 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006218
Johannes Weinerd2af3392019-11-30 17:55:43 -08006219 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6220 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006221
Johannes Weinerd2af3392019-11-30 17:55:43 -08006222 /* Record the group's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006223 if (!sc->proactive)
6224 vmpressure(sc->gfp_mask, memcg, false,
6225 sc->nr_scanned - scanned,
6226 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006227
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006228 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6229}
6230
Liu Song6c9e09072020-01-30 22:14:08 -08006231static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006232{
6233 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006234 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006235 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006236 bool reclaimable = false;
6237
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006238 if (lru_gen_enabled() && global_reclaim(sc)) {
6239 lru_gen_shrink_node(pgdat, sc);
6240 return;
6241 }
6242
Johannes Weiner1b051172019-11-30 17:55:52 -08006243 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6244
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006245again:
6246 memset(&sc->nr, 0, sizeof(sc->nr));
6247
6248 nr_reclaimed = sc->nr_reclaimed;
6249 nr_scanned = sc->nr_scanned;
6250
Yu Zhao6d313442022-09-18 02:00:00 -06006251 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006252
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006253 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006254
Johannes Weinerd2af3392019-11-30 17:55:43 -08006255 if (reclaim_state) {
6256 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6257 reclaim_state->reclaimed_slab = 0;
6258 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006259
Johannes Weinerd2af3392019-11-30 17:55:43 -08006260 /* Record the subtree's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006261 if (!sc->proactive)
6262 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6263 sc->nr_scanned - nr_scanned,
6264 sc->nr_reclaimed - nr_reclaimed);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006265
6266 if (sc->nr_reclaimed - nr_reclaimed)
6267 reclaimable = true;
6268
6269 if (current_is_kswapd()) {
6270 /*
6271 * If reclaim is isolating dirty pages under writeback,
6272 * it implies that the long-lived page allocation rate
6273 * is exceeding the page laundering rate. Either the
6274 * global limits are not being effective at throttling
6275 * processes due to the page distribution throughout
6276 * zones or there is heavy usage of a slow backing
6277 * device. The only option is to throttle from reclaim
6278 * context which is not ideal as there is no guarantee
6279 * the dirtying process is throttled in the same way
6280 * balance_dirty_pages() manages.
6281 *
6282 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6283 * count the number of pages under pages flagged for
6284 * immediate reclaim and stall if any are encountered
6285 * in the nr_immediate check below.
6286 */
6287 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6288 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006289
Johannes Weinerd2af3392019-11-30 17:55:43 -08006290 /* Allow kswapd to start writing pages during reclaim.*/
6291 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6292 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006293
6294 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006295 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006296 * reclaim and under writeback (nr_immediate), it
6297 * implies that pages are cycling through the LRU
6298 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006299 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006300 if (sc->nr.immediate)
6301 congestion_wait(BLK_RW_ASYNC, HZ/10);
6302 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006303
Johannes Weinerd2af3392019-11-30 17:55:43 -08006304 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006305 * Tag a node/memcg as congested if all the dirty pages
6306 * scanned were backed by a congested BDI and
6307 * wait_iff_congested will stall.
6308 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006309 * Legacy memcg will stall in page writeback so avoid forcibly
6310 * stalling in wait_iff_congested().
6311 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006312 if ((current_is_kswapd() ||
6313 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006314 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006315 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006316
6317 /*
6318 * Stall direct reclaim for IO completions if underlying BDIs
6319 * and node is congested. Allow kswapd to continue until it
6320 * starts encountering unqueued dirty pages or cycling through
6321 * the LRU too quickly.
6322 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006323 if (!current_is_kswapd() && current_may_throttle() &&
6324 !sc->hibernation_mode &&
6325 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006326 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6327
6328 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6329 sc))
6330 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006331
Johannes Weinerc73322d2017-05-03 14:51:51 -07006332 /*
6333 * Kswapd gives up on balancing particular nodes after too
6334 * many failures to reclaim anything from them and goes to
6335 * sleep. On reclaim progress, reset the failure counter. A
6336 * successful direct reclaim run will revive a dormant kswapd.
6337 */
6338 if (reclaimable)
6339 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006340}
6341
Vlastimil Babka53853e22014-10-09 15:27:02 -07006342/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006343 * Returns true if compaction should go ahead for a costly-order request, or
6344 * the allocation would already succeed without compaction. Return false if we
6345 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006346 */
Mel Gorman4f588332016-07-28 15:46:38 -07006347static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006348{
Mel Gorman31483b62016-07-28 15:45:46 -07006349 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006350 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006351
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006352 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6353 if (suitable == COMPACT_SUCCESS)
6354 /* Allocation should succeed already. Don't reclaim. */
6355 return true;
6356 if (suitable == COMPACT_SKIPPED)
6357 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006358 return false;
6359
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006360 /*
6361 * Compaction is already possible, but it takes time to run and there
6362 * are potentially other callers using the pages just freed. So proceed
6363 * with reclaim to make a buffer of free pages available to give
6364 * compaction a reasonable chance of completing and allocating the page.
6365 * Note that we won't actually reclaim the whole buffer in one attempt
6366 * as the target watermark in should_continue_reclaim() is lower. But if
6367 * we are already above the high+gap watermark, don't reclaim at all.
6368 */
6369 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6370
6371 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006372}
6373
Linus Torvalds1da177e2005-04-16 15:20:36 -07006374/*
6375 * This is the direct reclaim path, for page-allocating processes. We only
6376 * try to reclaim pages from zones which will satisfy the caller's allocation
6377 * request.
6378 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006379 * If a zone is deemed to be full of pinned pages then just give it a light
6380 * scan then give up on it.
6381 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006382static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006383{
Mel Gormandd1a2392008-04-28 02:12:17 -07006384 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006385 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006386 unsigned long nr_soft_reclaimed;
6387 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006388 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006389 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006390
Mel Gormancc715d92012-03-21 16:34:00 -07006391 /*
6392 * If the number of buffer_heads in the machine exceeds the maximum
6393 * allowed level, force direct reclaim to scan the highmem zone as
6394 * highmem pages could be pinning lowmem pages storing buffer_heads
6395 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006396 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006397 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006398 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006399 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006400 }
Mel Gormancc715d92012-03-21 16:34:00 -07006401
Mel Gormand4debc62010-08-09 17:19:29 -07006402 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006403 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006404 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006405 * Take care memory controller reclaiming has small influence
6406 * to global LRU.
6407 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006408 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006409 if (!cpuset_zone_allowed(zone,
6410 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006411 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006412
Johannes Weiner0b064962014-08-06 16:06:12 -07006413 /*
6414 * If we already have plenty of memory free for
6415 * compaction in this zone, don't free any more.
6416 * Even though compaction is invoked for any
6417 * non-zero order, only frequent costly order
6418 * reclamation is disruptive enough to become a
6419 * noticeable problem, like transparent huge
6420 * page allocations.
6421 */
6422 if (IS_ENABLED(CONFIG_COMPACTION) &&
6423 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006424 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006425 sc->compaction_ready = true;
6426 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006427 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006428
Andrew Morton0608f432013-09-24 15:27:41 -07006429 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006430 * Shrink each node in the zonelist once. If the
6431 * zonelist is ordered by zone (not the default) then a
6432 * node may be shrunk multiple times but in that case
6433 * the user prefers lower zones being preserved.
6434 */
6435 if (zone->zone_pgdat == last_pgdat)
6436 continue;
6437
6438 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006439 * This steals pages from memory cgroups over softlimit
6440 * and returns the number of reclaimed pages and
6441 * scanned pages. This works for global memory pressure
6442 * and balancing, not for a memcg's limit.
6443 */
6444 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006445 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006446 sc->order, sc->gfp_mask,
6447 &nr_soft_scanned);
6448 sc->nr_reclaimed += nr_soft_reclaimed;
6449 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006450 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006451 }
Nick Piggin408d8542006-09-25 23:31:27 -07006452
Mel Gorman79dafcd2016-07-28 15:45:53 -07006453 /* See comment about same check for global reclaim above */
6454 if (zone->zone_pgdat == last_pgdat)
6455 continue;
6456 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006457 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006458 }
Mel Gormane0c23272011-10-31 17:09:33 -07006459
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006460 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006461 * Restore to original mask to avoid the impact on the caller if we
6462 * promoted it to __GFP_HIGHMEM.
6463 */
6464 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006465}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006466
Johannes Weinerb9107182019-11-30 17:55:59 -08006467static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006468{
Johannes Weinerb9107182019-11-30 17:55:59 -08006469 struct lruvec *target_lruvec;
6470 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006471
Yu Zhao37397872022-09-18 02:00:03 -06006472 if (lru_gen_enabled())
6473 return;
6474
Johannes Weinerb9107182019-11-30 17:55:59 -08006475 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006476 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6477 target_lruvec->refaults[0] = refaults;
6478 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6479 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006480}
6481
Linus Torvalds1da177e2005-04-16 15:20:36 -07006482/*
6483 * This is the main entry point to direct page reclaim.
6484 *
6485 * If a full scan of the inactive list fails to free enough memory then we
6486 * are "out of memory" and something needs to be killed.
6487 *
6488 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6489 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006490 * caller can't do much about. We kick the writeback threads and take explicit
6491 * naps in the hope that some of these pages can be written. But if the
6492 * allocating task holds filesystem locks which prevent writeout this might not
6493 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006494 *
6495 * returns: 0, if no pages reclaimed
6496 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006497 */
Mel Gormandac1d272008-04-28 02:12:12 -07006498static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006499 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006500{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006501 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006502 pg_data_t *last_pgdat;
6503 struct zoneref *z;
6504 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006505retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006506 delayacct_freepages_start();
6507
Johannes Weinerb5ead352019-11-30 17:55:40 -08006508 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006509 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006510
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006511 do {
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006512 if (!sc->proactive)
6513 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6514 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006515 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006516 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006517
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006518 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006519 break;
6520
6521 if (sc->compaction_ready)
6522 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006523
6524 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006525 * If we're getting trouble reclaiming, start doing
6526 * writepage even in laptop mode.
6527 */
6528 if (sc->priority < DEF_PRIORITY - 2)
6529 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006530 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006531
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006532 last_pgdat = NULL;
6533 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6534 sc->nodemask) {
6535 if (zone->zone_pgdat == last_pgdat)
6536 continue;
6537 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006538
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006539 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006540
6541 if (cgroup_reclaim(sc)) {
6542 struct lruvec *lruvec;
6543
6544 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6545 zone->zone_pgdat);
6546 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6547 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006548 }
6549
Keika Kobayashi873b4772008-07-25 01:48:52 -07006550 delayacct_freepages_end();
6551
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006552 if (sc->nr_reclaimed)
6553 return sc->nr_reclaimed;
6554
Mel Gorman0cee34f2012-01-12 17:19:49 -08006555 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006556 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006557 return 1;
6558
Johannes Weinerb91ac372019-11-30 17:56:02 -08006559 /*
6560 * We make inactive:active ratio decisions based on the node's
6561 * composition of memory, but a restrictive reclaim_idx or a
6562 * memory.low cgroup setting can exempt large amounts of
6563 * memory from reclaim. Neither of which are very common, so
6564 * instead of doing costly eligibility calculations of the
6565 * entire cgroup subtree up front, we assume the estimates are
6566 * good, and retry with forcible deactivation if that fails.
6567 */
6568 if (sc->skipped_deactivate) {
6569 sc->priority = initial_priority;
6570 sc->force_deactivate = 1;
6571 sc->skipped_deactivate = 0;
6572 goto retry;
6573 }
6574
Johannes Weiner241994ed2015-02-11 15:26:06 -08006575 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006576 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006577 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006578 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006579 sc->memcg_low_reclaim = 1;
6580 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006581 goto retry;
6582 }
6583
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006584 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006585}
6586
Johannes Weinerc73322d2017-05-03 14:51:51 -07006587static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006588{
6589 struct zone *zone;
6590 unsigned long pfmemalloc_reserve = 0;
6591 unsigned long free_pages = 0;
6592 int i;
6593 bool wmark_ok;
6594
Johannes Weinerc73322d2017-05-03 14:51:51 -07006595 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6596 return true;
6597
Mel Gorman55150612012-07-31 16:44:35 -07006598 for (i = 0; i <= ZONE_NORMAL; i++) {
6599 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006600 if (!managed_zone(zone))
6601 continue;
6602
6603 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006604 continue;
6605
Mel Gorman55150612012-07-31 16:44:35 -07006606 pfmemalloc_reserve += min_wmark_pages(zone);
6607 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6608 }
6609
Mel Gorman675becc2014-06-04 16:07:35 -07006610 /* If there are no reserves (unexpected config) then do not throttle */
6611 if (!pfmemalloc_reserve)
6612 return true;
6613
Mel Gorman55150612012-07-31 16:44:35 -07006614 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6615
6616 /* kswapd must be awake if processes are being throttled */
6617 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006618 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6619 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006620
Mel Gorman55150612012-07-31 16:44:35 -07006621 wake_up_interruptible(&pgdat->kswapd_wait);
6622 }
6623
6624 return wmark_ok;
6625}
6626
6627/*
6628 * Throttle direct reclaimers if backing storage is backed by the network
6629 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6630 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006631 * when the low watermark is reached.
6632 *
6633 * Returns true if a fatal signal was delivered during throttling. If this
6634 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006635 */
Mel Gorman50694c22012-11-26 16:29:48 -08006636static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006637 nodemask_t *nodemask)
6638{
Mel Gorman675becc2014-06-04 16:07:35 -07006639 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006640 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006641 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006642
6643 /*
6644 * Kernel threads should not be throttled as they may be indirectly
6645 * responsible for cleaning pages necessary for reclaim to make forward
6646 * progress. kjournald for example may enter direct reclaim while
6647 * committing a transaction where throttling it could forcing other
6648 * processes to block on log_wait_commit().
6649 */
6650 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006651 goto out;
6652
6653 /*
6654 * If a fatal signal is pending, this process should not throttle.
6655 * It should return quickly so it can exit and free its memory
6656 */
6657 if (fatal_signal_pending(current))
6658 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006659
Mel Gorman675becc2014-06-04 16:07:35 -07006660 /*
6661 * Check if the pfmemalloc reserves are ok by finding the first node
6662 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6663 * GFP_KERNEL will be required for allocating network buffers when
6664 * swapping over the network so ZONE_HIGHMEM is unusable.
6665 *
6666 * Throttling is based on the first usable node and throttled processes
6667 * wait on a queue until kswapd makes progress and wakes them. There
6668 * is an affinity then between processes waking up and where reclaim
6669 * progress has been made assuming the process wakes on the same node.
6670 * More importantly, processes running on remote nodes will not compete
6671 * for remote pfmemalloc reserves and processes on different nodes
6672 * should make reasonable progress.
6673 */
6674 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006675 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006676 if (zone_idx(zone) > ZONE_NORMAL)
6677 continue;
6678
6679 /* Throttle based on the first usable node */
6680 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006681 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006682 goto out;
6683 break;
6684 }
6685
6686 /* If no zone was usable by the allocation flags then do not throttle */
6687 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006688 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006689
Mel Gorman68243e72012-07-31 16:44:39 -07006690 /* Account for the throttling */
6691 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6692
Mel Gorman55150612012-07-31 16:44:35 -07006693 /*
6694 * If the caller cannot enter the filesystem, it's possible that it
6695 * is due to the caller holding an FS lock or performing a journal
6696 * transaction in the case of a filesystem like ext[3|4]. In this case,
6697 * it is not safe to block on pfmemalloc_wait as kswapd could be
6698 * blocked waiting on the same lock. Instead, throttle for up to a
6699 * second before continuing.
6700 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006701 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006702 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006703 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006704 else
6705 /* Throttle until kswapd wakes the process */
6706 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6707 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006708
Mel Gorman50694c22012-11-26 16:29:48 -08006709 if (fatal_signal_pending(current))
6710 return true;
6711
6712out:
6713 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006714}
6715
Mel Gormandac1d272008-04-28 02:12:12 -07006716unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006717 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006718{
Mel Gorman33906bc2010-08-09 17:19:16 -07006719 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006720 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006721 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006722 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006723 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006724 .order = order,
6725 .nodemask = nodemask,
6726 .priority = DEF_PRIORITY,
6727 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006728 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006729 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006730 };
6731
Mel Gorman55150612012-07-31 16:44:35 -07006732 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006733 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6734 * Confirm they are large enough for max values.
6735 */
6736 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6737 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6738 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6739
6740 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006741 * Do not enter reclaim if fatal signal was delivered while throttled.
6742 * 1 is returned so that the page allocator does not OOM kill at this
6743 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006744 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006745 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006746 return 1;
6747
Andrew Morton1732d2b012019-07-16 16:26:15 -07006748 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006749 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006750
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006751 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006752
6753 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006754 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006755
6756 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006757}
6758
Andrew Mortonc255a452012-07-31 16:43:02 -07006759#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006760
Michal Hockod2e5fb92019-08-30 16:04:50 -07006761/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006762unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006763 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006764 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006765 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006766{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006767 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006768 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006769 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006770 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006771 .may_writepage = !laptop_mode,
6772 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006773 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006774 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006775 };
Ying Han0ae5e892011-05-26 16:25:25 -07006776
Michal Hockod2e5fb92019-08-30 16:04:50 -07006777 WARN_ON_ONCE(!current->reclaim_state);
6778
Balbir Singh4e416952009-09-23 15:56:39 -07006779 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6780 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006781
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006782 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006783 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006784
Balbir Singh4e416952009-09-23 15:56:39 -07006785 /*
6786 * NOTE: Although we can get the priority field, using it
6787 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006788 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006789 * will pick up pages from other mem cgroup's as well. We hack
6790 * the priority and make it zero.
6791 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006792 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006793
6794 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6795
Ying Han0ae5e892011-05-26 16:25:25 -07006796 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006797
Balbir Singh4e416952009-09-23 15:56:39 -07006798 return sc.nr_reclaimed;
6799}
6800
Johannes Weiner72835c82012-01-12 17:18:32 -08006801unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006802 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006803 gfp_t gfp_mask,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006804 unsigned int reclaim_options)
Balbir Singh66e17072008-02-07 00:13:56 -08006805{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006806 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006807 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006808 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006809 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006810 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006811 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006812 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006813 .target_mem_cgroup = memcg,
6814 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006815 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006816 .may_unmap = 1,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006817 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6818 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
Ying Hana09ed5e2011-05-24 17:12:26 -07006819 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006820 /*
6821 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6822 * equal pressure on all the nodes. This is based on the assumption that
6823 * the reclaim does not bail out early.
6824 */
6825 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006826
Andrew Morton1732d2b012019-07-16 16:26:15 -07006827 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006828 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006829 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006830
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006831 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006832
Vlastimil Babka499118e2017-05-08 15:59:50 -07006833 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006834 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006835 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006836
6837 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006838}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006839EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006840#endif
6841
Yu Zhao37397872022-09-18 02:00:03 -06006842static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006843{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006844 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006845 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006846
Yu Zhao37397872022-09-18 02:00:03 -06006847 if (lru_gen_enabled()) {
6848 lru_gen_age_node(pgdat, sc);
6849 return;
6850 }
6851
Dave Hansen2f368a92021-09-02 14:59:23 -07006852 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006853 return;
6854
Johannes Weinerb91ac372019-11-30 17:56:02 -08006855 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6856 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6857 return;
6858
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006859 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6860 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006861 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6862 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6863 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006864 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6865 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006866}
6867
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006868static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006869{
6870 int i;
6871 struct zone *zone;
6872
6873 /*
6874 * Check for watermark boosts top-down as the higher zones
6875 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006876 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006877 * start prematurely when there is no boosting and a lower
6878 * zone is balanced.
6879 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006880 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006881 zone = pgdat->node_zones + i;
6882 if (!managed_zone(zone))
6883 continue;
6884
6885 if (zone->watermark_boost)
6886 return true;
6887 }
6888
6889 return false;
6890}
6891
Mel Gormane716f2e2017-05-03 14:53:45 -07006892/*
6893 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006894 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006895 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006896static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006897{
Mel Gormane716f2e2017-05-03 14:53:45 -07006898 int i;
6899 unsigned long mark = -1;
6900 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006901
Mel Gorman1c308442018-12-28 00:35:52 -08006902 /*
6903 * Check watermarks bottom-up as lower zones are more likely to
6904 * meet watermarks.
6905 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006906 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006907 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006908
Mel Gormane716f2e2017-05-03 14:53:45 -07006909 if (!managed_zone(zone))
6910 continue;
6911
6912 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006913 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006914 return true;
6915 }
6916
6917 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006918 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006919 * need balancing by definition. This can happen if a zone-restricted
6920 * allocation tries to wake a remote kswapd.
6921 */
6922 if (mark == -1)
6923 return true;
6924
6925 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006926}
6927
Mel Gorman631b6e02017-05-03 14:53:41 -07006928/* Clear pgdat state for congested, dirty or under writeback. */
6929static void clear_pgdat_congested(pg_data_t *pgdat)
6930{
Johannes Weiner1b051172019-11-30 17:55:52 -08006931 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6932
6933 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006934 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6935 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6936}
6937
Mel Gorman1741c872011-01-13 15:46:21 -08006938/*
Mel Gorman55150612012-07-31 16:44:35 -07006939 * Prepare kswapd for sleeping. This verifies that there are no processes
6940 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6941 *
6942 * Returns true if kswapd is ready to sleep
6943 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006944static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6945 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006946{
Mel Gorman55150612012-07-31 16:44:35 -07006947 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006948 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006949 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006950 * race between when kswapd checks the watermarks and a process gets
6951 * throttled. There is also a potential race if processes get
6952 * throttled, kswapd wakes, a large process exits thereby balancing the
6953 * zones, which causes kswapd to exit balance_pgdat() before reaching
6954 * the wake up checks. If kswapd is going to sleep, no process should
6955 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6956 * the wake up is premature, processes will wake kswapd and get
6957 * throttled again. The difference from wake ups in balance_pgdat() is
6958 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006959 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006960 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6961 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006962
Johannes Weinerc73322d2017-05-03 14:51:51 -07006963 /* Hopeless node, leave it to direct reclaim */
6964 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6965 return true;
6966
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006967 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006968 clear_pgdat_congested(pgdat);
6969 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006970 }
6971
Shantanu Goel333b0a42017-05-03 14:53:38 -07006972 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006973}
6974
Linus Torvalds1da177e2005-04-16 15:20:36 -07006975/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006976 * kswapd shrinks a node of pages that are at or below the highest usable
6977 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006978 *
6979 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006980 * reclaim or if the lack of progress was due to pages under writeback.
6981 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006982 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006983static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006984 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006985{
Mel Gorman1d82de62016-07-28 15:45:43 -07006986 struct zone *zone;
6987 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006988
Mel Gorman1d82de62016-07-28 15:45:43 -07006989 /* Reclaim a number of pages proportional to the number of zones */
6990 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006991 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006992 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006993 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006994 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006995
Mel Gorman1d82de62016-07-28 15:45:43 -07006996 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006997 }
6998
Mel Gorman1d82de62016-07-28 15:45:43 -07006999 /*
7000 * Historically care was taken to put equal pressure on all zones but
7001 * now pressure is applied based on node LRU order.
7002 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007003 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007004
7005 /*
7006 * Fragmentation may mean that the system cannot be rebalanced for
7007 * high-order allocations. If twice the allocation size has been
7008 * reclaimed then recheck watermarks only at order-0 to prevent
7009 * excessive reclaim. Assume that a process requested a high-order
7010 * can direct reclaim/compact.
7011 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07007012 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07007013 sc->order = 0;
7014
Mel Gormanb8e83b92013-07-03 15:01:45 -07007015 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07007016}
7017
Mel Gormanc49c2c42021-06-28 19:42:21 -07007018/* Page allocator PCP high watermark is lowered if reclaim is active. */
7019static inline void
7020update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7021{
7022 int i;
7023 struct zone *zone;
7024
7025 for (i = 0; i <= highest_zoneidx; i++) {
7026 zone = pgdat->node_zones + i;
7027
7028 if (!managed_zone(zone))
7029 continue;
7030
7031 if (active)
7032 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7033 else
7034 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7035 }
7036}
7037
7038static inline void
7039set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7040{
7041 update_reclaim_active(pgdat, highest_zoneidx, true);
7042}
7043
7044static inline void
7045clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7046{
7047 update_reclaim_active(pgdat, highest_zoneidx, false);
7048}
7049
Mel Gorman75485362013-07-03 15:01:42 -07007050/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007051 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7052 * that are eligible for use by the caller until at least one zone is
7053 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007054 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007055 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007056 *
7057 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007058 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007059 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007060 * or lower is eligible for reclaim until at least one usable zone is
7061 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007062 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007063static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007064{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007065 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007066 unsigned long nr_soft_reclaimed;
7067 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007068 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007069 unsigned long nr_boost_reclaim;
7070 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7071 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007072 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007073 struct scan_control sc = {
7074 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007075 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007076 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007077 };
Omar Sandoval93781322018-06-07 17:07:02 -07007078
Andrew Morton1732d2b012019-07-16 16:26:15 -07007079 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007080 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007081 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007082
Christoph Lameterf8891e52006-06-30 01:55:45 -07007083 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007084
Mel Gorman1c308442018-12-28 00:35:52 -08007085 /*
7086 * Account for the reclaim boost. Note that the zone boost is left in
7087 * place so that parallel allocations that are near the watermark will
7088 * stall or direct reclaim until kswapd is finished.
7089 */
7090 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007091 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007092 zone = pgdat->node_zones + i;
7093 if (!managed_zone(zone))
7094 continue;
7095
7096 nr_boost_reclaim += zone->watermark_boost;
7097 zone_boosts[i] = zone->watermark_boost;
7098 }
7099 boosted = nr_boost_reclaim;
7100
7101restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007102 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007103 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007104 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007105 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007106 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007107 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007108 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007109
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007110 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007111
Mel Gorman86c79f62016-07-28 15:45:59 -07007112 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007113 * If the number of buffer_heads exceeds the maximum allowed
7114 * then consider reclaiming from all zones. This has a dual
7115 * purpose -- on 64-bit systems it is expected that
7116 * buffer_heads are stripped during active rotation. On 32-bit
7117 * systems, highmem pages can pin lowmem memory and shrinking
7118 * buffers can relieve lowmem pressure. Reclaim may still not
7119 * go ahead if all eligible zones for the original allocation
7120 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007121 */
7122 if (buffer_heads_over_limit) {
7123 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7124 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007125 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007126 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007127
Mel Gorman970a39a2016-07-28 15:46:35 -07007128 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007129 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007130 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007131 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007132
Mel Gorman86c79f62016-07-28 15:45:59 -07007133 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007134 * If the pgdat is imbalanced then ignore boosting and preserve
7135 * the watermarks for a later time and restart. Note that the
7136 * zone watermarks will be still reset at the end of balancing
7137 * on the grounds that the normal reclaim should be enough to
7138 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007139 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007140 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007141 if (!balanced && nr_boost_reclaim) {
7142 nr_boost_reclaim = 0;
7143 goto restart;
7144 }
7145
7146 /*
7147 * If boosting is not active then only reclaim if there are no
7148 * eligible zones. Note that sc.reclaim_idx is not used as
7149 * buffer_heads_over_limit may have adjusted it.
7150 */
7151 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007152 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007153
Mel Gorman1c308442018-12-28 00:35:52 -08007154 /* Limit the priority of boosting to avoid reclaim writeback */
7155 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7156 raise_priority = false;
7157
7158 /*
7159 * Do not writeback or swap pages for boosted reclaim. The
7160 * intent is to relieve pressure not issue sub-optimal IO
7161 * from reclaim context. If no pages are reclaimed, the
7162 * reclaim will be aborted.
7163 */
7164 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7165 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007166
Linus Torvalds1da177e2005-04-16 15:20:36 -07007167 /*
Yu Zhao37397872022-09-18 02:00:03 -06007168 * Do some background aging, to give pages a chance to be
7169 * referenced before reclaiming. All pages are rotated
7170 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007171 */
Yu Zhao37397872022-09-18 02:00:03 -06007172 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007173
7174 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007175 * If we're getting trouble reclaiming, start doing writepage
7176 * even in laptop mode.
7177 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007178 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007179 sc.may_writepage = 1;
7180
Mel Gorman1d82de62016-07-28 15:45:43 -07007181 /* Call soft limit reclaim before calling shrink_node. */
7182 sc.nr_scanned = 0;
7183 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007184 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007185 sc.gfp_mask, &nr_soft_scanned);
7186 sc.nr_reclaimed += nr_soft_reclaimed;
7187
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007188 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007189 * There should be no need to raise the scanning priority if
7190 * enough pages are already being scanned that that high
7191 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007192 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007193 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007194 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007195
7196 /*
7197 * If the low watermark is met there is no need for processes
7198 * to be throttled on pfmemalloc_wait as they should not be
7199 * able to safely make forward progress. Wake them
7200 */
7201 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007202 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007203 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007204
Mel Gormanb8e83b92013-07-03 15:01:45 -07007205 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007206 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007207 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007208 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007209 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007210 break;
7211
7212 /*
7213 * Raise priority if scanning rate is too low or there was no
7214 * progress in reclaiming pages
7215 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007216 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007217 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7218
7219 /*
7220 * If reclaim made no progress for a boost, stop reclaim as
7221 * IO cannot be queued and it could be an infinite loop in
7222 * extreme circumstances.
7223 */
7224 if (nr_boost_reclaim && !nr_reclaimed)
7225 break;
7226
Johannes Weinerc73322d2017-05-03 14:51:51 -07007227 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007228 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007229 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007230
Johannes Weinerc73322d2017-05-03 14:51:51 -07007231 if (!sc.nr_reclaimed)
7232 pgdat->kswapd_failures++;
7233
Mel Gormanb8e83b92013-07-03 15:01:45 -07007234out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007235 clear_reclaim_active(pgdat, highest_zoneidx);
7236
Mel Gorman1c308442018-12-28 00:35:52 -08007237 /* If reclaim was boosted, account for the reclaim done in this pass */
7238 if (boosted) {
7239 unsigned long flags;
7240
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007241 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007242 if (!zone_boosts[i])
7243 continue;
7244
7245 /* Increments are under the zone lock */
7246 zone = pgdat->node_zones + i;
7247 spin_lock_irqsave(&zone->lock, flags);
7248 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7249 spin_unlock_irqrestore(&zone->lock, flags);
7250 }
7251
7252 /*
7253 * As there is now likely space, wakeup kcompact to defragment
7254 * pageblocks.
7255 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007256 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007257 }
7258
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007259 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007260 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007261 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007262 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007263
Mel Gorman0abdee22011-01-13 15:46:22 -08007264 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007265 * Return the order kswapd stopped reclaiming at as
7266 * prepare_kswapd_sleep() takes it into account. If another caller
7267 * entered the allocator slow path while kswapd was awake, order will
7268 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007269 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007270 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007271}
7272
Mel Gormane716f2e2017-05-03 14:53:45 -07007273/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007274 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7275 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7276 * not a valid index then either kswapd runs for first time or kswapd couldn't
7277 * sleep after previous reclaim attempt (node is still unbalanced). In that
7278 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007279 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007280static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7281 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007282{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007283 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007284
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007285 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007286}
7287
Mel Gorman38087d92016-07-28 15:45:49 -07007288static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007289 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007290{
7291 long remaining = 0;
7292 DEFINE_WAIT(wait);
7293
7294 if (freezing(current) || kthread_should_stop())
7295 return;
7296
7297 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7298
Shantanu Goel333b0a42017-05-03 14:53:38 -07007299 /*
7300 * Try to sleep for a short interval. Note that kcompactd will only be
7301 * woken if it is possible to sleep for a short interval. This is
7302 * deliberate on the assumption that if reclaim cannot keep an
7303 * eligible zone balanced that it's also unlikely that compaction will
7304 * succeed.
7305 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007306 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007307 /*
7308 * Compaction records what page blocks it recently failed to
7309 * isolate pages from and skips them in the future scanning.
7310 * When kswapd is going to sleep, it is reasonable to assume
7311 * that pages and compaction may succeed so reset the cache.
7312 */
7313 reset_isolation_suitable(pgdat);
7314
7315 /*
7316 * We have freed the memory, now we should compact it to make
7317 * allocation of the requested order possible.
7318 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007319 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007320
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007321 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007322
7323 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007324 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007325 * order. The values will either be from a wakeup request or
7326 * the previous request that slept prematurely.
7327 */
7328 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007329 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7330 kswapd_highest_zoneidx(pgdat,
7331 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007332
7333 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7334 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007335 }
7336
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007337 finish_wait(&pgdat->kswapd_wait, &wait);
7338 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7339 }
7340
7341 /*
7342 * After a short sleep, check if it was a premature sleep. If not, then
7343 * go fully to sleep until explicitly woken up.
7344 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007345 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007346 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007347 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7348
7349 /*
7350 * vmstat counters are not perfectly accurate and the estimated
7351 * value for counters such as NR_FREE_PAGES can deviate from the
7352 * true value by nr_online_cpus * threshold. To avoid the zone
7353 * watermarks being breached while under pressure, we reduce the
7354 * per-cpu vmstat threshold while kswapd is awake and restore
7355 * them before going back to sleep.
7356 */
7357 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007358
7359 if (!kthread_should_stop())
7360 schedule();
7361
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007362 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7363 } else {
7364 if (remaining)
7365 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7366 else
7367 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7368 }
7369 finish_wait(&pgdat->kswapd_wait, &wait);
7370}
7371
Linus Torvalds1da177e2005-04-16 15:20:36 -07007372/*
7373 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007374 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007375 *
7376 * This basically trickles out pages so that we have _some_
7377 * free memory available even if there is no other activity
7378 * that frees anything up. This is needed for things like routing
7379 * etc, where we otherwise might have all activity going on in
7380 * asynchronous contexts that cannot page things out.
7381 *
7382 * If there are applications that are active memory-allocators
7383 * (most normal use), this basically shouldn't matter.
7384 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307385int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007386{
Mel Gormane716f2e2017-05-03 14:53:45 -07007387 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007388 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007389 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007390 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307391 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007392
Rusty Russell174596a2009-01-01 10:12:29 +10307393 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007394 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007395
7396 /*
7397 * Tell the memory management that we're a "memory allocator",
7398 * and that if we need more memory we should get access to it
7399 * regardless (see "__alloc_pages()"). "kswapd" should
7400 * never get caught in the normal page freeing logic.
7401 *
7402 * (Kswapd normally doesn't need memory anyway, but sometimes
7403 * you need a small amount of memory in order to be able to
7404 * page out something else, and this flag essentially protects
7405 * us from recursively trying to free more memory as we're
7406 * trying to free the first piece of memory in the first place).
7407 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007408 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007409 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007410
Qian Cai5644e1fb2020-04-01 21:10:12 -07007411 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007412 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007413 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007414 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007415
Qian Cai5644e1fb2020-04-01 21:10:12 -07007416 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007417 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7418 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007419
Mel Gorman38087d92016-07-28 15:45:49 -07007420kswapd_try_sleep:
7421 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007422 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007423
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007424 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007425 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007426 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7427 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007428 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007429 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007430
David Rientjes8fe23e02009-12-14 17:58:33 -08007431 ret = try_to_freeze();
7432 if (kthread_should_stop())
7433 break;
7434
7435 /*
7436 * We can speed up thawing tasks if we don't call balance_pgdat
7437 * after returning from the refrigerator
7438 */
Mel Gorman38087d92016-07-28 15:45:49 -07007439 if (ret)
7440 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007441
Mel Gorman38087d92016-07-28 15:45:49 -07007442 /*
7443 * Reclaim begins at the requested order but if a high-order
7444 * reclaim fails then kswapd falls back to reclaiming for
7445 * order-0. If that happens, kswapd will consider sleeping
7446 * for the order it finished reclaiming at (reclaim_order)
7447 * but kcompactd is woken to compact for the original
7448 * request (alloc_order).
7449 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007450 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007451 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007452 reclaim_order = balance_pgdat(pgdat, alloc_order,
7453 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007454 if (reclaim_order < alloc_order)
7455 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007456 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007457
Johannes Weiner71abdc12014-06-06 14:35:35 -07007458 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007459
Linus Torvalds1da177e2005-04-16 15:20:36 -07007460 return 0;
7461}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307462EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007463
7464/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007465 * A zone is low on free memory or too fragmented for high-order memory. If
7466 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7467 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7468 * has failed or is not needed, still wake up kcompactd if only compaction is
7469 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007470 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007471void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007472 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007473{
7474 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007475 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007476
Mel Gorman6aa303d2016-09-01 16:14:55 -07007477 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007478 return;
7479
David Rientjes5ecd9d42018-04-05 16:25:16 -07007480 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007481 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007482
Qian Cai5644e1fb2020-04-01 21:10:12 -07007483 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007484 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007485
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007486 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7487 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007488
7489 if (READ_ONCE(pgdat->kswapd_order) < order)
7490 WRITE_ONCE(pgdat->kswapd_order, order);
7491
Con Kolivas8d0986e2005-09-13 01:25:07 -07007492 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007493 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007494
David Rientjes5ecd9d42018-04-05 16:25:16 -07007495 /* Hopeless node, leave it to direct reclaim if possible */
7496 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007497 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7498 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007499 /*
7500 * There may be plenty of free memory available, but it's too
7501 * fragmented for high-order allocations. Wake up kcompactd
7502 * and rely on compaction_suitable() to determine if it's
7503 * needed. If it fails, it will defer subsequent attempts to
7504 * ratelimit its work.
7505 */
7506 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007507 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007508 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007509 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007510
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007511 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007512 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007513 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007514}
7515
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007516#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007517/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007518 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007519 * freed pages.
7520 *
7521 * Rather than trying to age LRUs the aim is to preserve the overall
7522 * LRU order by reclaiming preferentially
7523 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007524 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007525unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007526{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007527 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007528 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007529 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007530 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007531 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007532 .may_writepage = 1,
7533 .may_unmap = 1,
7534 .may_swap = 1,
7535 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007536 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007537 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007538 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007539 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007540
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007541 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007542 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007543 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007544
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007545 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007546
Andrew Morton1732d2b012019-07-16 16:26:15 -07007547 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007548 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007549 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007550
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007551 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007552}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007553#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007554
Yasunori Goto3218ae12006-06-27 02:53:33 -07007555/*
7556 * This kswapd start function will be called by init and node-hot-add.
7557 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7558 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007559void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007560{
7561 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307562 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007563
7564 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007565 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007566
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307567 trace_android_vh_kswapd_per_node(nid, &skip, true);
7568 if (skip)
7569 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007570 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7571 if (IS_ERR(pgdat->kswapd)) {
7572 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007573 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007574 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007575 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007576 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007577}
7578
David Rientjes8fe23e02009-12-14 17:58:33 -08007579/*
Jiang Liud8adde12012-07-11 14:01:52 -07007580 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007581 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007582 */
7583void kswapd_stop(int nid)
7584{
7585 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307586 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007587
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307588 trace_android_vh_kswapd_per_node(nid, &skip, false);
7589 if (skip)
7590 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007591 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007592 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007593 NODE_DATA(nid)->kswapd = NULL;
7594 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007595}
7596
Linus Torvalds1da177e2005-04-16 15:20:36 -07007597static int __init kswapd_init(void)
7598{
Wei Yang6b700b52020-04-01 21:10:09 -07007599 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007600
Linus Torvalds1da177e2005-04-16 15:20:36 -07007601 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007602 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007603 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007604 return 0;
7605}
7606
7607module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007608
7609#ifdef CONFIG_NUMA
7610/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007611 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007612 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007613 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007614 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007615 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007616int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007617
Dave Hansen51998362021-02-24 12:09:15 -08007618/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007619 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007620 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7621 * a zone.
7622 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007623#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007624
Christoph Lameter9eeff232006-01-18 17:42:31 -08007625/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007626 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007627 * occur.
7628 */
7629int sysctl_min_unmapped_ratio = 1;
7630
7631/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007632 * If the number of slab pages in a zone grows beyond this percentage then
7633 * slab reclaim needs to occur.
7634 */
7635int sysctl_min_slab_ratio = 5;
7636
Mel Gorman11fb9982016-07-28 15:46:20 -07007637static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007638{
Mel Gorman11fb9982016-07-28 15:46:20 -07007639 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7640 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7641 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007642
7643 /*
7644 * It's possible for there to be more file mapped pages than
7645 * accounted for by the pages on the file LRU lists because
7646 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7647 */
7648 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7649}
7650
7651/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007652static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007653{
Alexandru Moised031a152015-11-05 18:48:08 -08007654 unsigned long nr_pagecache_reclaimable;
7655 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007656
7657 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007658 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007659 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007660 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007661 * a better estimate
7662 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007663 if (node_reclaim_mode & RECLAIM_UNMAP)
7664 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007665 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007666 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007667
7668 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007669 if (!(node_reclaim_mode & RECLAIM_WRITE))
7670 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007671
7672 /* Watch for any possible underflows due to delta */
7673 if (unlikely(delta > nr_pagecache_reclaimable))
7674 delta = nr_pagecache_reclaimable;
7675
7676 return nr_pagecache_reclaimable - delta;
7677}
7678
Christoph Lameter0ff38492006-09-25 23:31:52 -07007679/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007680 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007681 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007682static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007683{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007684 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007685 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007686 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007687 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007688 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007689 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007690 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007691 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007692 .priority = NODE_RECLAIM_PRIORITY,
7693 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7694 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007695 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007696 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007697 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007698 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007699
Yafang Shao132bb8c2019-05-13 17:17:53 -07007700 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7701 sc.gfp_mask);
7702
Christoph Lameter9eeff232006-01-18 17:42:31 -08007703 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007704 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007705 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007706 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007707 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007708 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007709 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007710 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007711 noreclaim_flag = memalloc_noreclaim_save();
7712 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007713 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007714
Mel Gormana5f5f912016-07-28 15:46:32 -07007715 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007716 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007717 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007718 * priorities until we have enough memory freed.
7719 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007720 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007721 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007722 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007723 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007724
Andrew Morton1732d2b012019-07-16 16:26:15 -07007725 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007726 current->flags &= ~PF_SWAPWRITE;
7727 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007728 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007729 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007730
7731 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7732
Rik van Riela79311c2009-01-06 14:40:01 -08007733 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007734}
Andrew Morton179e9632006-03-22 00:08:18 -08007735
Mel Gormana5f5f912016-07-28 15:46:32 -07007736int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007737{
David Rientjesd773ed62007-10-16 23:26:01 -07007738 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007739
7740 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007741 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007742 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007743 *
Christoph Lameter96146342006-07-03 00:24:13 -07007744 * A small portion of unmapped file backed pages is needed for
7745 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007746 * thrown out if the node is overallocated. So we do not reclaim
7747 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007748 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007749 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007750 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007751 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7752 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007753 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007754
7755 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007756 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007757 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007758 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007759 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007760
7761 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007762 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007763 * have associated processors. This will favor the local processor
7764 * over remote processors and spread off node memory allocations
7765 * as wide as possible.
7766 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007767 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7768 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007769
Mel Gormana5f5f912016-07-28 15:46:32 -07007770 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7771 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007772
Mel Gormana5f5f912016-07-28 15:46:32 -07007773 ret = __node_reclaim(pgdat, gfp_mask, order);
7774 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007775
Mel Gorman24cf725182009-06-16 15:33:23 -07007776 if (!ret)
7777 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7778
David Rientjesd773ed62007-10-16 23:26:01 -07007779 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007780}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007781#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007782
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007783/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007784 * check_move_unevictable_pages - check pages for evictability and move to
7785 * appropriate zone lru list
7786 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007787 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007788 * Checks pages for evictability, if an evictable page is in the unevictable
7789 * lru list, moves it to the appropriate evictable lru list. This function
7790 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007791 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007792void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007793{
Alex Shi6168d0d2020-12-15 12:34:29 -08007794 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007795 int pgscanned = 0;
7796 int pgrescued = 0;
7797 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007798
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007799 for (i = 0; i < pvec->nr; i++) {
7800 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007801 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007802
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007803 if (PageTransTail(page))
7804 continue;
7805
7806 nr_pages = thp_nr_pages(page);
7807 pgscanned += nr_pages;
7808
Alex Shid25b5bd2020-12-15 12:34:16 -08007809 /* block memcg migration during page moving between lru */
7810 if (!TestClearPageLRU(page))
7811 continue;
7812
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007813 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007814 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007815 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007816 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007817 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007818 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007819 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007820 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007821 }
Hugh Dickins24513262012-01-20 14:34:21 -08007822
Alex Shi6168d0d2020-12-15 12:34:29 -08007823 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007824 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7825 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007826 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007827 } else if (pgscanned) {
7828 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007829 }
Hugh Dickins850465792012-01-20 14:34:19 -08007830}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007831EXPORT_SYMBOL_GPL(check_move_unevictable_pages);